Share, Read & Learn

Google Map API – Geo Location using Address in PHP

0 1,838

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 = "http://maps.googleapis.com/maps/api/geocode/json?address=".$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;
      break;
    case 'OK':
      return $geoloc['results'][0]['geometry']['location'];
      break;
  }
}

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>';
print_r($location);
echo '</pre>';

// Result
Array
(
    [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.