In recent projects I have had the unique challenge of calculating the distance between a user and an object. To do this, I wanted to utilize Google Maps V3 API to decode an address into Latitude / Longitude coordinates.

Using PHP, the first thing I need to do is define the address I want to translate into Lat Lng.


//Address to translate into LatLng
$address = '410 S Michigan Ave, Chicago, Illinois, 60605, United States';


Now that I have my address, I want to build the URL that will request data from Google. I will pass in my address variable into a PHP function called urlencode. This is recommended when working with variables in URLs. urlencode will take any special characters or spaces and encode them to be interpreted by a server.


//Set up google maps API URL
//Encode address variable
$url = '' . urlencode($address);


After the URL is built, I need to CURL the data from Google. This will make the request, using the URL we just built and return the data in JSON format.


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch), true);


The data I requested is now in a variable named response. So I can use response and see the data I want, but since I only want the Latitude and Longitude I just need to store those in a couple variables so I can reuse them anytime.


//If google responds with a status of OK
//Store latitude and longitude into variables
if($response['status'] == "OK"){
  $lat = $response['results'][0]['geometry']['location']['lat'];
	$lng = $response['results'][0]['geometry']['location']['lng'];


Next, I stored these values in a database and assigned them with a user, or object. Code examples can be found here: