Tuesday, February 22, 2011

Address to Latitude / Longitude


In PHP you can easily find the latitude and longitude of a particular address, which is in simple text format. All you have to do is to copy and paste the code which is provided at the end of this post. In this the address is converted by the use of a google API.

Now for that first you need to get a registered API key. You can signup for the API key here.

Paste the following code in your .php file and execute:


<?
//Three parts to the querystring: q is address, output is the format, key is the GAPI key
$key = "<YOUR_API_KEY>";
$address = urlencode("columbia MO");

//If you want an extended data set, change the output to "xml" instead of csv
$url = "http://maps.google.com/maps/geo?q=".$address."&output=csv&key=".$key;
//Set up a CURL request, telling it not to spit back headers, and to throw out a user agent.
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER,0); //Change this to a 1 to return headers
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$data = curl_exec($ch);
curl_close($ch);

echo "Data: ". $data;
?>

In case you get a safe mode error you can change the:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1)
to
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0)

in the above code


Best of luck!!

No comments:

Post a Comment