google map api v3 reverse geocoding not working ?

721 views
Skip to first unread message

mark

unread,
Oct 26, 2011, 10:12:18 AM10/26/11
to Google Maps JavaScript API v3
I have a form which uses the google maps api to geocode an address and
insert the lat / lng into form fields. When they submit this form it
takes them to a second form where a marker is placed on the google map
and the user then drags this marker onto their roof. At this point
using the reverse geocoding and jquery autocomplete i would like to
update the lat / lng fileds but for some reason the reverse geocoding
doesnt seem to be initializing. Any ideas ?

Example link = http://www.rayoflightes.com/gmaps/form1.php

var geocoder;
var map;
var marker;

function initialize(){
//MAP
var latlng = new google.maps.LatLng(41.659,-4.714);
var options = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};

map = new google.maps.Map(document.getElementById("map_canvas"),
options);

//GEOCODER
geocoder = new google.maps.Geocoder();

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

}

$(document).ready(function() {

initialize();

$(function() {
$("#address").autocomplete({
//This bit uses the geocoder to fetch address values
source: function(request, response) {
geocoder.geocode( {'address': request.term },
function(results, status) {
response($.map(results, function(item) {
return {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
}
}));
})
},
//This bit is executed upon selection of an address
select: function(event, ui) {
$("#latitude").val(ui.item.latitude);
$("#longitude").val(ui.item.longitude);
var location = new google.maps.LatLng(ui.item.latitude,
ui.item.longitude);
marker.setPosition(location);
map.setCenter(location);
}
});
});

//Add listener to marker for reverse geocoding
google.maps.event.addListener(marker, 'drag', function() {
geocoder.geocode({'latLng': marker.getPosition()},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
}
}
});
});

});

mark

unread,
Oct 26, 2011, 3:00:13 PM10/26/11
to google-map...@googlegroups.com
Sorry i have posted the wrong code above.

Should be

//Useful links:
// http://code.google.com/apis/maps/documentation/javascript/reference.html#Marker
// http://code.google.com/apis/maps/documentation/javascript/services.html#Geocoding
// http://jqueryui.com/demos/autocomplete/#remote-with-cache

     
var geocoder;
var map;
var marker;
   
function initialize(){
//MAP
  var latlng = new google.maps.LatLng(41.659,-4.714);
  var options = {
    zoom: 16,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.SATELLITE
  };
       
  map = new google.maps.Map(document.getElementById("map_canvas"), options);

      
  //GEOCODER
  geocoder = new google.maps.Geocoder();
       
  myMarker = new google.maps.Marker({

    map: map,
    draggable: true
  });
               
}
       
$(document).ready(function() {
        
  initialize();

      var address = document.getElementById("address").value;

    geocoder.geocode( { 'address': address}, function(results, status) {

      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var myMarker = new google.maps.Marker({
            map: map,
            draggable: true,
            position: results[0].geometry.location,
        });





    map.setZoom(18);
   
    /* When geocoding "fails", see if it was because of over quota error: */
            } else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
              wait = true;
              setTimeout("wait = false", 1000);

            } else {
              alert("Geocode was not successful for the following reason: " + status);
            }
    });


google.maps.event.addListener(myMarker, 'dragend', function(evt){
    document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});

google.maps.event.addListener(myMarker, 'dragstart', function(evt){
    document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
});

 
});

Rossko

unread,
Oct 26, 2011, 3:26:36 PM10/26/11
to Google Maps JavaScript API v3
> Example link =http://www.rayoflightes.com/gmaps/form1.php

I get javascript errors, do you not get that?

In http://www.rayoflightes.com/gmaps/form2.php, the variable
'myMarker' is ctreated in local scope within your geocoder callback,
but you try to use it when defining listeners (a) outside the scope
and (b) before the geocoder results return

Your 'map' variable isn't explicitly declared, which may cause cross-
browser quirks.

mark

unread,
Oct 26, 2011, 5:00:10 PM10/26/11
to google-map...@googlegroups.com
I have eventually got this working, baring in mind that im a complete javascript beginner how does my code look. Are there any errors or anything i should be worried about ?

Example link is the same http://rayoflightes.com/gmaps/form1.php

var geocoder = new google.maps.Geocoder();

function geocodePosition(pos) {
  geocoder.geocode({
    latLng: pos
  }, function(responses) {
    if (responses && responses.length > 0) {
      updateMarkerAddress(responses[0].formatted_address);
    } else {
      updateMarkerAddress('Cannot determine address at this location.');
    }
  });
}

function updateMarkerStatus(str) {
  document.getElementById('markerStatus').innerHTML = str;
}

function updateMarkerPosition(latLng) {
  document.getElementById('latitude').value = [
    latLng.lat()
  ];
  document.getElementById('longitude').value = [
    latLng.lng()
  ];
}



function initialize() {


          var address = document.getElementById("address").value;

  var latLng = new google.maps.LatLng(-34.397, 150.644);
  var map = new google.maps.Map(document.getElementById('mapCanvas'), {
    zoom: 12,
    center: latLng,
    mapTypeId: google.maps.MapTypeId.SATELLITE
  });
   
    geocoder.geocode( { 'address': address}, function(results, status) {

      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,

            draggable: true,
            position: results[0].geometry.location,
        });

    map.setZoom(18);

  // Update current position info.
  updateMarkerPosition(latLng);
  geocodePosition(latLng);
 
  // Add dragging event listeners.
  google.maps.event.addListener(marker, 'dragstart', function() {
    updateMarkerAddress('Dragging...');
  });
 
  google.maps.event.addListener(marker, 'drag', function() {
    updateMarkerStatus('Dragging...');
    updateMarkerPosition(marker.getPosition());
  });
 
  google.maps.event.addListener(marker, 'dragend', function() {
    updateMarkerStatus('Drag ended');
    geocodePosition(marker.getPosition());

  });
   
    /* When geocoding "fails", see if it was because of over quota error: */
            } else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
              wait = true;
              setTimeout("wait = false", 1000);

            } else {
              alert("Geocode was not successful for the following reason: " + status);
            }
    });
 

}

// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
Reply all
Reply to author
Forward
0 new messages