Learning Google Maps Geocoding by example The Geocoding Service is an integrated process in the Google Maps JavaScript API v3 that allows you to convert an address in their respective geographic coordinates.

Learning Google Maps Geocoding by example

by June 25, 2015
geocoding

The Geocoding Service is an integrated process in the Google Maps JavaScript API v3 that allows you to convert an address in their respective geographic coordinates.
The geocoder is included in the Google Maps JavaScript API v3 and so you don’t need to define any additional parameter in the API call URL. Since this service is already included in the API, there are no costs beyond the price applied to the basic API.
However you should bear in mind that the geocoding process has usage limits.

Google Geocoder Service usage limits

After loading the API you can do some requests for geocoding (less than 10) but then the service is limited to little over one request per second. Beyond these limits the API sends an alert to the user. To prevent this warning to be visible by the user and if you need to make several consecutive requests to the geocoding service, you must program the call to setTimeout geocoder with more than 750 milliseconds.

Where you can use geocoding service

With the geocoder you can add a marker on the map and center the map in a predefined area.

Imagine that you are creating a map to show the points of interest of your country. Through the geocoder you can allow the user to search by city or street, moving the map automatically to the desired area.

Similarly you can add a new marker on the map.

  1. The user enters the desired address in a text box.
  2. Using the geocoding service the address is converted to its geographical coordinates.
  3. Automatically the map is centered on the desired area.
  4. A new marker is added to the map.

The geocoding service can also be used to convert addresses in bulk. That is, you can convert various addresses in their respective geographic coordinates to include in a database. However this feature is beyond the scope of this guide.

In this guide I will explain how to move the map to a particular region and how to add a marker at the desired location by specifying an address.

Before you start this tutorial view a demonstration of the map or download the necessary code.

DEMO DOWNLOAD

The HTML structure needed for the application.

This example consists of a map, a text box and a button. The text box is used to get the address to search and the button starts the geocoder process.

You must first prepare the HTML, CSS and JavaScript files with basic options to include a map with Google Maps API on the web page.

HTML /index.htmlen.marnoto.com
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript" src="js/map.js"></script>
  </head>
  <body> 
    <div id="map-canvas"></div>
  </body>
</html>
CSS /style.cssen.marnoto.com
html {
  height: 100%;
}
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map-canvas {
   margin: 0;
   padding: 0;
   height: 400px;
   max-width: none;
}
#map-canvas img {
   max-width: none !important;
}
JS /map.jsen.marnoto.com
var map;
var marker;

function initialize() {
  var mapOptions = {
    center: new google.maps.LatLng(40.680898,-8.684059),
    zoom: 11,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
google.maps.event.addDomListener(window, "load", initialize);

Then include the text box that will receive the address and a button.

HTML /index.htmlen.marnoto.com
...
  <body>
    <div>
       Indique um endereço <input type="text" id="address-input">
       <button onclick="searchAddress();">Pesquisar</button>
    </div>   
    <div id="map-canvas"></div>
  </body>
</html>

Assuming you already have all the HTML elements prepared, let's proceed to the most important phase.

Starting Geocoder process

The Google Maps Geocoding Service runs with a call to google.maps.Geocoder() method and it isn’t necessary to include any call on the API url. The Geocoder method is already included in the basic API.

In this example I'll set the geocoding service in a specific function outside the function usually called initialize(). I will designate this function as searchAddress() but you can assign any other name.

JS /map.jsen.marnoto.com
function searchAddress() {

}

Within the searchAddress() function you start to create a new variable that will get the text box value in which is indicated the address to convert.

JS /map.jsen.marnoto.com
function searchAddress() {

  var addressInput = document.getElementById('address-input').value;

}

Then another variable is defined with the name geocoder to start a new instance of google.maps.Geocoder() method.

JS /map.jsen.marnoto.com
function searchAddress() {

  var addressInput = document.getElementById('address-input').value;

  var geocoder = new google.maps.Geocoder();
}

The Geocoder() has a method known as geocode(). This is method that you will use to make the request for geocoding.

This method accepts two parameters. In the first parameter, called GeocodeRequest, you're going to define an object with the property address: whose value is equal to the value of the text box address-input stored in addressInput variable. {address: addressInput}

In the second parameter you set a callback function that will process the results. function(results, status) {

JS /map.jsen.marnoto.com
function searchAddress() {

  var addressInput = document.getElementById('address-input').value;

  var geocoder = new google.maps.Geocoder();

  geocoder.geocode({address: addressInput}, function(results, status) {

  }
}

The GeocodeRequest object (first parameter) also accepts the property {location: LatLng}. When you use the property "location" you will be indicating to the Geocoding Service that you want to get an address through LatLng coordinates. This process is known as Reverse Geocoding.

In this example you are sending the property address and that's how the Google Maps geocoding service know what procedure to take. Which in this case is to convert an address in latitude and longitude coordinates.

geocoder.geocode({address: addressInput}, ...

The callback function defined in the second parameter also accepts two parameters. The first parameter results receives the result or results may be more than one. With the second parameter status is performed the check of the success of the geocoding service.

If the geocoder was successful, then you can move on to the processing of information received through the parameter results. If the geocoder was not successful, then procedes to check their causes. By the response obtained in the status parameter you're going to try to solve the problem or you give a response to the user to take certain procedure.

The first action to take is to check the returned status. if (status == google.maps.GeocoderStatus.OK) {

JS /map.jsen.marnoto.com
function searchAddress() {

  var addressInput = document.getElementById('address-input').value;

  var geocoder = new google.maps.Geocoder();

  geocoder.geocode({address: addressInput}, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK) {

    }
  }
}

If the value of the status parameter is equal to google.maps.GeocoderStatus.OK this means that the geocoding process was successful and returned one or more results. GeocoderStatus may return other values but for now you will believe that all is well and you can continue processing the information received.

Since the geocoder may return one or more results, the variable results is of type array. But believing that the geocode service hit the result that you want, then you will be working with the result of the first index results[0].

The information returned by the geocoder contains an object called GeocoderResults. One of the properties of this object is another object named geometry. One of the geometry object properties is location and its value is LatLng. So, you can set the result as follows: results[0]: { geometry: { location: LatLng } }
That is, to get LatLng coordinates just do this: results[0].geometry.location

The value received is a google.maps.LatLng object. Just enter this value directly in the process you want to use. In this case you will center the map on the location received by geocode, with map.setCenter(results[0].geometry.location) function and you give the latlng object as the only parameter.

Additionally you can reset the zoom value to reposition the map and highlight the desired area.

JS /map.jsen.marnoto.com
function searchAddress() {

  var addressInput = document.getElementById('address-input').value;

  var geocoder = new google.maps.Geocoder();

  geocoder.geocode({address: addressInput}, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK) {

      map.setCenter(results[0].geometry.location);

      map.setZoom(17);
    }
  }
}

Adding a marker with Google Maps Geocoder

Adding a marker into the map with the Google Maps Geocoding Service v3 by specifying an address is performed in the same way described above. However, it is necessary to set the function that creates the marker and additionally you can center the map on the marker position and zoom it. Following the example above:

JS /map.jsen.marnoto.com
function searchAddress() {

  var addressInput = document.getElementById('address-input').value;

  var geocoder = new google.maps.Geocoder();

  geocoder.geocode({address: addressInput}, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK) {

      var myResult = results[0].geometry.location; // reference LatLng value

      createMarker(myResult); // call the function that adds the marker

      map.setCenter(myResult);

      map.setZoom(17);

    }
  });
}

function createMarker(latlng) {

   // If the user makes another search you must clear the marker variable
   if(marker != undefined && marker != ''){
    marker.setMap(null);
    marker = '';
   }

   marker = new google.maps.Marker({
      map: map,
      position: latlng
   });

}

If the geocode was not successful

If the geocode was not successful, the function returns a warning message with the error message returned by the parameter status.

JS /map.jsen.marnoto.com
...

  if (status == google.maps.GeocoderStatus.OK) {

    var myResult = results[0].geometry.location; // reference LatLng value

    createMarker(myResult); // call the function that adds the marker

    map.setCenter(myResult);

    map.setZoom(17);

  } else { // if status value is not equal to "google.maps.GeocoderStatus.OK"

    // warning message
    alert("The Geocode was not successful for the following reason: " + status);

  }

...

The code shown in this guide is the minimum required to include the geocoding service in an application. From here you can move on to learning the possible responses of the properties status and results.

Map example.

Was this article helpful?
Do you shave any doubts or want to share some knowledge?
Use the comments box and let me know. You’re welcome!

Download the necessary files for this example

Miguel Marnoto

My expertise in the Google Maps JavaScript API v3 is a consequence of my enthusiasm about maps and recognition of the importance that Google Maps service has on people lives.

7 comments to ''Learning Google Maps Geocoding by example"

COMMENT
  1. Very good article. It can be extended by an autocomplete? I think, that Google support it.

    ReplyDelete
  2. hay un error en:
    var map;
    var marker;

    function initialize() {
    var mapOptions = {
    center: new google.maps.LatLng(40.680898,-8.684059),
    zoom: 11,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
    }
    google.maps.event.addDomListener(window, "load", initialize);

    la variable map se uelve a declarar y eso impide que la variable sea global y se quede local, eso quiere decir que no aparee el marcador

    ReplyDelete
  3. Google map is one of the most important services for the modern people in this world.There are many ways too get involved with the other activities for the improvement of the environment.But through the different types of google maps, the people can see the different location in the world.

    ReplyDelete
  4. This module helps to set geo address through Google map api.Gmap Geo Address

    ReplyDelete
  5. I got the warning says "Google Maps API warning: NoApiKeys https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys" Where is the place to put my ApiKey for this application?

    ReplyDelete
  6. I got the warning says "Google Maps API warning: NoApiKeys https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys" Where is the place to put my ApiKey for this application?

    ReplyDelete
  7. In trying to apply your example to my code, I got the following reference error message for 'results': ReferenceError: results is not defined

    This is the code where I encountered the error the the line where geocoder.geocode is called:

    function GamesCloseBy() {

    var addressText = $('#<%= UserAddress.ClientID %>').val();
    geocoder = new google.maps.Geocoder();
    geocoder.geocode({ address: addressText }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
    map.setCenter(results[0].geometry.location);
    var marker = new google.maps.Marker({
    map: map,
    position: results[0].geometry.location
    });
    } else {
    alert('Geocode was not successful for the following reason: ' + status);
    }
    });

    I have a value of "" for status, and a valid address text for addressText. Any idea what I am doing differently from your example?

    Thank You

    ReplyDelete

Note: Only a member of this blog may post a comment.