How To Integrate Google API (Maps) with PHP?

Google APIΒ is mostly used in Javascript or a Javascript based framework. When it comes to using such Google APIs with a server-side programming language like PHP, you find very few resources and guides that help you learn and execute such integrations.

While having to execute such integrations with Google APIs, you often hit a wall with questions like- How to derive the distance between two coordinates? How long will it take from a particular coordinate to another? Or, How to get actual addresses from coordinates?

This article intends to enable you to learn and execute such operations and also implement a few other cool and interesting features by using Google API of Maps with PHP, in the simplest manner possible.

1. Function to Derive Address from Coordinates

<?php class GoogleClass { public function getAddressFromGoogleMaps($lat, $lon) { $url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lon&sensor=false"; // Make the HTTP request $data = @file_get_contents($url); // Parse the json response $jsondata = json_decode($data, true); // If the json data is invalid, return empty array if (!$this->check_status($jsondata)) {
			return array();
		}

		$address = array(
			'country' => $this->google_getCountry($jsondata),
			'province' => $this->google_getProvince($jsondata),
			'city' => $this->google_getCity($jsondata),
			'street' => $this->google_getStreet($jsondata),
			'postal_code' => $this->google_getPostalCode($jsondata),
			'country_code' => $this->google_getCountryCode($jsondata),
			'formatted_address' => $this->google_getAddress($jsondata),
		);

		return $address;
	}

	//Check if the json data from Google Geo is valid
	public function check_status($jsondata) {
		if ($jsondata["status"] == "OK") {
			return true;
		}

		return false;
	}

	//Given Google Geocode json, return the value in the specified element of the array
	public function google_getCountry($jsondata) {
		return $this->findLongNameGivenType("country", $jsondata["results"][0]["address_components"]);
	}
	public function google_getProvince($jsondata) {
		return $this->findLongNameGivenType("administrative_area_level_1", $jsondata["results"][0]["address_components"], true);
	}
	public function google_getCity($jsondata) {
		return $this->findLongNameGivenType("locality", $jsondata["results"][0]["address_components"]);
	}
	public function google_getStreet($jsondata) {
		return $this->findLongNameGivenType("street_number", $jsondata["results"][0]["address_components"]) . ' ' . $this->findLongNameGivenType("route", $jsondata["results"][0]["address_components"]);
	}
	public function google_getPostalCode($jsondata) {
		return $this->findLongNameGivenType("postal_code", $jsondata["results"][0]["address_components"]);
	}
	public function google_getCountryCode($jsondata) {
		return $this->findLongNameGivenType("country", $jsondata["results"][0]["address_components"], true);
	}
	public function google_getAddress($jsondata) {
		return $jsondata["results"][0]["formatted_address"];
	}


  // Searching in Google Geo json, return the long name given the type.
  // (If short_name is true, return short name)
	public function findLongNameGivenType($type, $array, $short_name = false) {
		foreach ($array as $value) {
			if (in_array($type, $value["types"])) {
				if ($short_name) {
					return $value["short_name"];
				}

				return $value["long_name"];
			}
		}
	}

2. Function to Get Driving Distance and Time Between Coordinates

public function getDrivingDistance($lat1, $lat2, $long1, $long2) {
		$url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" . $lat1 . "," . $long1 . "&destinations=" . $lat2 . "," . $long2 . "&mode=driving";
		$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, true);
		$dist = $response_a['rows'][0]['elements'][0]['distance']['text'];
		$time = $response_a['rows'][0]['elements'][0]['duration']['text'];

		return array('distance' => $dist, 'time' => $time);
	}

}

Cheers!!
Happy coding πŸ™‚