Get latitude and longitude based on location name with Google Autocomplete API

Chandra picture Chandra · Aug 16, 2010 · Viewed 174.1k times · Source

I have a textbox in my page which gets a location name and button with text getLat&Long. Now on clicking my button I have to show an alert of latitude and longitude of the location in the textbox. Any suggestion?

Answer

RedBlueThing picture RedBlueThing · Aug 16, 2010

You can use the Google Geocoder service in the Google Maps API to convert from your location name to a latitude and longitude. So you need some code like:

var geocoder = new google.maps.Geocoder();
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK)
  {
      // do something with the geocoded result
      //
      // results[0].geometry.location.latitude
      // results[0].geometry.location.longitude
  }
});

Update

Are you including the v3 javascript API?

<script type="text/javascript"
     src="http://maps.google.com/maps/api/js?sensor=set_to_true_or_false">
</script>