Home Coding & Programming Get Latitude and Longitude Based on Location Name with Google Autocomplete API

Get Latitude and Longitude Based on Location Name with Google Autocomplete API

If you are searching for a way to create a textbox in your webpage which can get latitude and longitude based on an entered location name, then you are at the right place. The code i will be providing here has Google Autocomplete API which means that while users are entering the letters of the location in the textbox, suggestions will be provided to help ease the search.

I know how important this is to some developers which made me provide two separate codes that will give same result but with separate information. In case you require more assistant from me, you can always use the comment box below and i will be very glad to assist you.

So to create a textbox in your webpage which can get the latitude and longitude of any keyed in location name, go through the guide below;

  • Copy and paste the code below in between the <head> and </head> of your webpage code.
<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>

As you can see in the code above, there is an autocomplete function, it fetches the address from the input and gets auto completed by the API while typing.

  • Next, in between the <body> and </body> tag copy and paste the code below.
<input type="text" id="my-address">
        <button id="getCords" onClick="codeAddress();">Get Lat & Long</button>

The code above displays the text box where users are required to enter the location name they wish to get its latitude and longitude. Once the users have entered location and probably gotten the address, all they need to do hit the Get Lat & Long button and they will get the results as requested.

Note: The above uses the latest API and it loads the ‘places’ library (when calling the API uses the ‘libraries’ parameter).

The second code i will be providing as i mentioned gives a result that is somewhat different from that above. The result will look like as shown in the image below. This will also fetch the address from the input and auto complete by the API while typing.

So to add this code instead of the one provided above, go through the guide below;

  • Copy and paste the code below in between <head> and </head> of your webpage code.
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>

<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
  • Next copy the code below and paste between <body> and </body> of your webpage code.
<textarea placeholder="Enter Area name to populate Latitude and Longitude" name="address" onFocus="initializeAutocomplete()" id="locality" ></textarea><br>

<input type="text" name="city" id="city" placeholder="City" value="" ><br>
<input type="text" name="latitude" id="latitude" placeholder="Latitude" value="" ><br>
<input type="text" name="longitude" id="longitude" placeholder="Longitude" value="" ><br>
<input type="text" name="place_id" id="location_id" placeholder="Location Ids" value="" ><br>

<script type="text/javascript">
  function initializeAutocomplete(){
    var input = document.getElementById('locality');
    // var options = {
    //   types: ['(regions)'],
    //   componentRestrictions: {country: "IN"}
    // };
    var options = {}

    var autocomplete = new google.maps.places.Autocomplete(input, options);

    google.maps.event.addListener(autocomplete, 'place_changed', function() {
      var place = autocomplete.getPlace();
      var lat = place.geometry.location.lat();
      var lng = place.geometry.location.lng();
      var placeId = place.place_id;
      // to set city name, using the locality param
      var componentForm = {
        locality: 'short_name',
      };
      for (var i = 0; i < place.address_components.length; i++) {
        var addressType = place.address_components[i].types[0];
        if (componentForm[addressType]) {
          var val = place.address_components[i][componentForm[addressType]];
          document.getElementById("city").value = val;
        }
      }
      document.getElementById("latitude").value = lat;
      document.getElementById("longitude").value = lng;
      document.getElementById("location_id").value = placeId;
    });
  }
</script>

Finally, copy the code below and paste just after the </html> closing tag

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//maps.googleapis.com/maps/api/js?libraries=places&key=API KEY"></script>


<script src="https://fonts.googleapis.com/css?family=Roboto:300,400,500></script>

Please ensure you replace API KEY as highlighted in RED in the code above with your Google API key.

That’s it! Make use any of the guide and you should have a text box displayed in your webpage where users can simply enter a location and get the latitude and longitude of that location. Remember that each of the codes already have a Google Autocomplete API which makes searching easy and faster.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

List of All JavaScript Arithmetic Operators With Examples

JavaScript offers several operators to help us work with numbers. All these operators are binary operators, which means they operate on two operands. The operands...

How to Find a Website’s RSS Feed’s URL

Having access to the RSS feed of a website gives you the opportunity to stay up-to-date on everything that website publishes. Whether that’s a...

Laravel: String data, right truncated: 1406 Data too long for column (SOLVED)

I was working on a project today when i ran into the error message "String data, right truncated: 1406 Data too long for column...

How to Enable or Disable Chrome’s Autofill on Android Devices

Storing your login details and other information in Chrome and/or your Google Account isn’t as secure as using an encrypted password manager, but it’s...

Recent Comments