Tag Archives: google map

Showing Geographical Location On Google Map (Geocoding)

Translating a geographical location such as “London, UK” into a lat/long coordinate (lat: 51.5085150, long: -0.1254870) is called geocoding. This coordinate can then be used to display the location on google map.

Try putting a location in the box below and hit go:

Register for Google Map API Key

In order to implement the above widget first obtain an API key from Google:

  1. Go to
  2. Select Services on the left menu, ensure Geocoding API, Google Maps Embed API and Google Maps JavaScript API v3 are turned on

    geocoding1

    geocoding2
  3. Go to API Access, select Create new Browser key

    geocoding3
  4. The list of accepted HTTP referers will be asked, if you’re testing on local machine this would probably be localhost/*, otherwise you need to put your website domain name here. Hit Create once you’re done

    geocoding4
  5. Take a note of your API key, this will be used in the later part of this tutorial

    geocoding5

The HTML Code

This widget only contains 3 elements:

  • A text input box to provide the geographical location
  • A button to submit the address and show it on the map
  • A div container for the map
Enter location (eg: London, UK): 


Javascript

2 javascript libraries are used: jQuery and Google Map JS. The key parameter on the Google Map JS URL should be the key created above.


Firstly let’s initialize the div container so it doesn’t come up with blank map, here I set it into coordinate of San Francisco, CA:

$(document).ready(function() {
        var map = new google.maps.Map($('#map')[0], {
                center: new google.maps.LatLng(37.7749295, -122.4194155),
                zoom: 8
        });
        ...
}

And create a click handler for the ‘Go’ button which sends ajax post into Google Map JS API. The API will return a JSON response with the location if successful.

$(document).ready(function() {
        ...
        $('#go').click(function(e) {
                e.preventDefault();
                var loc = $('#loc').val();
                $.ajax({
                        url: '//maps.googleapis.com/maps/api/geocode/json?sensor=false&address='+loc
                }).done(function(data) {
                        if(data.status != "OK") {
                                alert("Unable to find location");
                                return;
                        }
                        var loc_result = data.results[0].geometry.location;
                        map.setCenter(new google.maps.LatLng(loc_result.lat, loc_result.lng));
                });
        });
});

See the widget in action in full screen.