11 December, 2010

How to get Lattitude and Longitude from Address using Google Maps

We can easily locate store using Goolge Maps Geocoder.
Google Maps uses REST method for accessing the services.

Our code uses cURL to locate stores using Google Maps API geocoder,
to query HTTP based geocoding API and SimpleXML to parse the
returned response. So, following code can be used to get the lattitude
and longitude of an address using google Maps Geocoder.

Lets start with the code using cURL for request. The cURL request
returns an XML in fact KML response on valid request.

$apiKey = "your_api_key_for_google_maps";
$address = "your_address";
$city = "your_city";
$state = "your_state_prefix";
$zip = "your_zip_code";

$url = "http://maps.google.com/maps/geo?output=xml&key=$apiKey&q=";
$query = $address.",".$city.",".$zip;
$url .= urlencode($query);

//initialize rhte curl object
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);


Now its time to parse the XML response using PHP's SimpleXML.

$xmlResponse = simplexml_load_string($response);

//check if the status code in response is 200, i.e. OK
if($xmlResponse->Response->Status->code == 200) {
foreach($xmlResponse->Response as $response) {
foreach($response->Placemark as $place) {
$latLngArr = explode(",", $place->Point->coordinates);
$lattitude = $latLngArr[0];
$longitude = $latLngArr[1];
}
}
}

In this way we can find lattitude and longitude of an address
using Google Maps geocoder feature.

No comments: