Share, Read & Learn

Google Map API – Get Geolocation using City/Locality

0 682

In this post, we will discuss Google Map API – Get Geo Location using City/Locality. I’m assuming, most users are familiar with the Google Maps. Google provides a flexible API to work with the Maps easily. If you want to know more about Google Map API just click here. Today, I’m going to share a function which used to get geolocations using city/locality.

If you want to use these functions in your Laravel project then just need to add this functions in your Laravel helper file. If you are not familiar with Laravel Custom Helper then follow the given article “Laravel Custom Helper Functions”.

Function to get geolocations using city/locality

/**
 * Get Geo Location by city
 */
function getGeoLocationByCity($city)
{
  $locality = trim($city);
  $details_url = "http://maps.googleapis.com/maps/api/geocode/json?locality=".$locality."&components=locality:".$locality."&sensor=true";
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $details_url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  $geoloc = json_decode(curl_exec($ch), true);
  switch ($geoloc['status']) {
    case 'ZERO_RESULTS':
      return 0;
      break;
    case 'OK':
      return $geoloc['results'][0]['geometry']['location'];
      break;
  }
}

In the above code snippet, we are creating one function which accepts one parameter city. And hits the Google Map API, after the successful execution we fetch the geo locations “$geoloc[‘results’][0][‘geometry’][‘location’]”.

// execute the function

$locations = getGeoLocationByCity('toronto');

// $location variable contains an array

echo '<pre>';
print_r($locations);
echo '</pre>';

// result
Array
(
    [lat] => 43.653226
    [lng] => -79.3831843
)

Final thoughts: In this post, we are discussing how to use Google Map API to get the geolocation using city/locality. Please feel free to add the comment if any query. Also, you can found more tutorials here.

Leave A Reply

Your email address will not be published.