Sunday, March 4, 2007

Hello World - The Google Maps Way

Last week I had said that I would be cooking up a "Hello World" kind of app. I did it. There were two parts:

  1. Display default location provided by GMap API:

In nutshell, just make the sample app provided by Google while registration, work on my local system. It also clarified one of my doubts - where is the API library of GMap located? 'Coz it was not provided when I registered. For some, it may be a silly question. Ok. So the answer is in the following line:

<script src=http://maps.google.com/maps?file=api&v=2&key=[yourkey]"

type="text/javascript"></script>

The src attribute is pointing to the place where APIs are available. The place is maps.google.com – the site of Google maps. Along with the URL key received while registering with Google maps. Next comes the implementation of custom logic. It starts with the function load():

<script type="text/javascript">

//<![CDATA[

function load() {

}

//]]>

</script>

The next step is to ensure browser compatibility with client browser. This is done using GBrowserIsCompatible().

<script type="text/javascript">

//<![CDATA[

function load() {

if (GBrowserIsCompatible()) {

}

}

//]]>

</script>

Once compatible browser is found, then an instance of GMap2 class is created. The parameter passed id the div object in which the map has to be shown:

<script type="text/javascript">

//<![CDATA[

function load() {

if (GBrowserIsCompatible()) {

var map = new GMap2(document.getElementById("map"));

}

}

//]]>

</script>

The last step is to display the map using setCenter() method of GMap2. the method takes latitude , longitude and zoom factor as parameters. Of these zoom is optional.

<script type="text/javascript">

//<![CDATA[

function load() {

if (GBrowserIsCompatible()) {

var map = new GMap2(document.getElementById("map"));

map.setCenter(new GLatLng(31.122027, 77.111664), 13);

}

}

//]]>

</script>

The last but not least is the HTML especially the div part:

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

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

</body>

The load() has to be called in body’s onLoad is obvious. Calling GUnload() is a good practice to avoid memory leaks. That’s for the first part.

No comments: