Tuesday, March 13, 2007

Hello World the Google Map API Way: Adding Controls

In the last post I had said I wanted to add something extra to the Hello world of GMap. The extras are controls. So the second part is:

2. Adding Controls to the map:

The map looks plain without the controls for scaling and mapping. So I decided to jazz it up with the following controls:

i. GSmallMapControl:

It shows a control with four buttons to pan(move the map) in four directions alongwith buttons to zoom in and out. The constructor is GSmallMapControl().

ii. GMapTypeControl:

It provides the control to change the type of map. The types are map, satellite image and hybrid which shows map superimposed on satellite image. GMapTypeControl() is the constructor.

iii. GScaleControl:

As the name suggests, it shows a scale within the map.

So how to add them to the map? The way is pretty simple- use the addControl() method of GMap2 instance. Here is the way in code:

function load() {

if (GBrowserIsCompatible()) {

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

//add the controls to the map

map.addControl(new GSmallMapControl());

map.addControl(new GMapTypeControl());

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

map.addControl(new GScaleControl());

}

}

If you have observed, there is a difference in adding GScaleControl when compared to others. The first two controls (for that most of the controls that I have tested) are added before setting the center of the map where as the GScaleControl() is set after the center of the map has been set. What would have happened if I had called it before setting the center? The result would have been a blank page with a JavaScript error. That’s what happened with me. If you get any different result please share.

That’s it for this post. Next I would be looking at event handling in Google Map.

No comments: