CodeBriefly
Tech Magazine

Google Map API – Geo Location using Address in PHP

0 4,743

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

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.

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