_google_map.js.erb 6.4 KB

var geocoder;
var map;
var marker;
var center;
var move = true;
var previousCenter;
var mapZoom = 15;
var delay_autocomplete = 500;

function pointToAddress(latlng) {
  $('location-fields').addClassName("loading");

  if (latlng == null)
    return;

  geocoder.geocode( {'latLng': latlng}, function(results, status) {
    if (status != google.maps.GeocoderStatus.OK) {
      alert("<%=_("Address not found, reason:")%>" + statusErrorMessage(status));
      return;
    }

    var place = results[0];

    $('location-fields').removeClassName("loading");

    var position = marker.getPosition();
    $('profile_data_lat').value = position.lat();
    $('profile_data_lng').value = position.lng();

    form = jQuery('#location-form')[0];
    form.lat = marker.getPosition().lat();
    form.lng = marker.getPosition().lng();

    var components_len = place.address_components.size();
    if (components_len < 2)
      return;

    var country_code = "";
    var state = "";
    var city = "";
    var zip_code = "";
    var route = "";
    var number = "";
    var sublocality = "";
    var address = "";

    var i;
    var has_postal_code = false;
    for (i=0; i < components_len; i++) {
      type = place.address_components[i].types[0];
      if (type == 'postal_code')
        has_postal_code = true;
    }

    for (i=0; i < components_len; i++) {
      type = place.address_components[i].types[0];
      value = place.address_components[i];

      if (type == 'country')
        country_code = value.short_name;
      else if (type == 'administrative_area_level_1')
        state = value.long_name;
      else if (type == 'locality')
        city = value.long_name;
      else if (type == 'postal_code')
        zip_code = value.short_name;
      if (has_postal_code) {
        if (type == "route")
          route = value.long_name;
        else if (type == "street_number")
          number = value.short_name;
        else if (type == 'sublocality')
          sublocality = value.long_name;
      }
    }

    // build address
    if (route) {
      address = route;
      if (number)
       address = address + ', ' + number;
      if (sublocality && sublocality != city)
       address = address + ', ' + sublocality;
    }

    if (country_code)
      $('profile_data_country').value = country_code;
    if (state)
      $('profile_data_state').value = state;
    if (city)
      $('profile_data_city').value = city;
    if (zip_code)
      $('profile_data_zip_code').value = zip_code;
    if (address)
      $('profile_data_address').value = address;

    map.setCenter(marker.getPosition());
  });
}

function addressToPoint() {
  $('location-fields').addClassName("loading");

  var country_option = $('profile_data_country').value;
  var address = $('profile_data_address').value + ", " + $('profile_data_zip_code').value + ", "
    + $('profile_data_city').value+ ", " + $('profile_data_state').value + ", " + country_option;

  if (geocoder) {
   geocoder.geocode({ 'address': address}, function(results, status) {
     if (status == google.maps.GeocoderStatus.OK) {
       map.setCenter(results[0].geometry.location);
       marker.setPosition(results[0].geometry.location);
       pointToAddress(marker.getPosition());

       $('profile_data_lat').value = results[0].geometry.location.lat();
       $('profile_data_lng').value = results[0].geometry.location.lng();
       $('location-fields').removeClassName("loading");
       enable_save();
     } else {
       $('location-fields').removeClassName("loading");
       alert('<%=_("Address not found, reason:")%>' + statusErrorMessage(status));
     }
   });
  }

  return false;
}

function statusErrorMessage(status)
{
  var translated_status = '';

  if (google.maps.GeocoderStatus.INVALID_REQUEST == status)
    translated_status = '<%= _('Invalid address') %>';
  else if (google.maps.GeocoderStatus.REQUEST_DENIED == status)
    translated_status = '<%= _('Request denied') %>';
  else if (google.maps.GeocoderStatus.OVER_QUERY_LIMIT == status)
    translated_status = '<%= _('Over query limit') %>';
  else if (google.maps.GeocoderStatus.ZERO_RESULTS == status)
    translated_status = "<%= _('Address do not exist') %>";

  return translated_status;
}

function initializeMap() {
  geocoder = new google.maps.Geocoder();

  var lat = <%= profile.lat || 'false' %>;
  var lng = <%= profile.lng || 'false' %>;
  if ( !(lat && lng) ) {
    lat = -15.7605361485013;
    lng = -47.933349609375;
  }

  var center = new google.maps.LatLng(lat,lng);;
  map = new google.maps.Map(document.getElementById("location-map"), {
    zoom: mapZoom,
    center: center,
    mapTypeId: google.maps.MapTypeId.HYBRID
  });

  marker = new google.maps.Marker({
    position: center,
    map: map,
    draggable: true
  });

  google.maps.event.addListener(marker, "dragend", function() {
    move = false;
    pointToAddress(marker.getPosition());
    map.setCenter(marker.getPosition());
    enable_save();
  });

}

jQuery.noConflict();
jQuery(document).ready(function () {

  initializeMap();

  jQuery.widget( "custom.catcomplete",jQuery.ui.autocomplete, {
    _renderMenu: function( ul, items ) {
      var self = this,
      currentCategory = "";
      jQuery.each( items, function( index, item ) {
        if ( item.category != currentCategory ) {
          ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
          currentCategory = item.category;
        }
        self._renderItem( ul, item );
      });
    }
  });

  jQuery("#profile_data_city").catcomplete({
    source: "../maps/search_city",
    minLength: 3,
    delay: delay_autocomplete,
    select: function( event, ui ) { $('profile_data_state').value =( ui.item ? ui.item.category : this.value ); }
  });

  jQuery("#profile_data_state").autocomplete({
    source: "../maps/search_state",
    minLength: 3,
    delay: delay_autocomplete
  });

  jQuery("#profile_data_city").keyup(function(){
    disable_save();
  });
  jQuery("#profile_data_state").keyup(function(){
    disable_save();
  });
  jQuery("#profile_data_country").change(function(){
    disable_save();
  });

});

function disable_save()
{
  jQuery('input[type="submit"]').attr("disabled", "true");
  jQuery('input[type="submit"]').val('<%=_("Localize before save")%>');
  jQuery('input[type="submit"]').addClass('disabled');
}
function enable_save()
{
  jQuery('input[type="submit"]').removeAttr("disabled");
  jQuery('input[type="submit"]').val('<%=_("Save")%>');
  jQuery('input[type="submit"]').removeClass('disabled');
}