Get Latitude and Longitude of a location with Google maps api and Jquery

by  
Share:
Get Latitude and Longitude of a location with Google maps api and Jquery

If you work with google map API getting Latitude and Longitude of a location/pincode can come in very handy. User can give a valid location/pincode and its Latitude and Longitude will be generated accordingly using Google maps api. In this tutorial I will explain how to get the Latitude and Longitude of a location with Google maps api and Jquery.

View Demo

Setup a form and attach jquery and Gmap library.

Let us first setup a form first, in which the user will provide a location name or a pincode.

<form id="user-location" method="post" action="#">
  <label for="address">Enter Address or Zip Code:</label>
  <input type="text" class="textbox" id="address" name="address" />
  <button id="submit" type="submit" class="submit">Submit</button>
</form>

We have to attach the jquery and google maps api library. The script.js has the code that binds the event when the user submits the form.
<script src="jquery-1.9.0.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>

<!-- Contain the script binding the form submit event -->
<script src="scripts.js"></script>

Get latitude and longitude with google map api.

To get the latitude and longitude we have to use this function provided by the google API.

function GoogleGeocode() {
  geocoder = new google.maps.Geocoder();
  this.geocode = function(address, callbackFunction) {
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          var result = {};
          result.latitude = results[0].geometry.location.lat();
          result.longitude = results[0].geometry.location.lng();
          callbackFunction(result);
        } else {
          alert("Geocode was not successful for the following reason: " + status);
          callbackFunction(null);
        }
      });
  };
}

Just the final step, binding the user value with the google api and displaying the results on the browser.
//Process form input
$(function() {
  $('#user-location').on('submit', function(e){
    //Stop the form submission
    e.preventDefault();
    //Get the user input and use it
    var userinput = $('form #address').val();

    if (userinput == "")
      {
        alert("The input box is blank.");
        return false;
      }

      var g = new GoogleGeocode();
      var address = userinput;

      g.geocode(address, function(data) {
        if(data != null) {
          olat = data.latitude;
          olng = data.longitude;

          $('#result').append("<p><strong>"+userinput+" -> </strong> Latitude: " + olat + " , " + "Longitude: " + olng + "</p>")

        } else {
          //Unable to geocode
          alert('ERROR! Unable to geocode address');
        }
      });

  });
});

View Demo
Share to download the Source Codes for FREE!
We're glad to give free downloads, but we need your love to carry on making that.
Please support us by sharing the page.

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Prince kumar on

Sir i want to search in 20 miles area club in my city according to my present address. please provide me a code or link you have related to this query.

Reply
Shahrukh Khan on

Hi. I think you should look at this plugin http://plugins.jquery.com/storelocator/

Reply
EVan on

Thanks for the post. How do I send the co-ordinates to a mysql databse

Reply
Shahrukh Khan on

Thanks. how will you capture the co-ordinates. Inserting in the database is an easy thing. Just create two columns for lat/long and just insert in that table.

Reply
piotr on

Great tutorial Mr. Shahrukh!!
Do you think you can find some time to give tutorial on how to insert lat and long to sql database?

Best regards

Piotr

piotr on

…using for example hidden form field

Manoj on

Use the below function in your php file to get the latitude and longitude from pincode.
function getLongLatFromPincode($pincode) {
$return = array();
$url = “http://maps.googleapis.com/maps/api/geocode/json?address=” . $pincode . “&sensor=false”;
$details = file_get_contents($url);
$result = json_decode($details, true);
$lat = $result[‘results’][0][‘geometry’][‘location’][‘lat’];
$lng = $result[‘results’][0][‘geometry’][‘location’][‘lng’];
$return[‘lat’] = $lat;
$return[‘lon’] = $lng;
return $return;
}

the use your sql statement to insert in to the pincode table

kousalya on

it is working nice in your demo, but i run this code in my localhost it is not working, is there anything that i need to change in that code

Reply
Shahrukh Khan on

no . it will work fine

Reply
techsaathi on

Sir, when user search the location on my website, then see the Google Map location…

Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.