11/21/12

Classic ASP Plotting new visitor location on a google static map

I've been intrigued by the possibility of plotting my web registrants physical location on a map for a while so I thought I'd give it a try and see what was required to make this happen. There are two tools that I ended up using:

1. Google static maps API. Really easy to use - basically just construct the URL to the google map image and you are off and running.

2. Get the visitor location (lat longitude) from their IP address. This was a bit trickier.

Getting started:

1. Visit https://developers.google.com/maps/documentation/staticmaps/ and read up on the creation of a google static map. In my case I stuck with the most basic implementation to keep things easy.


2. After searching for a while I found the best way to get from IP address to location was to use this web service: http://ipinfodb.com/ This service allows you to call an HTTP address and get back physical location information. The basic idea it to call the infodb URL like so:

URL = "http://api.ipinfodb.com/v3/ip-city/?key=" & locationKEY & "&ip=" & UserIPAddress

The result if you simply browse to this address is a semi-colon delimited string containing details like city/state and Lat;Long.

What I did was to create a classic asp function that returned the Lat,Long position like so:

Function getPosition(UserIPAddress)

URL = "http://api.ipinfodb.com/v3/ip-city/?key=" & locationKEY & "&ip=" & UserIPAddress


Set xmlHttp = Server.Createobject("MSXML2.ServerXMLHTTP")
    xmlHttp.Open "GET", URL, False
    xmlHttp.setRequestHeader "User-Agent", "asp httprequest"
    xmlHttp.setRequestHeader "content-type", "application/x-www-form-urlencoded"
    xmlHttp.Send
    getHTML = xmlHttp.responseText
    xmlHttp.abort()
    set xmlHttp = Nothing   


 arrLocation = SPLIT(getHTML,";")


 strLatitude = arrLocation(8)
 strLongitude = arrLocation(9)

 strCoordinatesTemp = strLatitude & "," & strLongitude

 getPosition = strCoordinatesTemp

END FUNCTION

Once this function was created, all I had to do was iterate through my latest visitors IP address to generate the actual map

'--get most recent 5 locations
sqlGet = "select top(5) pr_ip_address,pr_index from tProfile order by pr_index desc"
set objRsLocations = objConn.Execute(sqlGet)

DO WHILE NOT objRsLocations.EOF


strCoordinates = strCoordinates & "%7C" & getPosition(objRsLocations("pr_ip_address"))
objRsLocations.MoveNext

LOOP

Once that was done - just append the coordinates to the google static maps api url and you are good to go:

<img src=http://maps.googleapis.com/maps/api/staticmap?size=300x300&markers=color:blue%7Clabel:%7C<%=strCoordinates%>&sensor=true>

The result?



No comments:

Post a Comment