Search code examples
javascriptasynchronousgeocodinglatitude-longitudegoogle-geocoder

Google's GeoCode Convert City, STATE into Latitude Longitude


The following code works asynchronously. I only have it set up to convert a City, State into latitude and longitude. That value is then alerted.

How can I write a function that actually returns these values?

var map;
var geocoder;

function initialize() {

  geocoder = new GClientGeocoder();

}

// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
function addAddressToMap(response) {
  //map.clearOverlays();
  if (!response || response.Status.code != 200) {
    alert("Sorry, we were unable to geocode that address");
  } else {
    place = response.Placemark[0];

    latitude = place.Point.coordinates[0];
    longitude = place.Point.coordinates[1];

    alert("Latitude " + latitude + " Longitude" + longitude);

  }
}

function showLocation(address) {
  geocoder.getLocations(address, addAddressToMap);
}

Solution

  • Return those values from the callback won't doing anything. If you want to store those values somewhere just do it in the callback. You could do it in your current code if you just declare latitude and longitude at the top where declare the map and geocoder vars.