Websnippetz

Get cool snippets on php, css, jQuery, Magento and wordpress

Get latitude and longitude using google map api – PHP

Google provides an API to get latitude and longitude based on the valid address. All we need to do is just pass address to that api. We can able to get response in various format. In below code i’m requesting api to return response a json format. If curl is enabled in your server you can use below function to get latitude and longitude by passing just address.


function getLocation($address = null){
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.rawurlencode($address).'&sensor=false';

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);

$res = json_decode($result, true);
if(isset($res['results'][0]['geometry']['location'])){
return $res['results'][0]['geometry']['location'];
}else{
return false;
}
}

If curl is not working try this file_get_contents method to get the response.


function getLocation($address = null){
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.rawurlencode($address).'&sensor=false';

$result = file_get_contents($url);
$res = json_decode($result, true);
if(isset($res['results'][0]['geometry']['location'])){
return $res['results'][0]['geometry']['location'];
}else{
return false;
}
}

karthi s

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: