Home PHP

Google Maps Geocoding Example with PHP

Today's code is a Google Maps geocoding example with PHP and we also use some Google Maps JavaScript to show the geo-coded data on the map.

You can use this code if you want to create a store locator. Why this is useful? Imagine if you have several addresses on your database, you will never want to manually pin point the latitude and longitude of each of those addresses.

That's why we have the geocoding method. Just input the addresses and Google will try to identify the approximate location of that address.

The contents of this post include:

  • Step 1: Basic HTML code.
  • Step 2: Create form inside the body tag.
  • Step 3: Put some example addresses before the form.
  • Step 4: Create the PHP geocode() function.
  • Step 5: The code when the user submitted the form.
  • Complete Code on Google Maps Geocoding Example with PHP
  • Live Demo

Step 1: Basic HTML code.

Create index.php file and place the following code.

<!DOCTYPE html>
<html lang="en">
<head>
 
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<title>Live Demo of Google Maps Geocoding Example with PHP</title>

	<style>
	/* some custom css */
	#gmap_canvas{
		width:100%;
		height:30em;
	}
	</style>

</head>
<body>
 
</body>
</html>

Step 2: Create form inside the body tag.

<form action="" method="post">
	<input type='text' name='address' placeholder='Enter any address here' />
	<input type='submit' value='Geocode!' />
</form>

Step 3: Put some example addresses before the form.

<div id='address-examples'>
	<div>Address examples:</div>
	<div>1. G/F Makati Cinema Square, Pasong Tamo, Makati City</div>
	<div>2. 80 E.Rodriguez Jr. Ave. Libis Quezon City</div>
</div>

Step 4: Create the PHP geocode() function.

Place the following code after the previous step's code.

Get your Google Maps Geocoding API key here.

Replace YOUR_API_KEY with your Google Maps Geocoding API key.

DO NOT restrict your API key so that it will work.

<?php 
// function to geocode address, it will return false if unable to geocode address
function geocode($address){

	// url encode the address
	$address = urlencode($address);
	
	// google map geocode api url
	$url = "https://maps.googleapis.com/maps/api/geocode/json?address={$address}&key=YOUR_API_KEY";

	// get the json response
	$resp_json = file_get_contents($url);
	
	// decode the json
	$resp = json_decode($resp_json, true);

	// response status will be 'OK', if able to geocode given address 
	if($resp['status']=='OK'){

		// get the important data
		$lati = isset($resp['results'][0]['geometry']['location']['lat']) ? $resp['results'][0]['geometry']['location']['lat'] : "";
		$longi = isset($resp['results'][0]['geometry']['location']['lng']) ? $resp['results'][0]['geometry']['location']['lng'] : "";
		$formatted_address = isset($resp['results'][0]['formatted_address']) ? $resp['results'][0]['formatted_address'] : "";
		
		// verify if data is complete
		if($lati && $longi && $formatted_address){
		
			// put the data in the array
			$data_arr = array();			
			
			array_push(
				$data_arr, 
					$lati, 
					$longi, 
					$formatted_address
				);
			
			return $data_arr;
			
		}else{
			return false;
		}
		
	}

	else{
		echo "<strong>ERROR: {$resp['status']}</strong>";
		return false;
	}
}
?>

Step 5: The code when the user submitted the form.

Place the code below after the body tag. Replace YOUR_API_KEY with your Google Maps API Key.

Get your Google Maps JavaScript API Key here.

Make sure you restrict your API key to be used on your domain only. Use the Google API dashboard here.

<?php
if($_POST){

	// get latitude, longitude and formatted address
	$data_arr = geocode($_POST['address']);

	// if able to geocode the address
	if($data_arr){
		
		$latitude = $data_arr[0];
		$longitude = $data_arr[1];
		$formatted_address = $data_arr[2];
					
	?>

	<!-- google map will be shown here -->
	<div id="gmap_canvas">Loading map...</div>
	<div id='map-label'>Map shows approximate location.</div>

	<!-- JavaScript to show google map -->
	<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 myOptions = {
				zoom: 14,
				center: new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>),
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			map = new google.maps.Map(document.getElementById("gmap_canvas"), myOptions);
			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 $formatted_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

	// if unable to geocode the address
	}else{
		echo "No map found.";
	}
}
?>

Live Demo

View the live demo by clicking the button below:

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

THANK YOU!

has been added to your cart!

Powered by Easy Digital Downloads

Thank you!

have been added to your cart!

Powered by Easy Digital Downloads

Related Source Code

Working with Geolocation watchPosition() API - In this post, I share a working navigator.geolocation.watchPosition() code I used when I wanted the user to know his current location in real time (while he is walking or riding a vehicle).

Additional Resources

Google Maps Geocoding API Usage Limits

Thanks for reading this Google Maps Geocoding Example with PHP!

120 replies
  1. Naraku
    Naraku says:

    hello.Thk’s for this Code. I’m trying to integrate it in my own site but I got an error with function file_get_contents. My script can’t open the link but when i put the link in my browser i have the result in json format.
    In logs I have this

    [function.file-get-contents]: failed to open stream: Connection timed

    please help !!!

      • Naraku
        Naraku says:

        Hello @ninjazhai:disqus, I fixed my problem. In fact my web serveur couldn’t did request over internet. I changed all my conception and now I’m using Jacscript for Geocoding using the javascript class google.maps.Geocoder.

  2. Matt Robinson
    Matt Robinson says:

    This is a great tutorial and works for zip codes (which is what I need). Is there any way to capture the town or city name so that I can output it back to the user in a paragraph of text?

  3. Brandon Clark
    Brandon Clark says:

    Hello @ninjazhai:disqus In my source code I get an error ” unexpected token ?” at this line “center: new google.maps.LatLng(” Would this have anything to do with the init_map functions or variables? Thanks in advance.

  4. Dwight R. Worley
    Dwight R. Worley says:

    Hey Mike, great tutorial. I neglected to thank you a couple of years back when I used this as a base for a tool to make embeddable traffic maps (which seems to be popular with international audiences based on my website traffic, particularly Russia) Anyway, it’s good to see you’re keeping it updated. You can see my version on my Github here, which has a link to a live demo: https://github.com/dwightworley/traffic-map-embed

    Thanks again for your work.

  5. Sahasra Kamaraju
    Sahasra Kamaraju says:

    Love this code, been looking for something similar since a while ago. Works perfectly.
    Was quite bamboozled with the enormous amount of documentation in the google developers page.
    Slight query, any idea how to actually store this location in a database and then display the same to someone else when they open the map? Similar to a tracking app where you can track somebody’s location.

  6. chris kwan
    chris kwan says:

    I got this “This page didn’t load Google Maps correctly. See the JavaScript console for technical details.” I think it has something to do with API Key but even after I provided it, no map shows up.

  7. aagins
    aagins says:

    in this script

    function init_map() {
    var myOptions = {
    zoom: 14,
    center: new google.maps.LatLng(, ),
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById(“gmap_canvas”), myOptions);
    marker = new google.maps.Marker({
    map: map,
    position: new google.maps.LatLng(, )
    });
    infowindow = new google.maps.InfoWindow({
    content: “”
    });
    google.maps.event.addListener(marker, “click”, function () {
    infowindow.open(map, marker);
    });
    infowindow.open(map, marker);
    }
    google.maps.event.addDomListener(window, ‘load’, init_map);

    i would like to show more than 1 location. lets says i want to show from my stored address. thanks

    • Mike Dalisay
      Mike Dalisay says:

      Hi @KenPachi, would you try to right click your page > click inspect element > click ‘console’ tab and tell us what exactly is the error message? Better if you will send your test link so we can investigate more about the issue. Thanks.

  8. Dan Alexa
    Dan Alexa says:

    Hello,
    thank you for this great website and especially Google Maps Tutorial here.

    I dont understand why, but I do have problems to get it working though. Where do I include the geocode-function?

    After clicking on Geocode I just get a Warning:
    file_get_contents(http://maps.google.com/maps/api/geocode/json?address=):
    failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
    in C:xampphtdocsjson_test.php on line 35
    No map found.

  9. Nur Amirah Roslan
    Nur Amirah Roslan says:

    thank a lot for your good sharing…i have tried your code but there is error Fatal error: Call to undefined function geocode() in C:wamp64wwwepenilaiantest6.php on line 72..can i know whats wrong with it.Thank you

  10. Jukka
    Jukka says:

    I got the system working fine, but now it is complaining that quota has been exceeded. Not sure whose key it is using. When I then try to use https:// and &key=MY-KEY, it responds nothing.

    Array ( [error_message] => You have exceeded your daily request quota for this API. We recommend registering for a key at the Google Developers Console: https://console.developers.google.com/apis/credentials?project=_ [results] => Array ( ) [status] => OVER_QUERY_LIMIT )

    Any ideas?

  11. tbschen
    tbschen says:

    When I try the live example above quickly multiple times, I sometimes get the following errors:

    Notice: Undefined offset: 0 in /home/100661.cloudwaysapps.com/rpxdhcedbx/public_html/demos/php-examples/google-maps-geocoding-example-with-php/index.php on line 126

    Notice: Undefined offset: 0 in /home/100661.cloudwaysapps.com/rpxdhcedbx/public_html/demos/php-examples/google-maps-geocoding-example-with-php/index.php on line 127

    Notice: Undefined offset: 0 in /home/100661.cloudwaysapps.com/rpxdhcedbx/public_html/demos/php-examples/google-maps-geocoding-example-with-php/index.php on line 128

    You may look into it, maybe it is to prevent “spam”?

  12. Robert Hook
    Robert Hook says:

    I can’t get Google Geocode to work at all. It use to work just fine. I used it on my site several years ago. Was trying to get the function operational again but my code fails. It doesn’t even return why. The main get functions just returns false. So I’m wondering what has changed about Google Geocode service.

    The only difference between your code and mine is that you are using $resp_json = file_get_contents($url); whereas I am using simplexml_load_file($url). But that is just personal preference. Tried using file_file_contents and got the same results. It just returns false not matter what you do. Here is what I do…This use to work just fine.

    // GOOGLE URL
    $url = “https://maps.googleapis.com/maps/api/geocode/xml?address=”. urlencode($dvtblx) .”&sensor=false&key{removed for posting online}”;
    if(empty($xml = simplexml_load_file($url))) $ex[‘address’] = “Googleapis is not functioning.”;
    elseif(“” == $xml) $ex[‘tblx’] = “Geocode problem with address, revise and retry.”;
    elseif(“OK” != $xml->status) $ex[‘tblx’] = “Geocode: ” . (“ZERO_RESULTS” == $xml->status? “Not Found”: substr($xml->status,0,30));
    else{
    $dvtby0 = $uca[‘y0’] = (double)$xml->result->geometry->location->lat; //x
    $dvtbx0 = $uca[‘x0’] = (double)$xml->result->geometry->location->lng;
    $dvtby1 = $uca[‘y1’] = (double)$xml->result->geometry->viewport->southwest->lat; //a
    $dvtbx2 = $uca[‘x1’] = (double)$xml->result->geometry->viewport->southwest->lng;
    $dvtbx1 = $uca[‘x2’] = (double)$xml->result->geometry->viewport->northeast->lng; //b
    $dvtby2 = $uca[‘y2’] = (double)$xml->result->geometry->viewport->northeast->lat;

    • Mike Dalisay
      Mike Dalisay says:

      Hi @disqus_TjtVilhOXM:disqus, I updated the code above with Google maps Geocoding and JavaScript API keys. I changed the Geocode API URL as well, see:


      $url = "https://maps.googleapis.com/maps/api/geocode/json?address={$address}&key=YOUR_API_KEY";

      • Robert Hook
        Robert Hook says:

        This turned out to be a weird problem that took me hours to troubleshoot. Everything worked just fine months ago. Once we discovered it worked on the server but not when accessed by a remote browser was when we realized it was weird. Digging deep we discovered that it was actually shooting an error instead of returning false. The fix was upgrading to a newer version of PHP which of course made other stuff not work properly. How this is even possible I still don’t know as I have moved on. I hope you people know that the random things you do to make things better translates to endless hours of rework for people like me that have deadlines to meet and paying customers to please.

        • Mike Dalisay
          Mike Dalisay says:

          @disqus_TjtVilhOXM:disqus, in your case, it sounds like you are using our simple example above on your big production application. It is not recommended.

          I don’t know the exact date and time of Google Maps API updates. I don’t know when or how to update my tutorial above immediately as well.

          In your case, you must go directly to the official Google maps docs where you can always find the most updated and detailed information about how to use the Google maps API.

          See https://developers.google.com/maps/documentation/

  13. Alvaro da Costa
    Alvaro da Costa says:

    Hey i just have a problem, the code works fine and it doesn’t show any errors, but the map doesn’t show up, am working on localhost, so may that be the issue?

  14. Alvaro da Costa
    Alvaro da Costa says:

    Hey i just have a problem, the code works fine and it doesn’t show any
    errors, but the map doesn’t show up, am working on localhost, so may
    that be the issue?

  15. glenn jamero
    glenn jamero says:

    Hey just wondering if why there’s no map appearing after i press geocode do i need to modify some stuff or not ?, btw there is no error though. please reply asap thanks

  16. Ali Mohammad Fawzi
    Ali Mohammad Fawzi says:

    Location returned by this demo is wrong for search keyword “1412 norway” , compared to similar search on google maps.

    https://uploads.disquscdn.com/images/61ac9877ea7ad816d848740fb1c6e1ba3239c9a11fb06b4c4342794a1fb41dc6.png

    I also have issue with my own code that is described here https://stackoverflow.com/questions/49406156/goolge-maps-api-returns-different-result-via-code-vs-browser?noredirect=1#comment85910553_49406156
    Same Google maps api URL returns two different location coordinates when called by code vs when entered in browser url field.

    • Mike Dalisay
      Mike Dalisay says:

      Hi @alimohammadfawzi:disqus, I replied to your other comment. I can’t think of a reason why exactly you’re having this issue.

      But I read somewhere before that Google maps shows a map depending on your location. For example, when you’re in Country_1 and you view your Country_1 on Google maps, your country is bigger of have better borders. But you’re in Country_2 and your view your Country_1, Country_2 will have the favor.

      I’m not sure, I’m just thinking out loud.

  17. Jon
    Jon says:

    Just wanted to start by saying thanks for the great tutorial. I ran into the same problem as @disqus_TjtVilhOXM:disqus where file_get_contents returned false. It didn’t matter if I used json or xml. Instead I ended up using curl to get the results needed I’m sure it’s some crazy server setting someplace but I’m currently limited on time to find the real issue. Just wanted to throw it out my quick fix in case it helps anyone else.

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 3);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    $resp_json= curl_exec($ch);
    curl_close($ch);

    echo $resp_json; //This will be the json you need for the rest of the geocode function

    • Munsen Tidoco
      Munsen Tidoco says:

      I can not. It tells me that restrictions do not allow it.
      I have the key restricted to work only in my domain.
      If you are so kind as to put the code as you say, for if this works and I was wrong in something.
      The only thing I hope you do is to convert addresses to coordinates and another to do them the other way around, from coordinates to addresses.
      I disabled the restrictions for that key and they work, but I re-enabled them because it scares me to get a millionaire bill.
      So, if you can give me the example, I’ll thank you.

      • Mike Dalisay
        Mike Dalisay says:

        @munsen_tidoco:disqus, unfortunately, your requirement is not part of our tutorial above. You need to tweak it according to your needs. Removing the map should be easy. Also, when you change the restriction, you need at least 15 min for this to take effect.

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.