How To Find & Use Latitude,Longitude Coordinates Through Google Maps API and PHP cURL

Published on : December 2, 2015

Author:

Category: PHP


google maps php curl
Assume you have a number of addresses and your aim is to get the latitude & longitude for any given address dynamically and subsequently you want those addresses to show on the Google map one by one.

To achieve that you have to use PHP cURL and Google maps API.
So let’s start by getting those addresses one by one from the CSV file and send it into the PHP function, sample source code is added below.

// function to get  the address

function get_lat_long($address){

sleep(5);

$address = str_replace(" ", "+", $address);

$region = 'US';

$url =    "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $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);

$response = curl_exec($ch);

curl_close($ch);

$response_a = json_decode($response);

$lat = $response_a->results[0]->geometry->location->lat;

$long = $response_a->results[0]->geometry->location->lng;

$latlon = array($lat, $long);

var_dump($response_a);

var_dump($latlon);

return $latlon;

}

 

It’s very easy to use. Read address one by one and pass it into this function. This function will read the address and generate a query string. The string then sends a request into the Google maps API and get responses using the cURL. The cURL response will then converted to JSON data and fetches the latitude and longitude from the address. You can then use the data into your map one by one using array. Pretty simple, isn’t it?

Here is a little caveat though, if you make too many requests into the Google maps API in a short period of time or  if you have a lot of data to extract from the server , a warning message will be triggered e.g. you have reached the maximum limit of the query string. To avoid this issue you have to request the server within a time interval. Here, i have used 5 seconds interval for the requests and 500 data to extract from Google maps API.
Hope you would find this post helpful, thank you !


Leave a Reply

Your email address will not be published. Required fields are marked *