Posts Tagged Google Maps

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.

<form name="myForm">
  Address:<br />
  <input type="text" name="address" />
  <input type="button" value="Get coordinates" onclick="getCoordinates()"/>
  <br />
  Latitude:<br />
  <input type="text" name="lat" /><br />
  Longitude:<br />
  <input type="text" name="lng" />
</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.

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");
  }
}

And that’s all! Hit the more link to see the full page code.

Read the rest of this entry »