Google Map API – Geo Location using Address in PHP

0 2,862

In this post, we will discuss Google Map API – Geo Location using Address in PHP. In the given code snippet, we are creating a simple PHP function which receiving only one parameter. And this parameter contains the complete address, that address geolocation generated via the Google Map API.

function getGeoLocation($addr)
    $cleanAddress = str_replace (" ", "+", $addr);
    $details_url = "".$cleanAddress."&sensor=false";
    $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;
    case 'OK':
      return $geoloc['results'][0]['geometry']['location'];

First, we format the address as required by the Google API. Then use the PHP curl function to send a request to the Google API. That function returns an array if location available.

$location = getGeoLocation('7283 N. Lafayette Rd. Dorchester Center, MA 02124');
echo '<pre>';
echo '</pre>';

// Result
    [lat] => 42.8659306
    [lng] => -70.8723014

In this post, we are discussing how to use Google Map API to get the geolocation. Please feel free to add the comment if any query. Also, you can found for tutorials here.

Leave A Reply

Your email address will not be published.