CodeBriefly
Tech Magazine

Google Map API – Get Geolocation using City/Locality

0 1,451

Get real time updates directly on you device, subscribe now.

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.

If you like our content, please consider buying us a coffee.
Thank you for your support!
Buy Me a Coffee

Get real time updates directly on you device, subscribe now.

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRead More