Alessandro Melandri

WebSphere Commerce Specialist, project manager, wannabe photographer

Get Location Coordinates Using Google Maps

This is a simple tutorial on finding location’s coordinates using Google Maps APIs.

First of all you need to signup for a Google Maps API key, otherwise your script will not work. When you are done, start building a simple form with three fields: one for the location and the others for coordinates display.

1
2
3
4
5
6
7
8
9
10
<form>
  Address:
  <input name="address" type="text" />
  <input onclick="getCoordinates()" type="button" value="Get coordinates" />

  Latitude:
  <input name="lat" type="text" />
  Longitude:
  <input name="lng" type="text" />
</form>

Now, we need to define the getCoordinates() function: this function must read the value of the address field, check if it’s valid and get its coordinates. To get coordinates we’ll use the GClientGeocoder class and its method getLatLng(address:String, callback:function):

Sends a request to Google servers to geocode the specified address. If the address was successfully located, the user-specified callback function is invoked with a GLatLng point. Otherwise, the callback function is given a null point. In case of ambiguous addresses, only the point for the best match is passed to the callback function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var geocoder = new GClientGeocoder();

function getCoordinates(address){

  var address = document.myForm.address.value;

  if (address != ''){

    geocoder.getLatLng(address,function(point){

      if (point != null){
        document.myForm.lat.value = point.lat();
        document.myForm.lng.value = point.lng();
      }

      else{
        alert("Location not found");
      }
    })
  } else {
    alert("Please insert a location");
  }
}