The WyriHaximus.Network LogoWyriHaximus.Network?: WyriHaximus.net | 21 vistors online | Guest | Login | Register

How to add your visitors to a Google Map



Ok message 1 of today will be a howto to add your visitors as dots on a world map using Google Maps.

First of all we need a API key from Google, you can get it here

Then we start setting up the very basics on the maps. First with a DIV where the map will be placed in:

<div id="map_canvas" style="width: 700px; height: 300px"></div>

Above that we add the javascript include from google, make sure to replace [API_KEY] with your API key:

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=[API_KEY]" type="text/javascript"></script> 

Next we create a function named on_load (or any other name you like but I'll use on_load in this howto):

<script type="text/javascript">   
function on_load()
{
}
window.onload = on_load;
</script>

As you can see I also added window.onload and pointed it to the on_load function. This is to make sure it works in all supported browsers. (IE and Safari go nuts if you start executing the map before the page is loaded. FF has no problem with this tho.) Ok now we are going to fill up the function with the initial code to display the map.

First we add an if to the function to check if the used browser is supported:

    if(GBrowserIsCompatible())
    {
    }

Within this if we create the map object and display it, the map_canvas bit is the name of the DIV where the map is rendered in:

        var map = new GMap2(document.getElementById("map_canvas"));

Now we have a working map. Nothing fancy yet tho, that is what we are going to add now.

First we add the daylightmap (by daylightmap.com be sure to check here before you add this bit). We begin by adding their js include directly after google's include:

<script src="http://www.daylightmap.com/daylight_packed.js" type="text/javascript"></script>

Then we add this in the on_load function directly after where we created the map object:

        var daylight = new daylightMap.daylightLayer();
        daylight.addToMap(map);

This will play an extra layer over the map showing the current daylight and night zones. To add more interactivity we add 2 controls and we also set the center of the map:

        map.setCenter(new GLatLng(30, 0), 1);
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());

Now it becomes fun cause we are going to add dots for each online visitor to the map. To keep this guide universal I assume you how basic programming knowledge and that you readed the HostIP API page. The example will be written in PHP and the IP to display on the map are in an array. This to ensure you can port it to your language of choose. (Feel free to leave a comment with your own version in your language.)

We start with a for loop to walk through to that is placed after adding the interactive bits to the map, note that I fill the array in the example with some random IP's (I just made them up nothing more nothing less):

        <?php
        $ips = array();
        $ips[] = $_SERVER['REMOTE_ADDR'];
        $ips[] = '6.56.89.74';
        for($i=0;$i<count($ips);$i++)
        {
           
        }
        ?>

Now we fetch the Latitude and Longitude from hostip.info (you can host the database yourself aswell but that goes beyond the scope of this howto):

$data = @file_get_contents('http://api.hostip.info/get_html.php?ip=' . $ips[$i] . '&position=true');

Next we check if the fetch was successful and explode/split the data into an array:

            if($data)
            {
                $ex = explode("\n",str_replace(array("\r","\n\n",'Latitude: ','Longitude: '),array("\n","\n",'',''),$data));
            }

As you can see I removed the lat and long text from the data bit. This will make checking and using easier. If no lat/long known is the string will be empty.  Now we check if the string is empty or not (we add this right after the explode():

                if(!empty($ex[2]) && !empty($ex[3]))
                {
                }

Within this if we add a echo command to add a marker on the map:

                    echo('var point = new GLatLng(' . $ex[2] . ',' . $ex[3] . ");\r\n");
                    echo("map.addOverlay(new GMarker(point));\r\n");

Congratulations you have now a Google Map with a point for every visitor online on your site. You should have this code now:

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=[API_KEY]" type="text/javascript"></script>
<script src="http://www.daylightmap.com/daylight_packed.js" type="text/javascript"></script>
<div id="map_canvas" style="width: 700px; height: 300px"></div>
<script type="text/javascript">   
function on_load()
{
    if(GBrowserIsCompatible())
    {
        var map = new GMap2(document.getElementById("map_canvas"));
        var daylight = new daylightMap.daylightLayer();
        daylight.addToMap(map);
        map.setCenter(new GLatLng(30, 0), 1);
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        <?php
        $ips = array();
        $ips[] = $_SERVER['REMOTE_ADDR'];
        $ips[] = '6.56.89.74';
        for($i=0;$i<count($ips);$i++)
        {
            $data = @file_get_contents('http://api.hostip.info/get_html.php?ip=' . $ips[$i] . '&position=true');
            if($data)
            {
                $ex = explode("\n",str_replace(array("\r","\n\n",'Latitude: ','Longitude: '),array("\n","\n",'',''),$data));
                if(!empty($ex[2]) && !empty($ex[3]))
                {
                    echo('var point = new GLatLng(' . $ex[2] . ',' . $ex[3] . ");\r\n");
                    echo("map.addOverlay(new GMarker(point));\r\n");
                }
            }
        }
        ?>
    }
}
window.onload = on_load;
</script>

Updated code with SuperRembo's comment:

<?php
function host_ip($ip)
{
    $data = @file_get_contents('http://api.hostip.info/get_html.php?ip=' . $ip . '&position=true');
    if($data)
    {
        $ex = explode("\\n",str_replace(array("\\r","\\n\\n",'Latitude: ','Longitude: '),array("\\n","\\n",'',''),$data));
        if(!empty($ex[2]) && !empty($ex[3]))
        {
            return array($ex[2],$ex[3]);
        }
    }
    return false;
}
$markers = $ips = array();
$ips[] = $_SERVER['REMOTE_ADDR'];
$ips[] = '6.56.89.74';
for($i=0;$i<count($ips);$i++)
{
    $marker = host_ip($ips[$i]);
    if($marker)
    {
        $markers[] = $marker;
    }
    unset($marker);
}
?>
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=[API_KEY]" type="text/javascript"></script>
<script src="http://www.daylightmap.com/daylight_packed.js" type="text/javascript"></script>
<div id="map_canvas" style="width: 700px; height: 300px"></div>
<script type="text/javascript">  
function on_load()
{
    var add_marker = function (x) {
           marker_manager.addMarker(new GMarker(new GLatLng(x[0], x[1])), 0);
    }
    if(GBrowserIsCompatible())
    {
        <?php
        echo('var markers = ' . json_encode($markers) . ";\\r\\n");
        ?>
        var map = new GMap2(document.getElementById("map_canvas"));
        var daylight = new daylightMap.daylightLayer();
        daylight.addToMap(map);
        map.setCenter(new GLatLng(30, 0), 1);
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        marker_manager = new GMarkerManager(map);
        markers.forEach(add_marker);
    }
}
window.onload = on_load;
</script>

My implantation:

Enjoy it and feel free to post your a link to your implentations Cool.

WyriHaximus

WyriHaximus.net :: How to add your visitors to a Google Map Score: 2 Vote:
By Blogsvine @ 22 March 2008, 15:36
Tutorial how you can add your visitors location to a Google Map.

Suggestions Score: 1 Vote:
By SuperRembo @ 23 March 2008, 12:29
Nice tutorial.

But with a couple of modifications your code would be much cleaner and easier to understand.

    * Put the code that collects the data from hostip.info in a seperate function.
    * Let php write just a javascript array with the data you need to create the markers. Then let javascript build the markers using that data.
    * You could use json_encode() to build the array (requires PHP 5.2)
    * Use the Google MarkerManager to create the markers. This is much faster if you need to craete a large number of markers.
   



Nice! Score: 4 Vote:
By Thor Erik @ 25 March 2008, 10:00
This just look so cool mate :)Could be done as SuperRembo said, but still cool :) Gonna do it on my own site when i get the time :D

Thanks! Score: -9 Vote:
By WyriHaximus @ 25 March 2008, 21:45
@SuperRembo -> Thank you for the suggestions, I'll dive into them and update the tutorial this week. Specialy the javascript bits :).
@Thor Erik -> Looking forward to the result.

Updated Score: -3 Vote:
By WyriHaximus @ 29 March 2008, 22:29
@SuperRember -> Updated the message with your suggestions.

Is an ASP version possible? Score: 2 Vote:
By doe1967 @ 21 November 2008, 2:10

Hi WyriHaximus!

I like your map very much!  Could you create an ASP version?  Our library site is pretty popular and I would love to put your map there and link back to you, but my IT folks don't run PHP on the server so I have to stuck to ASP :(

Cheers,
S


Re: Is an ASP version possible? Score: 0 Vote:
By WyriHaximus @ 23 November 2008, 17:20

Hey doe1967

Personally I don't know any ASP. But maybe your IT folks can fabricate the code from this tutorial. It's a very basic script: Fetch the data -> parse it -> create a JSON string from the parsed information. Could contact a few of my friends if they can't make anything out of this :).

WyriHaximus


WyriHaximus's last blog post..Toplist MOD for phpBB3: Comments beta


Name:
Website:
Email:
Subject:
Message: