Get City, State and Country name by latitude and longitude using Google Map API and PHP

No comments
In this blog, I'am going to write a function to get City, State and Country name by latitude and longitude using Google Map API and PHP. I have created a function called get_city_state_country(), that will help us getting city, state and country name.

Below function get_city_state_country() accept two parameters. First parameter is used for latitude of the location and second one is for longitude. When you call this function in your script by passing latitude and longitude, it will return an array with city name, state name and country name. If no result found by Google Map API then it will return blank array with city, state and country keys.


<?php
public function get_city_state_country($latitude, $longitude) {
        $output = array('city' => '', 'state' => '', 'country' => '');
        $agent = 'Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0';
        $ch = curl_init();
        $url1 = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" . $latitude . "," . $longitude . "&sensor=false&key=YOUR KEY HERE";
        curl_setopt($ch, CURLOPT_USERAGENT, $agent);
        curl_setopt($ch, CURLOPT_URL, $url1);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $val = curl_exec($ch);
        $locs = json_decode($val);
        if ($locs->status != 'ZERO_RESULTS' && isset($locs->results[0])) {
            foreach ($locs->results[0]->address_components as $l) {
                if ($l->types[0] == 'locality') {
                    $output['city'] = $l->long_name;
                }
                if ($l->types[0] == 'administrative_area_level_1') {
                    $output['state'] = $l->long_name;
                }
                if ($l->types[0] == 'country') {
                    $output['country'] = $l->long_name;
                }
            }
        }
        return $output;
    }
 $result = get_city_state_country('28.535517','77.391029');
 print_r($result);
?>

Please note that, before using this function, make sure that curl() function is enabled on your server. Without CURL this function throw error and will not work. And you also have pass your Google Map account in 'key' parameter to make it work.



No comments :

Post a Comment