Complete PHP CURL, JSON and Google Maps API Example

The aim of this tutorial to show how you can combine, CURL, JSON and the Google Map API to create a widget that displays your browser position (internet connection) on a map. This tutorial can also be used as a Google Maps API tutorial, an intorduction to JSON and a php CURL example. This will teach you how to integrate curl, json and the google maps API. We will make a json call to a php script. The script will then open a cURL connection to a service and get your IP information and respond. The json response will then be decoded and displayed on a google map. View this Example at work

This tutorial assumes that you have a php capable web server hosted externally on the internet. If not then you can use the php that is hosted on codediaries.

Versions used in this example
Apache 2.2N/A
Google Maps API V2N/A
Links to these files can be found here

This example consists of the three files listed below.

Open cURL connection and get the IP Information
  • Create the php file
     1. <?php
     2. $xman=$_GET["json"];
     4. $ch = curl_init();
     5. curl_setopt($ch, CURLOPT_URL, "".
     6. "key=e8418e1d22fe3b8198f3b07728c8e31851d5202b08b5b10c148a2b54dbbdfe1d".
     7. "&timezone=false&ip=".$_SERVER['REMOTE_ADDR']);
     9. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    11. $output=curl_exec($ch);
    13. preg_match("/<CountryName>(.*?)<\/CountryName>/ims",$output, $matches);
    14. $country = $matches[1];
    15. preg_match("/<RegionName>(.*?)<\/RegionName>/ims",$output, $matches);
    16. $region = $matches[1];
    17. preg_match("/<City>(.*?)<\/City>/ims",$output, $matches);
    18. $city= $matches[1];
    19. preg_match("/<Latitude>(.*?)<\/Latitude>/ims",$output, $matches);
    20. $lat= $matches[1];
    21. preg_match("/<Longitude>(.*?)<\/Longitude>/ims",$output, $matches);
    22. $long= $matches[1];
    24. $jsonstring = "{\"user_agent\":\"".urlencode($_SERVER['HTTP_USER_AGENT'])."\",";
    25. $jsonstring.= "\"ip\":\"".urlencode($_SERVER['REMOTE_ADDR'])."\",";
    26. $jsonstring.= "\"country\":\"".urlencode($country)."\",";
    27. $jsonstring.= "\"region\":\"".urlencode($region)."\",";
    28. $jsonstring.= "\"city\":\"".urlencode($city)."\",";
    29. $jsonstring.= "\"lat\":\"".urlencode($lat)."\",";
    30. $jsonstring.= "\"lng\":\"".urlencode($long)."\",";
    31. $jsonstring.= "\"referer\":\"".urlencode($_SERVER['HTTP_REFERRER'])."\"}";
    33. header("Content-Type: text/javascript");
    34. echo $xman."(".$jsonstring.");";
    35. ?>
    Hide line numbers
    What is being passed to the php script in the $_GET['json'] parameter is the name of the javascript function.

    Line 5 you call with the IP obtained from $_SERVER['remote_addr']. This returns an XML file. You need to register at their site and get an API key for your use.

    Lines 13-22 Decode the xml file to extract the country, region, city

    Lines 24-31 Create the json response from the details

    Lines 33-34 Set the header as javascript and return the information with the original function name you received at line 2.
  • Now host this file in your php enabled server. For this example to work the file has to be hosted on an external server. If you host it locally, the remote_addr attribute will give you which is meaningless. If you do not have an external host then you can use
  • Test the script by calling it with json=mycallback in your browser.
    You should see som text in your browser. The json format is given below.

    {"user_agent":"Mozilla Firefox ...",
    "region":"New South Wales",

The Google Maps Javascipt
  • This is the remoteInfo.js file.
     1. var map;
     2. function initialize(lat, lng) {
     3.     var myOptions = {
     4.         zoom: 2,
     5.         center: new google.maps.LatLng(lat, lng),
     6.         mapTypeId: google.maps.MapTypeId.ROADMAP
     7.     }
     8.     map = new google.maps.Map(document.getElementById("map_canvas"),
     9.                                   myOptions);
    10. }
    11. function markMe(lat, lng, text){
    12.     var image = '';
    13.     var myLatLng = new google.maps.LatLng(lat, lng);
    14.     var beachMarker = new google.maps.Marker({
    15.         position: myLatLng,
    16.         map: map,
    17.         icon: image
    18.     });
    19.     infowindow = new google.maps.InfoWindow({content : text});
    20.     google.maps.event.addListener(beachMarker, "click", function() {
    21., beachMarker);    
    22.     });
    23. }
    24. function urldecode(x){
    25.     return unescape(x).replace(/\+/g," ");
    26. }
    27. function mycback(resp){
    28.     initialize(, resp.lng);
    29.     text=urldecode(resp.ip)+"<br/>"+urldecode("<br/>"+urldecode(resp.region)+"<br/>"+urldecode(;
    30.     markMe(, resp.lng, text);
    31. }
    32. document.write("<script type=\"text/javascript\" src=\"\"/>");
    Hide line numbers

    Line 32 Calls the previous php script with json=mycback. Once this get's called when it returns javascript like below.
    This then calls mycback on Line 27. Note that you should point this url to where you hosted your remoteInfo.php file.

    Line 27 mycback has access to all the json response values in the form of, resp.user_agent etc. It then calls Initialize() to initialize the map and then markMe(), to place a marker on the map

Putting it all together
  • This is the html file that calls the js file. This is saved as test.html
     1. <html>
     2. <head>
     3. </head>
     4. <body>
     5. <div id="map_canvas" style="width:295px;height:250px;font-family:arial;font-size:0.75em"></div>
     6. <script type="text/javascript" src=""></script>  
     7. <script type="text/javascript" src="remoteInfo.js"></script> 
     8. <script type="text/javascript">
     9. /**Dummy**/
    10. </script> 
    11. </body>
    12. </html>
    Hide line numbers

    Line 5 Has the 'div' with id='map_canvas'. Google will create the map in this layer.

    Line 6 This loads the API. Note, you will need an API key for this. You can use the one in the example, but you should get one of your own. You can get one at Google Maps.

    Line 7 You are including the remoteInfo.js file from the previous section. The remoteInfo.js and test.html file are in the same directory for this example.

    Lines 8-10 Is a little trick you need to include to make it work. Just add it.
  • Now opent remoteInfo.html and you should see your position displayed on a map.


institute of lraqi scholars & academician said...

thank you very much

chamila said...

Hi I need to send details from Php to Java. Using php cul we can send variables to jAVA(SERVER),But I can u tel me How I get this request from java server side??

righteous said...

Don't need to use curl to pass value from php to java. Just use a redirect
header("Location :/locatiton/to/servlet.jsp?x=$phpval");

surender said...

i am confused please help me. how do i fetch data through json using cellid,mcc,mnc,ta,lac .