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

Comments

Popular posts from this blog

Send email from xampp localhost

Modify item price in cart after placing order using sales_quote_add_item

Convert long url to short url using tinyurl api