Using Google Maps to show the geographical location of your website's visitors
Part V – Setting up the map
Now comes the fun part – actually creating the map!
We need to include the actual JavaScript from Google (You'll need your own API key):
<script src="http://maps.google.com/maps?file=api&v=1&key=YOURKEYHERE" type="text/javascript"></script>
We’ll need a DIV to be the container for the map, it’ll look something like this:
<div id="map" style="width: 400px; height: 400px"></div>
We’ll be setting up the map and adding all the values using JavaScript. First, lets setup our icons – I’m creating one that is green (for the current user) and one that is red (for all other users):
<script type="text/javascript">
//<![CDATA[
var greenIcon = new GIcon();
greenIcon.image = "http://labs.google.com/ridefinder/images/mm_20_green.png";
greenIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
greenIcon.iconSize = new GSize(24, 40);
greenIcon.shadowSize = new GSize(22, 20);
greenIcon.iconAnchor = new GPoint(6, 20);
greenIcon.infoWindowAnchor = new GPoint(5, 1);
var redIcon = new GIcon();
redIcon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
redIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
redIcon.iconSize = new GSize(24, 40);
redIcon.shadowSize = new GSize(22, 20);
redIcon.iconAnchor = new GPoint(6, 20);
redIcon.infoWindowAnchor = new GPoint(5, 1);
Now, lets instantiate the Map Object:
var map = new GMap(document.getElementById("map"));
Add a few controls to it:
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
Center and Zoom it (in this case, it centers in the middle of the US – feel free to change the latitude and longitude, although in a second we’ll be centering on the viewer’s location anyway):
map.centerAndZoom(new GPoint(-96.556061, 39.4838), 14);
You’ll notice we created a new object – GPoint. This is just an object with a latitude/longitude. We’ll be using it more later.
Now, for each visitor, we’ll need to create a marker (a GMarker object). This will consist of 3 things: The actual point (GPoint), the icon object (red or green), and the html we’ll be popping up. Let’s write a function to handle that:
function createMarker( point, html, icon ){
icon.iconSize = new GSize( iconX, iconY );
var marker = new GMarker(point,icon);
GEvent.addListener(marker,"click",function()
{
marker.openInfoWindowHtml('<div style="width:200px; text-align:left;">' + html + '</div>');
});
return marker;
}
What does that do? For each point/icon/html we pass in, it’ll create a marker with the proper icon and add an event handler to it. The event handler calls a function when the marker is clicked, and the function pops up the HTML. This function doesn’t actually place the marker on the map, it just returns a new GMarker object.
Part VI - Using the XML to create the map >>
|