Add a Google Map to your Website

Monday, October 08, 2007

I recently used Google Maps API on my college website. It was somewhat tedious to read the API documentation and figure out how to code a simple map. So, here I'm writing a basic tutorial for adding a location map on your website.

Start by signing up for an API key. Go through this "Hello World" example of the Google Maps API. For a start, copy this code and run it. The first thing you would need to modify is the following:

map.setCenter(new GLatLng(37.4419, -122.1419), 13);
You would need the latitude and longitude of the desired location. To find out the coordinates of your desired location use the Google Map Search, go to your desired location and right click on the directions option to find the coordinates. The second argument (13) specifies the zoom level of the map.

The above code would produce the map of the desired location on your browser screen. Now lets see how to add-on some features on your map.


Adding an Info Window
:

An info window is a call-out text from a particular location. To add an info window, just add the following line of code in the initialize() method:
map.openInfoWindowHtml(map.getCenter(), "any html formatted text here");
You can also add tabbed info windows, which I'm not discussing here to keep this tutorial simple.
Class Reference: GInfoWindow, GInfoWindowTab


Adding Controls:

Controls are a set of buttons which allow you to perform specific functions. To allow users to switch between different Map Types, viz. Map, Satellite and Hybrid; use the following statement in the initialize() method:
map.addControl(new GMapTypeControl());
You can add various other controls to the Map. To view the complete list of available controls, view the class reference.
Class Reference: GControl


Adding a Marker:

A marker is used to mark a position on the map. For adding a marker on a specific point add the following lines of code in the initialize() method:
var point = new GLatLng(28.631749, 77.116578);
map.addOverlay(new GMarker(point));
The above code places a marker on the desired point. You can also define a custom image as a marker using the GIcon class.
Class Reference: GMarker


These are just a few of the features of the Google Map API. These would be sufficient if you are planning to implement a simple location map on your website. For more advanced features of the Google Maps API, refer to the API Documentation.

1 comments:

Anonymous said...

Thanks. The tutorial helped me a lot.
Mike.

Post a Comment