Google Maps Geocoding Example with PHP

[adinserter block=”34″]

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">
<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.";
    }
}
?>

Download Source Code

You can download all the codes used in this tutorial for only $9.99 $5.55!
[purchase_link id=”12462″ text=”Download Now” style=”button” color=”green”]

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!


Comments

122 responses to “Google Maps Geocoding Example with PHP”

  1. I am having a go at doing this one, I love your site by the way it’s a fantastic way to flesh out ideas 😀 LOVE IT!

    1. ninjazhai Avatar
      ninjazhai

      Just saw this comment @disqus_Tkg3Hukomt, thanks for complimenting our site!

  2. 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. ninjazhai Avatar
      ninjazhai

      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.

        1. ninjazhai Avatar
          ninjazhai

          Good to hear it’s fixed now @disqus_DNUPio9HWu!

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

          2. Savitha Bijoy Avatar
            Savitha Bijoy

            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?

          3. @marwa_97 @savithabijoy what location did you try to input? I’ll have to test it, thanks!

  3. Fabio Fronda Avatar
    Fabio Fronda

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

    1. Hello @fabiofronda, thanks for the tip, code updated now!

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

        1. @Julius, thanks, I just updated the code. 🙂

    2. Viral Sampat Avatar
      Viral Sampat

      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.

      1. Hello @viralsampat, what exactly is the error message you see?

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

    1. @Nancy, would you give us your test URLs so we can investigate on the issue more? Sorry for the late reply, I just saw this comment.

  5. Ayikoyo Charles Avatar
    Ayikoyo Charles

    Is there a way i can modify the above code to work with mysql database?

    1. Hello @ayikoyocharles, yes, you can just retrieve your addresses from database and use the same geocode() function for it. Tutorial like this can help https://www.codeofaninja.com/2011/12/php-and-mysql-crud-tutorial.html

      1. Ayikoyo Charles Avatar
        Ayikoyo Charles

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

  6. AsMa Mefoued Avatar
    AsMa Mefoued

    Thank you very much that was very usefull 😀

    1. Hello @asmamefoued, I’m glad you found it very useful!

      1. AsMa Mefoued Avatar
        AsMa Mefoued

        @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 🙂

  7. sensor parameter is no longer required…

    1. Hello @Tom, thanks for this tip, we will look into it and update the code.

  8. Trinity Vandenacre Avatar
    Trinity Vandenacre

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

    1. You are welcome @Trinitycodes! I’m glad this post saved you a lot of time! 🙂

  9. Wonderful, thank you very much!

    1. You’re welcome @disqus_eOHyI1eypW!

  10. rohatash rawar Avatar
    rohatash rawar

    Thanks it work fine

    1. Hello @rohatashrawar thanks for visiting our site! Glad it works fine for you!

  11. Carlos Arotinco Jr Avatar
    Carlos Arotinco Jr

    Hey just wondering why you didnt use a key for the source geocode? Thanks

    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: https://developers.google.com/maps/documentation/geocoding/usage-limits

  12. Someone already mentioned this, but the sensor=false is not needed in either place in the code. It throws a SensorNotRequired warning (see details here https://developers.google.com/maps/documentation/javascript/error-messages). Removing it from both the $url variable and the script src gets rid of the warning and still works fine.

    1. Hello @scottdeluzio, thanks for this tip, your statement is true. I just updated the post!

  13. Matt Robinson Avatar
    Matt Robinson

    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. Hello @disqus_OlZP6UyAAF, glad the code above works for you! I believe you can do that, you have to play with the data returned by Google Maps API, see this example http://maps.googleapis.com/maps/api/geocode/json?address=77379&sensor=true

  14. Brandon Clark Avatar
    Brandon Clark

    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.

  15. wow it’s working. thanks

    1. You’re welcome, glad it works for you @disqus_AhliCF4f7a!

      1. but it’s not take session id, session name, session email of facebook. why.

        1. @disqus_AhliCF4f7a what are you trying to accomplish? Would you tell us any error message you see?

  16. but i want that google map will show whole path between 2 locations. so plz tell me the code.

    1. Hello @disqus_AhliCF4f7a, thanks for the new post idea, we will add it in our to-do list.

  17. Chris Bruce Avatar
    Chris Bruce

    How are you setting and passing the API Key for the Maps API?

    1. Hello @disqus_t3KF6qireI, we do not use any API key in the script above.

  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.

    1. Hello @Re, glad to help you! Yes you might need a key in your case, but our code above works without a key. See the live demo.

  19. Dwight R. Worley Avatar
    Dwight R. Worley

    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.

    1. Hello @Dwight, you’re welcome! Thanks for sharing your project, it’s cool. 🙂

  20. Dwight R. Worley Avatar
    Dwight R. Worley

    FYI, I didn’t thank you here but I did credit you on Github. 🙂

    1. Yes I saw it, thanks for linking your project to here!

  21. Sahasra Kamaraju Avatar
    Sahasra Kamaraju

    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: https://www.codeofaninja.com/2014/06/php-object-oriented-crud-example-oop.html

      2. Create a PHP script that formats the data to a JSON. Here’s a tutorial: https://www.codeofaninja.com/2013/10/generating-json-string-with-php.html

      3. In your app, you can parse that JSON response to be displayed to the app’s user. Here’s a tutorial in Android: https://www.codeofaninja.com/2013/11/android-json-parsing-tutorial.html

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

  22. chris kwan Avatar
    chris kwan

    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. Hello @chris_kwan , yes there are cases that we need to add an API key. We’ll have to make use of https://console.developers.google.com/. Would you tell us what you see in the console?

      1. chris kwan Avatar
        chris kwan

        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

        1. Did you try to add your API key like the following?

          1. chris kwan Avatar
            chris kwan

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

          2. Oh, please remove the call back, it should look like this:

          3. chris kwan Avatar
            chris kwan

            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. It looks like an error in your PHP script? Do you see this in the console?

          5. chris kwan Avatar
            chris kwan

            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.

          6. Try to run without your database first. If it worked, it means your PHP script has the problem, not our script above.

          7. chris kwan Avatar
            chris kwan

            yes will do thanks again.

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

    1. Hello @aagins , so you mean you want to show two markers in the map? Please take a look at this answer http://stackoverflow.com/a/3059129/827530

  24. KenPachi Avatar
    KenPachi

    Hi Sir, I try this code but the maps not display even i use my API’s Key

    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.

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

    1. Thanks for this suggestion, we’ll add this code in the future!

  26. map is not being displayed…what do i do?

    1. Hi @Disha, what was the error message you see in your console?

  27. Dan Alexa Avatar
    Dan Alexa

    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.

    1. Hi @Dan, would you try to hard code the URL, use the following example:

      http://maps.google.com/maps/api/geocode/json?address=Eastwood%20Quezon%20City

      If that worked, it means you did not supply the correct address.

  28. Nur Amirah Roslan Avatar
    Nur Amirah Roslan

    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

    1. Hi @nuramirahroslan , please make sure the geocode() function is in your php file.

  29. Aditya Rizki Utama Avatar
    Aditya Rizki Utama

    hi sir! nice code, but where i must put the php geocode function()..??

    1. It is in the step 4 above.

  30. Qadeer Akhtar Avatar
    Qadeer Akhtar

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

    1. Hi @qadeerakhtar, you will have all the files used to make our demo above work. Your own API key will work as well.

  31. Jason Taii Avatar
    Jason Taii

    Hello… there is an error “Call to undefined function geocode() “

    1. Hi @jasontaii, are you sure you added the code on step 4 above? If so, would you show us your full code?

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

    1. Hi @Jukka, you need to restrict the key to be used with your domain only. There’s an option in the Google console to set that restriction.

  33. 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”?

    1. Hi @tbschen, I’m unable to replicate the issue. Would you try again? Please send a screenshot of the error as well. Thank you!

      1. Sure, there you go:
        https://uploads.disquscdn.com/images/16f2544ad7397369f051a8fee4ee2fadc839a72122072bb2bd2fb94c1395e355.png

        It probably has to do with you not using an API key? Google does allow a couple of requests without a key, but not all and if it blocks your request, the expected array with longitude and latitude are not generated.

        1. I just updated the tutorial above with Google Maps Geocoding and JavaScript API Keys. Would you try again and tell me if you still see the error?

          1. I’m unable to replicate the issue, would you try to hard refresh the page?

  34. Robert Hook Avatar
    Robert Hook

    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;

    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 = "https://maps.googleapis.com/maps/api/geocode/json?address={$address}&key=YOUR_API_KEY";

  35. Robert Hook Avatar
    Robert Hook

    This function only returns boolean false. Does not work in production.

    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. Robert Hook Avatar
        Robert Hook

        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.

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

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

  36. Alvaro da Costa Avatar
    Alvaro da Costa

    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?

  37. Alvaro da Costa Avatar
    Alvaro da Costa

    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 @alvaro_da_costa, yes, you should try to upload the code on a web server where it can be accessed online.

      1. Alvaro da Costa Avatar
        Alvaro da Costa

        I made it work on local host, just changed a little bit! thanks! O.o

        1. Glad you made it work @alvaro_da_costa, but would you tell us how did you fix it?

  38. glenn jamero Avatar
    glenn jamero

    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

    1. Hi @glennjamero, I’m unable to replicate the issue on our live demo. Did you check the error message in your console?

  39. Ali Mohammad Fawzi Avatar
    Ali Mohammad Fawzi

    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.

    1. Hi @alimohammadfawzi, I’m unable to replicate the issue. Please see attached screenshot.

      https://uploads.disquscdn.com/images/deed849e5ef8c63583805e8626504c53c2aa4d823b15dccd725cd1247e45f7ab.jpg

  40. Ali Mohammad Fawzi Avatar
    Ali Mohammad Fawzi

    Hi
    Live demo here returns wrong location for “1412 norway” compared to google map search. Do you reason for that?

    https://uploads.disquscdn.com/images/156ea551fd4e68a5bbd6f9c3d8ca753aa669b90f9109f13b0eb5b015ef2433c9.png

    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.

  41. 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);
    curl_close($ch);

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

    1. Thanks for sharing your solution @Jon!

  42. Hi @disqus_K2pLw0Bldu, would you tell me the error message you saw in your console? Let us know of your test link as well so we can take a look.

  43. Hi @disqus_K2pLw0Bldu, please make sure you set up your API key properly on your Google console. Enable the needed API in your API library.

  44. You’re welcome @rakadevelop! I’m glad to know our tutorial helped solve a problem you encountered.

  45. Hi @chris_wickell, thanks for the catch. I just added it in the tutorial above.

  46. Hi @munsen_tidoco, if you don’t need the map, you may modify the geocode() function and return the $resp variable. It should contain a JSON result.

    1. Munsen Tidoco Avatar
      Munsen Tidoco

      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.

  47. Till Lindemann Avatar
    Till Lindemann

    Hey there! I’m trying to this with Laravel, and I having a hard time with the code

    https://uploads.disquscdn.com/images/b8f7c60ff5fd2b172f7c93e7b27326d51caf40a1a6b9d367d41cc265c91d940b.png

    Maybe it has something to do with the way I put the function.

    1. Hi @gonzata1996, I don’t know yet how to use it with Laravel. I won’t be very helpful with your case, sorry.

  48. 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. Hi Tom, thanks for letting me know. We are currently fixing this.

Leave a Reply

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