Complete PHP CURL, JSON and Google Maps API Example

Aim
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

Assumptions
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. http://codediaries.com/myphp/remoteInfo.php?json=mycallback

Versions used in this example
Sofware/ComponentImage
PHP 5N/A
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.
Example
_|_requestInfo.js
_|_requestInfo.php
_|_test.html

Open cURL connection and get the IP Information
  • Create the php file
     1. <?php
     2. $xman=$_GET["json"];
     3.  
     4. $ch = curl_init();
     5. curl_setopt($ch, CURLOPT_URL, "http://api.ipinfodb.com/v2/ip_query.php?".
     6. "key=e8418e1d22fe3b8198f3b07728c8e31851d5202b08b5b10c148a2b54dbbdfe1d".
     7. "&timezone=false&ip=".$_SERVER['REMOTE_ADDR']);
     8. 
     9. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    10. 
    11. $output=curl_exec($ch);
    12. 
    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];
    23.   
    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'])."\"}";
    32. 
    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 ipinfo.com 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 127.0.0.1 which is meaningless. If you do not have an external host then you can use http://codediaries.com/myphp/remoteInfo.php
    `
  • Test the script by calling it with json=mycallback in your browser.
    http://codediaries.com/myphp/remoteInfo.php?json=mycallback
    You should see som text in your browser. The json format is given below.

    mycallback(
    {"user_agent":"Mozilla Firefox ...",
    "country":"Australia",
    "region":"New South Wales",
    "lat":"908833",
    "long":"33346",
    ......
    "referer":""
    }

    )
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 = 'http://google-maps-icons.googlecode.com/files/friends.png';
    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.         infowindow.open(map, beachMarker);    
    22.     });
    23. }
    24. function urldecode(x){
    25.     return unescape(x).replace(/\+/g," ");
    26. }
    27. function mycback(resp){
    28.     initialize(resp.lat, resp.lng);
    29.     text=urldecode(resp.ip)+"<br/>"+urldecode(resp.country)+"<br/>"+urldecode(resp.region)+"<br/>"+urldecode(resp.city);
    30.     markMe(resp.lat, resp.lng, text);
    31. }
    32. document.write("<script type=\"text/javascript\" src=\"http://codediaries.com/myphp/remoteInfo.php?json=mycback\"/>");
    Hide line numbers

    Line 32 Calls the previous php script with json=mycback. Once this get's called when it returns javascript like below.
    mycback({"userr-agent":"mozilla",.....,"referer":""})
    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.lat, 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="http://maps.google.com/maps/api/js?key=ABQIAAAAU34fqM8XohIf42U76GcxNhQD6263AO_J-cN-o5MVlTXsf8kbcBRgf8XZKHTaVeqWfZVYZJ5ub5dW3A&sensor=false"></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.

4 comments:

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
<?php
$phpval="test";
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 .