Thursday, October 12, 2006

Using Google Maps API - Basic Map Part.1

Here's a quick start guide of using Google Map API.

Before Started

  1. Sign up for the Google Maps API
  2. Copy the generated key
  3. Prepare to write a standards-compliant XHTML page with an appropriateDOCTYPE.

Get Started

Let's create a map indicating San Francisco International Airport (SFO).
First, include Google Maps JavaScript code source and your CSS in <head> section of HTML.

<script src="http://maps.google.com/maps?file=api&v=2&key=COPY_THE_KEY"
      type="text/javascript"></script>

<style type="text/css">
#mapSFO {height: 300px; width: 350px;}
</style>

Next, in <body>, create a placeholder of a map within a <div> with the map ID ("mapSFO").

Then creates a JavaScript GMap2 object to display a map. This GMap2 class represents a single map on the page. The center location of the map is defined in the next line, by latitude and longitude. The second parameter indicates the zoom level. 0 is most zoomed out and 17 is most detailed. (You can find any Latitude and longitude you want from geocoder.us)

<div id="mapSFO"></div>

<script type="text/javascript">
  //<![CDATA[ 
  var map = new GMap2(document.getElementById("mapSFO"));
  map.setCenter(new GLatLng(37.632934, -122.392159), 12);
</script>

View in browser. Now the map of SFO area is displayed.

Adding Controls

Optionally, you can add controls to the map with the addControl method.

  map.addControl(new GLargeMapControl());
  map.addControl(new GMapTypeControl());
  map.addControl(new GScaleControl());

See how the controls are added:

Also try; GSmallMapControl to see how it looks like!

Display a Marker

Displaying map markers is defined by GMarker. This uses the default red Google Maps icon unless specified. In this example, I use GLatLang method to define the location of SFO, since I've set the center of the map slightly off in the beginning. You can use getCenter() method to display a marker at center.
Finally, call addOverlay() method to dispaly thr marker icon.

  var marker = new GMarker(new GLatLng(37.622934, -122.392159));
  map.addOverlay(marker);

This is how it looks like in browser:

See the entire XHTML

OK. I will post the rest later when I have time.
(Next: Using Custom Icons, and Opening an Info Window)

No comments: