Zymic

Webmaster resources

Follow us on Twitter!

Hosting status updates - Click here

PHP & MySQL

Free Tutorials » PHP & MySQL » Create a Visitor Map

This tutorial aims to outline the process of creating a visitor map you sometimes see on MySpace profiles.

Step 1

This tutorial aims to outline the process of creating a visitor map you sometimes see on MySpace profiles. It does not aim to be a definitive guide on creating an incredibly precise map, but rather shows an example of the process involved and how different APIs and data can work together. Due to the nature of the external services used, it is not going to be entirely accurate, however it generally bodes quite well and is accurate to country almost all the time. Eventually, this is the kind of output we'll get:

Step 1 diagram

We will be using three external services: hostip.info, maps.yahoo.com and maps.google.com. The visitor's IP address is gathered, and this is then fed to the hostip.info API. If its location can be determined, then it is passed to the Yahoo Maps API to gather its geographic coordinates. Note: I am aware that the Yahoo API can be bypassed as the hostip.info API provides geographic coordinates, but at the time of writing no such feature was available. However, by the end of the tutorial you should have learned enough to add this functionality in yourself. These will then be plotted using the Google Maps API to create the actual map display. If the location can not be determined, the user is not plotted on the map, so it heavily depends on the APIs involved. A pseudo-flowchart may look something as follows:

Step 1 diagram

What it is advised you should know before using this tutorial:

1) At least a basic understanding of PHP, especially functions and data types (array, boolean etc.)

2) An understanding of databases, namely MySQL and its integration with PHP scripts

3) Hopefully knowledge of what the Document Object Model and XML are, though these are not a necessity

Step 2

The first thing to do is sign up for a Google Maps API key. You can do this here; be sure to read the restrictions and the terms of use.

Step 3

Create a database, naming it something like 'visitormap', and assign it a user. We will have five fields; id, ip, location, longitude and latitude; all hopefully self-explanatory. So, execute the following SQL:

CREATE TABLE `visitor_map` (
 `id` INTEGER auto_increment,
 `ip` VARCHAR(15) NOT NULL,
 `location` VARCHAR(32) NOT NULL,
 `longitude` FLOAT NOT NULL,
 `latitude` FLOAT NOT NULL,
 PRIMARY KEY (`id`)
);

For ease of use, we'll now create a configuration file. Create a file called config.php and insert the following, changing the constant values to suit your database setup and Google Maps API key.

<?php
 
define('DB_HOST', 'localhost');  // Database host
define('DB_NAME', 'visitormap'); // Database being used
define('DB_USER', 'david2012');  // Database user
define('DB_PASS', 'password56'); // Database user's password
 
/* Your Google Maps API key */
define('API_KEY', 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
 
?>

Step 4

We want to create a function in which we can house the code to give us the coordinates and other information we need to create the map display. If you are not very strong on functions, view the Zymic tutorial on functions or visit the PHP manual page. Create a file named visitormap.php with the following (explained afterwards):

<?php
 
function IPtoCoords($ip)
{
	$dom = new DOMDocument();
 
	$ipcheck = ip2long($ip);
    if($ipcheck == -1 || $ipcheck === false)
    	trigger_error('Invalid IP, what are you doing? :|', E_USER_ERROR);
	else
		$uri = 'http://api.hostip.info/?ip=' . $ip;
 
	$dom->load($uri);
	$location = (strpos($dom->getElementsByTagName('name')->item(1)->nodeValue, 'Unknown') === false)
					? $dom->getElementsByTagName('name')->item(1)->nodeValue
					: $dom->getElementsByTagName('countryAbbrev')->item(0)->nodeValue;
 
	if($location == 'XX')
		return false;
	else
	{
		$dom->load('http://local.yahooapis.com/MapsService/V1/geocode?appid=YahooDemo&location=' . $location);
		$longitude = $dom->getElementsByTagName('Longitude')->item(0)->nodeValue;
		$latitude  = $dom->getElementsByTagName('Latitude')->item(0)->nodeValue;
		return array('location' => $location, 'longitude' => $longitude, 'latitude' => $latitude);
	}
}
 
?>

Step 5

<?php
 
function IPtoCoords($ip)
{
	$dom = new DOMDocument();
}
 
?>

Here we create a function called 'IPtoCoords'. Eventually, it will return us an array of the following values: location (be it city or country--however accurate the hostip.info API is), longitude and latitude. Inside the function, PHP's DOMDocument object is instantiated (an instance created of; in this case assigned to the $dom variable) using the 'new' keyword, and this will provide us with methods to grab data from XML outputted from both the hostip.info and Yahoo Maps APIs.

Step 6

<?php
 
function IPtoCoords($ip)
{
	/*$dom = new DOMDocument();*/
 
	$ipcheck = ip2long($ip);
    if($ipcheck == -1 || $ipcheck === false)
    	trigger_error('Invalid IP, what are you doing? :|', E_USER_ERROR);
	else
		$uri = 'http://api.hostip.info/?ip=' . $ip;
 
}
 
?>

We want to make sure the IP is valid, just in case the user is trying something a bit funny. So, we use the PHP function ip2long to check this - it works by converting the IP to a proper address, and then if this either returns -1 or a boolean value of false, we can assume that the given address is invalid. If the IP is invalid, we trigger an error message, however if the IP is indeed correct, we form a URI out of the IP in format http://api.hostip.info/?ip=IP and assign it to a variable for later use - this is the first step in using hostip.info's API.

Step 7

<?php
 
function IPtoCoords($ip)
{
	/*$dom = new DOMDocument();
 
	$ipcheck = ip2long($ip);
    if($ipcheck == -1 || $ipcheck === false)
    	trigger_error('Invalid IP, what are you doing? :|', E_USER_ERROR);
	else
		$uri = 'http://api.hostip.info/?ip=' . $ip;*/
 
	$dom->load($uri);
	$location = (strpos($dom->getElementsByTagName('name')->item(1)->nodeValue, 'Unknown') === false)
					? $dom->getElementsByTagName('name')->item(1)->nodeValue
					: $dom->getElementsByTagName('countryAbbrev')->item(0)->nodeValue;
}
 
?>

First we call the DOMDocument's 'load' method, which loads an external XML file. In this case, it's the $uri variable we created in the previous step. The next section is a bit more complex and uses a ternary operator (short-hand if/else block) Basically, we have the $location variable at the beginning, and will assign it values based on the if/else block. We use the strpos function to test if the second 'name' tag in the XML file contains the word 'Unknown' as returned by the API, using the DOM's getElementsByTagName method. If it does, we use the ISO 3166 country code returned in the 'countryAbbrev' tag, but if not, we use the second 'name' tag as it contains a known location.

Step 8

<?php
 
function IPtoCoords($ip)
{
	/*$dom = new DOMDocument();
 
	$ipcheck = ip2long($ip);
    if($ipcheck == -1 || $ipcheck === false)
    	trigger_error('Invalid IP, what are you doing? :|', E_USER_ERROR);
	else
		$uri = 'http://api.hostip.info/?ip=' . $ip;
 
	$dom->load($uri);
	$location = (strpos($dom->getElementsByTagName('name')->item(1)->nodeValue, 'Unknown') === false)
					? $dom->getElementsByTagName('name')->item(1)->nodeValue
					: $dom->getElementsByTagName('countryAbbrev')->item(0)->nodeValue;*/
 
	if($location == 'XX')
		return false;
	else
	{
		$dom->load('http://local.yahooapis.com/MapsService/V1/geocode?appid=YahooDemo&location=' . $location);
		$longitude = $dom->getElementsByTagName('Longitude')->item(0)->nodeValue;
		$latitude  = $dom->getElementsByTagName('Latitude')->item(0)->nodeValue;
		return array('location' => $location, 'longitude' => $longitude, 'latitude' => $latitude);
	}
}
 
?>

The first two lines are performing a check on the location. If our $location variable was given the contents of the 'countryAbbrev' tag, it may have resolved to 'XX' as provided by the hostip.info API - meaning the country could not be determined. If this is the case, we return a boolean value of false. If not, we begin utilising the Yahoo Maps API, using a similar convention to the hostip.info one.

Again, we load a URI into the DOMDocument's 'load' method, this time loading a Yahoo URI with a 'location' GET value of what is held by our $location variable. The API is clever and the GET value can be a wide range of things, including street, city, state, zip, country (including ISO 3166 code) and various combinations. In our case it will generally either be a city, or if this could not be resolved by the hostip.info API then a country code. With this new URI loaded, we again use the getElementsByTagName method to grab the contents of the first 'Longitude' and 'Latitude' tags with the nodeValue property (which grabs the text content contained within the tag.)

Finally, we set the return values of the function. It is an associative array in the format location: city or country, longitude: location longitude, latitude: location latitude. This will then be used for entering into our database and eventually displaying on a map.

Step 9

Now that we can successfully gain the visitor's location, we can use this to build our finished visitor map. Create a new file (for instance viewmap.php). At the top of your file, put the following:

<?php
 
// Include the configuration and function files we created
require 'config.php';
require 'visitormap.php';
 
// Establish a MySQL connection and select our database using values contained in config.php.
mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_NAME);
 
// Assign the user's IP to a variable and plot it into our function, whose return value is assigned to $userinfo
// Remember, the user's IP is not to be trusted 100%
$ip = $_SERVER['REMOTE_ADDR'];
$userinfo = IPtoCoords($ip);
 
// We select the location column from the database
$user = mysql_query('SELECT `location` FROM `visitor_map` WHERE `location` = \'' . $userinfo['location'] . '\'');
// If it does NOT return a value, and the user's IP could indeed be matched...
// (This makes sure that we have no duplicate rows (which would be a waste) and can determine the visitor's location, respectively)
// ...We insert the values returned by our function into the database, escaping any possible dangerous input
if(!mysql_fetch_row($user) && $userinfo)
	mysql_query('INSERT INTO `visitor_map` (`ip`, `location`, `longitude`, `latitude`) VALUES (\'' . mysql_real_escape_string($ip) . '\', \'' . $userinfo['location'] . '\', ' . $userinfo['longitude'] . ', ' . $userinfo['latitude'] . ')') or die(mysql_error());
 
?>

This is quite simple so explanation is contained within the file itself.

Step 10

Now that we've inserted the user's data into our database, we select all of this information and plot it on a Google Maps object. In the file you just created, you can now create the HTML of the page, including whatever content you wish. The Google Maps API requires the following, however:

1) Include the JavaScript file required for Google Maps, using your API key. Insert the following into the <head> of your HTML page:

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

2) Certain functions must be triggered on page load and unload. You can use JavaScript event handlers if you want to separate structure from behaviour, but the easiest method is to put the information into the <body> tag:

<body onload="load();" onunload="GUnload();">

Step 11

Now we'll be using the actual Google Maps API to plot the data, which is done using JavaScript. In the head of your HTML document, put the following:

<script type="text/javascript">
//<![CDATA[
 
function load()
{
	if(GBrowserIsCompatible())
	{
		var map = new GMap2(document.getElementById('map'));
		map.addControl(new GLargeMapControl());
		map.setCenter(new GLatLng(0, 0), 1);
 
		<?php
 
		$query = mysql_query('SELECT `longitude`, `latitude` FROM `visitor_map`');
		while($row = mysql_fetch_array($query))
		{
		?>
			map.addOverlay(new GMarker(new GLatLng(<?php echo $row['latitude']; ?>, <?php echo $row['longitude']; ?>)));
 
		<?php
		}
 
		?>
	}
}
 
//]]>
</script>

We start off defining a 'load' function, which is triggered on page load, shown in the previous step. Then, an if statement is used to see if the user's browser supports Google Maps. The next line assigns the map canvas to an HTML element, in this case with an ID of 'map', using the DOM's getElementById method. The following two lines add a large zoom/pan control to the map object and set the default centre of the map when loading to 0 (the centre of the world), respectively.

Finally, we use some PHP to draw the longitude and latitude coordinates from our database, then loop the results. On each successive loop, we create a marker (the red pointer showing the visitor locations) using the addOverlay method provided by the Google Maps API. The following JavaScript is echoed, albeit with the values contained in our database:

map.addOverlay(new GMarker(new GLatLng(LATITUDE, LONGITUDE)));

All of this is covered in the Google Maps API documentation.

Step 12

Now that we have our JavaScript function which plots the data set up, all we have to do is define a canvas for the map to be displayed. In the 'load' function, we specified an HTML element of ID 'map', so make sure this reflects the ID of the element you'll be using to display the map:

<div id="map" style="width: 500px; height: 300px"></div>

Basic inline CSS styles are applied to give a width and a height to the canvas, but it's not a necessity. There we have it! Your visitormap should work. If not, download the provided example and compare the code with your own.

Step 13

Conclusion:

1) Our script has some limitations. Primarily, the accuracy is not going to be 100% and can be as vague as a country or city. Secondly, if the user's IP can't be pinpointed, they are not plotted, rendering the visitor map unreliable regarding visitor data (hits etc.).

2) Performance is a big issue. The script uses three external APIs, and on this note can be quite slow (though luckily we are storing the data returned from 2 of the APIs in a database, meaning in general only 1 API is used for the display). This tutorial was meant to demonstrate some coding examples, and realistically if you have millions of visitors then your database is going to get very large, the page will end up huge and of course the map will get crowded.

3) The idea is useful though. It could be extended very easily into a unique guestbook type of script by changing the database structure (accommodating for name, email address, message etc.), and using a message pointer provided by the Google Maps API to show the message left by the visitor when their location marker is clicked. It opens up the gates for some interesting concepts.

Tutorial comments

10.11.2014 -

ocaab3 says …

Hi! everybody, Our shop cheap wholesale and retail Air Jordans shoes,Air Max Shoes,Designer Handbags,Jewelry,Belts,hats,Jeans,Sports Jerseys,sunglasses online,high quality goods and Low price,outlet online,free shipping, Welcome to ==== http://www.fashionfast.net ==
nike air max shoe $42
Air Jordan (1-24) shoes $42
Jordan (1-22)&2014 shoes $42
Nike shox (R4, NZ, OZ, TL1, TL2, TL3) $38
Handbags ( Lv fendi D&G MK) $42
T-shirts (polo, ed hardy, lacoste) $14
Jean (True Religion, ed hardy, coogi)$34
Sunglasses ( Oakey, coach, Gucci, Armaini)$12
New era cap $16
Jewelry $15
FREE SHIPPING
http://www.fashionfast.net

http://www.fashionfast.net

http://www.fashionfast.net

http://www.fashionfast.net
http://www.fashionfast.net

http://www.fashionfast.net

http://www.fashionfast.net

http://www.fashionfast.net

===( http://www.fashionfast.net )===

===( http://www.fashionfast.net )===

===( http://www.fashionfast.net )===

===( http://www.fashionfast.net )===

===( http://www.fashionfast.net )===

===( http://www.fashionfast.net )===
This is a shopping paradise
We need your support and trust

18.10.2014 -

3dwalkthrough01 says …

hi i M new user...give me a more advises and increase.

https://www.architectural3dstudio.com/3d-exterior-rendering.html

06.10.2014 -

jennica says …

ou nga

16.09.2014 -

polo2014 says …

http://www.shopbestgoods.com/
http://www.nike-jordanshoes.com/
http://www.beatsbydreoutlet.net/
http://www.michaelkorsus.com/
http://www.polo-tshirts.com/
http://www.northsclearance.com/
http://www.ralph-laurensale.com/
http://www.gucci-shoesuk2014.com/
http://www.michael-korsusa.com/
http://www.polo-outlets.com/
http://www.ralph-laurenhome.com/
http://www.marcjacobsonsale.com/
http://www.mcmworldwides.com/
http://www.salongchamppairs.com/
http://www.canada-gooser.com/
http://www.burberryoutlet2014.com/
http://www.michaelkors.so/
http://www.hermes-outletonline.com/
http://www.oakley-sunglassfactory.com/
http://www.north-faceoutlets.net/
http://www.moncler-clearance.com/
http://www.woolrich-clearance.com/
http://www.barbour-jacketsoutlet.com/
http://www.moncler-jacketsoutletonline.com/
http://www.monsterbeatsbydres.net/
http://www.louis-vuittonblackfriday.com/
http://www.lv-guccishoesfactory.com/
http://www.mcmoutlet-jp.com/
http://www.cheapdiscountoutlet.com/
http://coachoutlet.iwopop.com/
http://www.coachsfactoryoutlet.com/
http://www.coach-blackfriday2014.com/
http://www.coach-storeoutletonline.com/
http://www.coach-factorysoutletonline.com/
http://www.coachccoachoutlet.com/
http://www.coach-factories.net/
http://www.coach-pursesoutletonline.com/
http://www.llouisvuitton-factory.net/
http://www.coach-outletsusa.com/
http://www.mksfactoryoutlet.com/
http://www.zxcoachoutlet.com/
http://www.mischristmas.com/
http://www.misblackfriday.com/
http://www.bestcustomsonline.com/
http://www.newoutletonlinemall.com/
http://www.clickmichaelkors.com/
http://www.cmichaelkorsoutlet.com/
http://www.ralphlaurenepolo.com/
http://michaelkorsoutlet.mischristmas.com/
http://mcmbackpack.mischristmas.com/
http://monsterbeats.mischristmas.com/
http://northfaceoutlet.mischristmas.com/
http://mk.misblackfriday.com/
http://coachoutlet.misblackfriday.com/
http://coachfactory.misblackfriday.com/
http://uggaustralia.misblackfriday.com/
http://coachpurses.misblackfriday.com/
http://coachusa.misblackfriday.com/
http://coach.misblackfriday.com/
http://michaelkorss.misblackfriday.com/
http://michaelkors.misblackfriday.com/
http://airmax.misblackfriday.com/
http://michael-kors.misblackfriday.com/
https://www.facebook.com/pages/Coach-Factory-Outlet-Online-Store-Michael-Kors-Outlet-Online-Sale-75-Off/712060898859091
https://www.facebook.com/pages/Ralph-Lauren-Polo-Outlet-Online-Sale/1404100279810690

16.09.2014 -

polo2014 says …

http://www.shopbestgoods.com/
http://www.nike-jordanshoes.com/
http://www.beatsbydreoutlet.net/
http://www.michaelkorsus.com/
http://www.polo-tshirts.com/
http://www.northsclearance.com/
http://www.ralph-laurensale.com/
http://www.gucci-shoesuk2014.com/
http://www.michael-korsusa.com/
http://www.polo-outlets.com/
http://www.ralph-laurenhome.com/
http://www.marcjacobsonsale.com/
http://www.mcmworldwides.com/
http://www.salongchamppairs.com/
http://www.canada-gooser.com/
http://www.burberryoutlet2014.com/
http://www.michaelkors.so/
http://www.hermes-outletonline.com/
http://www.oakley-sunglassfactory.com/
http://www.north-faceoutlets.net/
http://www.moncler-clearance.com/
http://www.woolrich-clearance.com/
http://www.barbour-jacketsoutlet.com/
http://www.moncler-jacketsoutletonline.com/
http://www.monsterbeatsbydres.net/
http://www.louis-vuittonblackfriday.com/
http://www.lv-guccishoesfactory.com/
http://www.mcmoutlet-jp.com/
http://www.cheapdiscountoutlet.com/
http://coachoutlet.iwopop.com/
http://www.coachsfactoryoutlet.com/
http://www.coach-blackfriday2014.com/
http://www.coach-storeoutletonline.com/
http://www.coach-factorysoutletonline.com/
http://www.coachccoachoutlet.com/
http://www.coach-factories.net/
http://www.coach-pursesoutletonline.com/
http://www.llouisvuitton-factory.net/
http://www.coach-outletsusa.com/
http://www.mksfactoryoutlet.com/
http://www.zxcoachoutlet.com/
http://www.mischristmas.com/
http://www.misblackfriday.com/
http://www.bestcustomsonline.com/
http://www.newoutletonlinemall.com/
http://www.clickmichaelkors.com/
http://www.cmichaelkorsoutlet.com/
http://www.ralphlaurenepolo.com/
http://michaelkorsoutlet.mischristmas.com/
http://mcmbackpack.mischristmas.com/
http://monsterbeats.mischristmas.com/
http://northfaceoutlet.mischristmas.com/
http://mk.misblackfriday.com/
http://coachoutlet.misblackfriday.com/
http://coachfactory.misblackfriday.com/
http://uggaustralia.misblackfriday.com/
http://coachpurses.misblackfriday.com/
http://coachusa.misblackfriday.com/
http://coach.misblackfriday.com/
http://michaelkorss.misblackfriday.com/
http://michaelkors.misblackfriday.com/
http://airmax.misblackfriday.com/
http://michael-kors.misblackfriday.com/
https://www.facebook.com/pages/Coach-Factory-Outlet-Online-Store-Michael-Kors-Outlet-Online-Sale-75-Off/712060898859091
https://www.facebook.com/pages/Ralph-Lauren-Polo-Outlet-Online-Sale/1404100279810690

View all user comments for this tutorial.

Tutorial statistics

Date added:
05.01.2008
Author:
Tom
User rating:
4/5
Rate tutorial:
Total views:
16874
Total comments:
383

Advertisements