Display Your Visitors Location using Google Maps

If you have ever seen a map on a web site showing your location then you know what we are trying to achieve here. One of the easiest ways to do this is to use a data file provided by maxmind to look up the users IP address or a domain name / IP address the visitor entered, I will first explain the steps we need to take and the tools we will need and then a walkthrough of how to put it all together.

What you will need.

The Steps we will take.

  • Include the API and load Date file
  • Check if the user entered a custom IP address or domain name
  • If not get the visitors Ip address
  • If they entered a domain name convert to IP address
  • Validate our IP address
  • Use the provided API to communicate with the maxmind data file and retrieve the location of this IP address / domain name.
  • Using the returned data from the API overlay the co-ordinates on top of a map.
  • Add custom speech bubbles and formatting etc.

Ok so now we have all the tools we need and know the steps we are going to take let's get stuck right in. At the very top of our page we add the following code which includes our API and loads the data file as our first steps indicates we should.

include("geoipcity.inc"); // API provided for communicating with the .dat database file.
$gi = geoip_open("GeoLiteCity.dat",GEOIP_STANDARD); // load data file

Probably the most trickiest part to get right will be the validation, there are lots of different ways to validate IP addresses so if you would like to write your own IP address validation functions or you have some suggestions then please post them at the end of this article. Our validation will use the built in php function ip2Long which you can read more about here www.php.net/ip2Long

Our function is the same as the example on the php.net site apart from we will be using the gethostbyname function later on in our code.

//Simple IP address validation function
function validateIP($ipa)
{
    $valid = false;
    $ipLong = ip2long($ipa);
    if ($ipLong == -1 || $ipLong === false)
    {
    }
    else
    {
        $valid = true;
    }
    	return $valid;
} // end function

Now we have our validateIP function we can check to see if the client entered a domain or IP address for us to look up, validate it then decide whether or not to use it. We use the gethostbyname function to return an IP address if they entered a domain name. If they did not enter an IP address or domain name or the value they entered was invalid we simply use their IP address using $_SERVER['REMOTE_ADDR'] which will return the clients IP address.

if(isset($_POST['lookup']))
{
    //using gethostbyname will give us a ip address in case they entered a domain name
    $ipa = gethostbyname($_POST['ip']); 

    //validate our ip address
    if(validateIP($ipa))
    {
        //set the ip var if the ip was valid
        $ip = $ipa;
    }
    else
    {
        //this returns the clients ip address which we will use if
        //they entered an invalid ip or domain name
        $ip = $_SERVER['REMOTE_ADDR'];
        //feedback if ip address they entered was invalid
        $invalid = "Bad Ip Address";
     }
} //end of isset
else
{
    //gets the clients ip address if they did not
    //enter one for us to lookup
    $ip = $_SERVER['REMOTE_ADDR'];
}

The geoip_record_by_addr function provided by our API accepts two parameters, the data file we have already loaded and the IP address we have just validated, and returns an object which we then save a reference to in the $record variable and finally close the connection to the data file.

//use the geoip_record_by_addr function of the api passing in
//the ip address and the data file
$record = geoip_record_by_addr($gi, $ip);
geoip_close($gi); // close the connection to the .Dat file
?>

We now start the HTML document including our google API key, please not that you are able to use google maps locally for testing without and API key but our script will return 127.0.0.1 (loopback IP) as your IP address which will not display a map so you will need to hard code some test IP's in to test locally.

Our last few steps are all done using JavaScript to overlay our latitude and longitude over the map and then add our marker. We can also customise things such as controls, map types and events such as mouse scroll. The code should be pretty straight forward if you read the comments.

That's it we are nearly done, just add this form and the div for the map. Don't forget to add the load function to the onload event of your body tag.

//if there was something wrong with the ip address display the error if(isset($invalid)) { echo $invalid; } ?>

I am looking forward to some positive feedback on this article and hopefully some suggestions of other useful things you may have achieved and would like to share while using Google maps. I managed to get reverse look ups working for latitude and longitudes as well ISP identification using more of Maxminds data files.

Note: The location showed will be the location where your ISP or the server of the domain is located.

Here are all the files needed not including the Maxminds data file which you will have to download from the link above. Download Here

Comments

Permalink

hi i'm a newbie and i already made a map using v2 but the problem is I don't know how to label my arkers(balloons), can you show me samples? I'm using php for manipulating the marker...

Permalink

Sorry for the slow reply, missed your comment somehow. Not sure if you got this fixed but you should probably have a look at the new Google Maps API, version 3.

Permalink

Hello, nice job with the script, very useful.
The map is working and it show me the location with marker and balloon, but entering a different ip and look up for it, will display a white page, any idea why?
Thank you again!

Permalink

Ok, i found out the problem.
The IP address validation was missing from the map.php file.
I put the code and everything is ok.
Thank you again, you are the best.

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.