Friday, August 15, 2008

Use Google Maps to display a route

I will show how to display a route using google maps on a web site.

1. go to http://code.google.com/apis/maps/ and get a key for your web site, you need a google mail account, and write your web site address, if you are working locally, type the URL like http://mycomputername/, this is because the web site can be displayed from other computer on the network, if we use http://localhost/, we can only use the page locally. If you are using a public web site, use http://mywebsite/

2. With your key, add the following lines between the head tag of your web page:
<head>
<
script src="http://maps.google.com/maps?file=api&v=2&key=mykey" type="text/javascript"> < / script>


Note the key=mykey, where mykey is the key you got from the google.

3. Add the folowing script between the head tag too, of your web page:

<script type="text/javascript">
function initialize()
{
var map;
//Verify if the browser is compatible
if (GBrowserIsCompatible()) {
//Create the map object, for the div with id map_canvas
map = new GMap2(document.getElementById("map_canvas"));
//Set the center of the map and the initial zoom
map.setCenter(new GLatLng(5.971217,-74.95697), //Center
6 // zoom from 1 to 15
);
//Create the line secuence
var polyline = new GPolyline([
new GLatLng(6.252507, -75.583191),
new GLatLng(6.342597, -75.555725),
new GLatLng(6.247046,-75.421143),
new GLatLng(6.118708, -75.187683),
new GLatLng(5.971217,-74.95697),
new GLatLng(5.807292, -74.602661),
new GLatLng(5.20857,-74.742737),
new GLatLng(4.646920, -74.093170)], //Line points array
"#ff0000", //Color for the line
5 //width
);
map.addOverlay(polyline); //Add the line to the map
//Add mark for the start
map.addOverlay(new GMarker(new GLatLng(6.252507, -75.583191)));
//Add mark for the end
map.addOverlay(new GMarker(new GLatLng(4.658555, -74.100037)));
//Create the map control to show diferent type of the map
var mapControl = new GMapTypeControl();
//Add the control to the map
map.addControl(mapControl);
//Add zoom in/out control
map.addControl(new GLargeMapControl());
}
}
< /script>

4. Asign the onload event to the body, the function initialize:
<body onload="javascript:initialize();">


5. Add the following div to the body, the div size will be the size of your map window in the explorer:


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


note the div id, is the same used when creating the map object.

that's all, browse your web and enjoy the google maps.

No comments: