Address to latitude/longitude using Google Maps API v3 Geocoding

Google Maps API v3 Geocoding

Google Maps API v3 has several services, of which one is Geocoding service. This service allows conversion of an address to a latitude and longitude. Along with this information, a lot of good information about the geocoding process is returned. This article highlights how to geocode an address to latitude/longitude using Google’s Geocoding service. The code uses jQuery/JavaScript.

Requirements

Allow user to enter an address. Perform geocoding and return the lat/lon and any other information the geocoding service sends using Google Maps API v3 Geocoding

Final Result

The final result is available on Obtain latitude/longitude from address using Google Geocoding API page. Feel free to explore the results and compare them with Google’s Geocoding Service documentation.

Entire solution

Let’s see how it is all put together. Feel free to download geocoding.js to create your own example. The Javascript file is somewhat documented. The code is also available on https://github.com/zedfoxus/google-maps-demo and a full screen version is available also on https://github.com/zedfoxus/google-maps-demo/tree/master/geocoding.

The index page contains basic form.

<form role="form" action="./" method="get" onsubmit="return false;">
  <div class="col-sm-4">
    <input type="text" id="address" class="form-control" placeholder="Address">
  </div>
  <button type="button" id="geocode" class="btn btn-primary">Show Lat/Lon</button>
</form>

JavaScript dependencies are Bootstrap, Google JavaScript API v3 and customized geocoding.js

    <link type="text/css" rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script type="text/javascript" src="geocoding.js"></script>

Geocoding

We will focus on geocoding.js now. Two variables are declared globally. decoder variable is initialized with Google’s Geocoder. information variable will hold formatted information after geocoding results are obtained.

    var decoder = new google.maps.Geocoder();
    var information = "";

    $(document).ready(function() {
        setup();
    });

    function setup() {
        $("#address").focus();
        $("#geocode").click(function() {
            geocode();
        });
    }

Once DOM is built and ready for modification, we set the focus of the cursor on Address field. Button’s click event is wired up with function geocode(). This function’s sole purpose is to take the address provided by the user and pass it on to Google’s Geocoding service like so:

    function geocode() {

        information = "";

        var address = $("#address").val();
        if (address.trim().length == 0) {
            alert("No address was entered");
            return;
        }

        decoder.geocode(
            {
                'address': address
            }
            , function(result, status) {
                evalutateStatus(result, status);
            });
    }

Google’s API returns result and status of the geocoding. Status is evaluated first. If status is OK as defined by the enumerated constant google.maps.GeocoderStatus.OK, each received item is parsed in the displayResult function.

    function evalutateStatus(result, status) {
        switch(status) {
            case google.maps.GeocoderStatus.ZERO_RESULTS:
                populateInformation("No results found;" + status);
                break;
            case google.maps.GeocoderStatus.OVER_QUERY_LIMIT:
                populateInformation("Too many requests have been sent already;" 
                    + status);
                break;
            case google.maps.GeocoderStatus.REQUEST_DENIED:
                populateInformation("Google denied the request;" + status);
                break;
            case google.maps.GeocoderStatus.INVALID_REQUEST:
                populateInformation("Request is invalid;" + status);
                break;
            case google.maps.GeocoderStatus.OK:
                displayResults(result);        
                break;
            default:
                populateInformation("No information to provide;" + status);
                break;
        }
    }

Display results function

A given address’s geocoding attempt may result in more than one lat/lon. For example, if only Atlanta is typed as the address, 6 results are returned. The returned result is an array. The function displayResult enumerates through the results and sends each result to function called displayInformation like so:

    function displayResults(results) {
        var resultsCounter = results.length;
        for (var i = 0; i < resultsCounter; i++) {
            information += 
                "<div>" 
                + "<strong>Result " + (i+1) 
                + " of " + resultsCounter + "</strong>"
                + "</div>";
            displayInformation(results[i]);
        }
    }

Each result passed to displayInformation() function is parsed and meaningful sentences are created. Although the code has been included with this article, it is important to mention that some information may or may not be received. For example, Google may sometimes inform us that a partial match of an address was located. When such partial match is detected, Google includes partial_match property. The code confirms the existence of partial_match before attempting to format that information.

        if (typeof result.partial_match !== "undefined") {
            information += "<div>Partial match: " + result.partial_match 
                + "</div>";
        }

The general hierarchy of information looks like this for Kona, Hawaii’s geocoding:

Google Maps API v3 Geocoding results

According to my observations and needs, the following nodes have been very useful:

  • formatted_address
  • geometry.locations
  • geometry.location_type

Geocoding may not always give precise information. It is important to look at the location type and add a flag when the lat/lon is not precise. Google Maps API v3 Geocoding exercise has been useful to me in various situations and hope that this article helps more developers.