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

186,781

Solution 1

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> 

Solution 2

I hope this can help someone in the future.

You can use the Google Geocoding API, as said before, I had to do some work with this recently, I hope this helps:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
        <script type="text/javascript">
        function initialize() {
        var address = (document.getElementById('my-address'));
        var autocomplete = new google.maps.places.Autocomplete(address);
        autocomplete.setTypes(['geocode']);
        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            var place = autocomplete.getPlace();
            if (!place.geometry) {
                return;
            }

        var address = '';
        if (place.address_components) {
            address = [
                (place.address_components[0] && place.address_components[0].short_name || ''),
                (place.address_components[1] && place.address_components[1].short_name || ''),
                (place.address_components[2] && place.address_components[2].short_name || '')
                ].join(' ');
        }
      });
}
function codeAddress() {
    geocoder = new google.maps.Geocoder();
    var address = document.getElementById("my-address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {

      alert("Latitude: "+results[0].geometry.location.lat());
      alert("Longitude: "+results[0].geometry.location.lng());
      } 

      else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
google.maps.event.addDomListener(window, 'load', initialize);

        </script>
    </head>
    <body>
        <input type="text" id="my-address">
        <button id="getCords" onClick="codeAddress();">getLat&Long</button>
    </body>
</html>

Now this has also an autocomlpete function which you can see in the code, it fetches the address from the input and gets auto completed by the API while typing.

Once you have your address hit the button and you get your results via alert as required. Please also note this uses the latest API and it loads the 'places' library (when calling the API uses the 'libraries' parameter).

Hope this helps, and read the documentation for more information, cheers.

Edit #1: Fiddle

Solution 3

http://maps.googleapis.com/maps/api/geocode/OUTPUT?address=YOUR_LOCATION&sensor=true

OUTPUT = json or xml;

for detail information about google map api go through url:

http://code.google.com/apis/maps/documentation/geocoding/index.html

Hope this will help

Solution 4

The below is the code that i used. It's working perfectly.

var geo = new google.maps.Geocoder;
geo.geocode({'address':address},function(results, status){
    if (status == google.maps.GeocoderStatus.OK) {              
        var myLatLng = results[0].geometry.location;

        // Add some code to work with myLatLng              

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

Hope this will help.

Solution 5

I hope this will be more useful for future scope contain auto complete Google API feature with latitude and longitude

var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();  

Complete View

<!DOCTYPE html>
<html>
    <head>
    <title>Place Autocomplete With Latitude & Longitude </title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
#pac-input {
    background-color: #fff;
    padding: 0 11px 0 13px;
    width: 400px;
    font-family: Roboto;
    font-size: 15px;
    font-weight: 300;
    text-overflow: ellipsis;
}
#pac-input:focus {
    border-color: #4d90fe;
    margin-left: -1px;
    padding-left: 14px;  /* Regular padding-left + 1. */
    width: 401px;
}
}
</style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
    <script>


  function initialize() {
        var address = (document.getElementById('pac-input'));
        var autocomplete = new google.maps.places.Autocomplete(address);
        autocomplete.setTypes(['geocode']);
        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            var place = autocomplete.getPlace();
            if (!place.geometry) {
                return;
            }

        var address = '';
        if (place.address_components) {
            address = [
                (place.address_components[0] && place.address_components[0].short_name || ''),
                (place.address_components[1] && place.address_components[1].short_name || ''),
                (place.address_components[2] && place.address_components[2].short_name || '')
                ].join(' ');
        }
        /*********************************************************************/
        /* var address contain your autocomplete address *********************/
        /* place.geometry.location.lat() && place.geometry.location.lat() ****/
        /* will be used for current address latitude and longitude************/
        /*********************************************************************/
        document.getElementById('lat').innerHTML = place.geometry.location.lat();
        document.getElementById('long').innerHTML = place.geometry.location.lng();
        });
  }

   google.maps.event.addDomListener(window, 'load', initialize);

    </script>
    </head>
    <body>
<input id="pac-input" class="controls" type="text"
        placeholder="Enter a location">
<div id="lat"></div>
<div id="long"></div>
</body>
</html>
Share:
186,781
Chandra
Author by

Chandra

Updated on July 09, 2022

Comments

  • Chandra
    Chandra almost 2 years

    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?

  • King Friday
    King Friday about 10 years
    yes thanks! the lat() lng() is perfect because seems to change from request to request randomly with actual properties like "k" and "A" or someother weird ones like that for lat lng. You are coool.
  • Supertecnoboff
    Supertecnoboff about 9 years
    This is awesome! Just one question, does this require an API key?
  • Supertecnoboff
    Supertecnoboff about 9 years
    Does this require an API key?
  • Ariel
    Ariel about 9 years
    @Supertecnoboff works without an API key but you won't get the benefits. Check what Google says about the: API Key. Also I made a: Fiddle.
  • serge
    serge over 8 years
    what is the difference sensor true or false?
  • Ankit Sharma
    Ankit Sharma over 8 years
    The sensor param is no longer used or required. stackoverflow.com/questions/8616764/…
  • Maria Ines Parnisari
    Maria Ines Parnisari over 7 years
    It should be results[0].geometry.location.lat() and results[0].geometry.location.lng()
  • 3 rules
    3 rules over 5 years
    @Ariel I have used your code but in my application using same code getting DENIED but in fiddle it is working fine why?
  • Ariel
    Ariel over 5 years
    @3rules I don't know why it did not work for you. I just tried it locally and had no problem at all, just uploaded a pastebin so you can copy&paste this html: pastebin.com/BQSZwm6D. Copy & paste that into a new html and open it, it worked for me. Open a new question in SO exposing the relevant code and give me the link to look into it. Cheers!
  • 3 rules
    3 rules over 5 years
    @Ariel yes it's working fine in jsfiddle but not in my application...I will test again and come back...
  • Marthinus Strydom
    Marthinus Strydom almost 4 years
    How can I add COUNTRY and ADMINISTRATIVE REGION to this solution? I want country, administrative region (state), city, lat and long.