Google Maps Geocode Address Locator with PHP

Geocoding is the process of converting address into geographic coordinates to show the geo-coded data on the map. For example if you have a particular address and wants to locate that address on the map or wants to create a store locator, then Google Maps Geocoding API can help you to handle this. You just need to pass that address and Geocoding API will return response as JSON or XML to display using Google Maps JavaScript API. So in this tutorial you will learn how to implement Google Maps Geocoding API with a location marker on Google Map. The tutorial explained in easy steps with live to enter address and display location marker on Google map with address details. You can also download source code of live demo.

Also, read:

As we will cover this tutorial with live demo to implement Google Maps Geocoding API with a location marker on Google Map JavaScript and PHP, so the file structure for this example is following.

  • index.php
  • functions.php
  • style.css

Step1: Include Bootstrap, jQuery and CSS
As we will create example HTML using Bootstrap, so in index.php file, we will include Bootstrap CSS and also jQuery to use to display Google Map. We will also include CSS file style.css to display Google map.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" /> 

Step2: Create HTML Form To Enter Address
In index.php file, we will create Form HTML to enter address and a submit button to display Google Map according to address on form submit.


<form action="" method="post">
	<div class="row">		
		<div class="col-sm-4">	
			<div class="form-group">
				<input type='text' name='searchAddress' class="form-control" placeholder='Enter address here' />
			</div>
		</div>
		<div class="form-group">
			<input type='submit' value='Find' class="btn btn-success" />
		</div>
	</div>
</form>	

Step3: Create Google Geocoding API Function
In functions.php, we will create function getGeocodeData to get latitude, longitude and formatted address details into JSON format from particular address with Google Geocoding API and return as array to use in Google JavaScript Map. You also need to create Google Geocoding API Key to use here to get Geocoe details.

function getGeocodeData($address) { 
    $address = urlencode($address);     
    $googleMapUrl = "https://maps.googleapis.com/maps/api/geocode/json?address={$address}&key=YOUR_API_KEY";
    $geocodeResponseData = file_get_contents($googleMapUrl);
    $responseData = json_decode($geocodeResponseData, true);
    if($responseData['status']=='OK') {
        $latitude = isset($responseData['results'][0]['geometry']['location']['lat']) ? $responseData['results'][0]['geometry']['location']['lat'] : "";
        $longitude = isset($responseData['results'][0]['geometry']['location']['lng']) ? $responseData['results'][0]['geometry']['location']['lng'] : "";
        $formattedAddress = isset($responseData['results'][0]['formatted_address']) ? $responseData['results'][0]['formatted_address'] : "";         
        if($latitude && $longitude && $formattedAddress) {         
            $geocodeData = array();                         
            array_push(
                $geocodeData, 
                $latitude, 
                $longitude, 
                $formattedAddress
            );             
            return $geocodeData;             
        } else {
            return false;
        }         
    } else {
        echo "ERROR: {$responseData['status']}";
        return false;
    }
}

Step4: Display Google JavaScript Map with Address Marker
Now finally we will add code in index.php on Form submit to display Google JavaScript with address Marker using Geocoding response. We will call PHP function getGeocodeData() to get Geocoding response and passed to Google JavaScript Map. We also need to create JavaScript Google Map API Key to use here.

<?php
if($_POST) { 
	// get geocode address details
	$geocodeData = getGeocodeData($_POST['searchAddress']); 
	if($geocodeData) {         
		$latitude = $geocodeData[0];
		$longitude = $geocodeData[1];
		$address = $geocodeData[2];                     
	?> 
	<div id="gmap">Loading map...</div>
	<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=YOUR_API_KEY"></script>   
	<script type="text/javascript">
		function init_map() {
			var options = {
				zoom: 14,
				center: new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>),
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			map = new google.maps.Map($("#gmap")[0], options);
			marker = new google.maps.Marker({
				map: map,
				position: new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>)
			});
			infowindow = new google.maps.InfoWindow({
				content: "<?php echo $address; ?>"
			});
			google.maps.event.addListener(marker, "click", function () {
				infowindow.open(map, marker);
			});
			infowindow.open(map, marker);
		}
		google.maps.event.addDomListener(window, 'load', init_map);
	</script> 
	<?php 
	} else {
		echo "Incorrect details to show map!";
	}
}
?>

You may also like:

You can view the live demo from the Demo link and can download the script from the Download link below.
Demo Download


2 thoughts on “Google Maps Geocode Address Locator with PHP

Comments are closed.