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 pinpoint 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.

Step 1: Basic HTML code.

Create index.php file and place the following code.

<!DOCTYPE html>
<html lang="en">
    <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>
    /* some custom css */

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!' />

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>

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.

// 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 = "{$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 
        // 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();            
            return $data_arr;
            return false;
        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.

    // get latitude, longitude and formatted address
    $data_arr = geocode($_POST['address']);
    // if able to geocode the address
        $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=""></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 () {
      , marker);
  , marker);
        google.maps.event.addDomListener(window, 'load', init_map);
    // if unable to geocode the address
        echo "No map found.";

Download Source Code

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

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!

Categorized as PHP

By Mike Dalisay

I'm Mike Dalisay, a pro web developer since 2010. I love web development. Improving our tutorials and source codes makes me happy. Do you want to suggest an edit to our tutorial? Got something to ask about our source codes? You may use our comments section below or email our team at [email protected]


  1. Your “download the source code” no longer works. It chokes on the payment, “Error: You must enable a payment gateway to use Easy Digital Downloads”
    You’re losing revnue!

    1. 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.

      1. @munsen_tidoco, 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.

  2. Just wanted to start by saying thanks for the great tutorial. I ran into the same problem as @disqus_TjtVilhOXM 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);

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

    1. Hi @alimohammadfawzi, 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.

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

    I also have issue with my own code that is described here
    Same Google maps api URL returns two different location coordinates when called by code vs when entered in browser url field.

  4. 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

  5. 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?

  6. 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?

    1. Hi @disqus_TjtVilhOXM, I updated the tutorial above with Google Maps Geocoding and JavaScript API Keys and it worked at my end. Would you try again and tell us if it worked at your end?

      1. 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.

      2. @disqus_TjtVilhOXM, 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.


  7. 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.

    $url = “”. 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));
    $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;

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

      $url = "{$address}&key=YOUR_API_KEY";

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

    Notice: Undefined offset: 0 in /home/ on line 126

    Notice: Undefined offset: 0 in /home/ on line 127

    Notice: Undefined offset: 0 in /home/ on line 128

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

  9. 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: [results] => Array ( ) [status] => OVER_QUERY_LIMIT )

    Any ideas?

  10. In complete source code, do I have the complete package, I mean 3,4 files and my own geo-location API key will work?

  11. 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

  12. 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:
    failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
    in C:xampphtdocsjson_test.php on line 35
    No map found.

  13. hi can you please provide code to display route between source and destination using php and google maps

    1. 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.

  14. 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 () {, marker);
    });, 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

  15. 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.

      1. I have enable all of them
        Google Maps Directions API — — — — —
        Google Maps Distance Matrix API — — — — —
        Google Maps Elevation API — — — — —
        Google Maps Embed API — — — — —
        Google Maps Geocoding API — — — — —
        Google Maps JavaScript API — — — — —
        Google Maps Roads API — — — — —
        Google Static Maps API

        and under credentials I have my Browser API key and for a specific domain

      2. yes that was from google example, but I got this response “js?
        Uncaught InvalidValueError: initMap is not a function

      3. yes I did, but still the map does not show up and there is error (test_c.php:32 Uncaught ReferenceError: google is not defined) ?

      4. yes, I am doing it differently by querying a database and extracting data out to be process instead of posting it like in your case.

  16. 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.

    1. Hello @sahasrakamaraju, thanks for the feedback! To answer your question:

      1. You can store the data on a MySQL database. This tutorial will help you with that:

      2. Create a PHP script that formats the data to a JSON. Here’s a tutorial:

      3. In your app, you can parse that JSON response to be displayed to the app’s user. Here’s a tutorial in Android:

      Those tutorials does not use the same data set, but it should give you a start.

  17. 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:

    Thanks again for your work.

  18. very good Tutorial, and it did help me a lot, but google json api need KEY and if you dont use it, it will not process the request.

  19. Hello @ninjazhai 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.

  20. 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?

    1. For those who has the same question, the answer is: Because it works for this example. But its best to use a key to prevent errors in the future.

      At the moment, it looks like Google is not very strict when you use their API small number of requests. But if your app makes large number of requests and they detected it, I believe they will require you to use a key or pay for the requests exceeding the free tier.

      See the Geocode usage limit here:

  21. Thanks so much, worked like a charm for storing Unknown Lat and Lon in database. Saved me lots of time, I’m sure!

      1. @ninjazhai Hi ! please i have a question ! i’m using php 5.5.12 and “mysql_query(“SET NAMES ‘utf8′”)” don’t work with this version. Is there another solution to avoid weird caracters instead of accent ( i use MySQL 5.6.17 ) thank you :)

      1. Thanks alot. in case i will face some challenges, i will seek for some help again

  22. having rare situation. Two sites a same hosting provider. At one your script works fine, at the other it doenst. Any idea?

  23. Hello… an error in geocode function. The test must be $resp[‘status’]==’OK’ instead of $resp[‘status’]=’OK’

      1. Hello! You still have to update the $resp[‘status’]=’OK’ to $resp[‘status’]==’OK’ in the complete code example! ;)

    1. Hello,
      i used above code for finding city but there is some error occur in geocode(). so anyone help me how to solve this error and i get proper output.

  24. 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 !!!

    1. Hello @disqus_DNUPio9HWu, are you sure your json extension is installed? Please paste your link here so we can try to debug better…

      1. Hello @ninjazhai, 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. hello ninja, i tried this tutorial, when i write a location, i got no errors, but the map does not show up..
        recently i am trying many tutorials but almost non of them works !!
        plesase need a help !
        what the problem could be?

      3. Is there a solution for the issue stated by Marwa_97?
        Even I am facing the same issue and not sure how to fix. Can someone help?

Leave a comment

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

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

Back to top