Google Maps API Tutorial -1


Google Map API lets anyone embed maps at your webpage with JavaScript. The Maps API is a free service, available for any web site that is free to consumers. Please see their terms of use for more information.

Stating with google maps is very Simple.
1. Generate a key for your domain
2. Embed this Javascript file from google at your webpage http://maps.google.com/maps?file=api&v=2&key={YOUR_KEY} Don’t forget to replace the {YOUR_KEY} with actual key for your domain.
3. Create a div where you would like map to appear
4. Put JS code at your page to show the map.

Below code produes a map as shown in the image

  1. <script src=’http://maps.google.com/maps?file=api&amp;v=2&amp;key={YOUR_KEY}’></script>
  2. <div id="mapdiv" style="border: 1px solid #979797; width: 400px; height: 300px;">
  3. </div>
  4. <script language="Javascript">
  5. <pre>if (GBrowserIsCompatible())
  6. {
  7. var map = new GMap2(document.getElementById("mapdiv"));
  8. map.setCenter(new GLatLng(37.4328, -122.077), 13);
  9. }
  10. </script>

Note: Don’t forget to put html and body tags at your page. Otherwise map sometimes gives JS error.

If you are wondering from where I got the desired co-ordinates of city that I wanted to show, again Google maps Geo is here for your help. Use this URL http://maps.google.com/maps/geo?q=Pune,India&output=xml&key={YOUR_KEY} to find co-ordinates of any city that you want.

First Map Image

a. To Show zoom control options at left side of map use

map.addControl(new GSmallMapControl());

b. To add marker at map use GMarker function for creation of marker followed by addOverlay to addto add marker to map.

var marker = new GMarker(new GLatLng(18.520470,73.856621));

map.addOverlay(marker);

c. Want to show some message after clicking on the marker? Very simple.

GEvent.addListener(marker, “click”, function() {
var html = ‘<div style=”width: 210px; padding-right: 10px”>Hey!! This is lovely city Pune, where I work.</div>’;
marker.openInfoWindowHtml(html);
});

Wow!!! We are done. Finally this is how the map should look.

Final Map

Have you liked it? Why not help me by sharing this :
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • MySpace
  • Reddit
  • Slashdot
  • StumbleUpon
  • Technorati
  • TwitThis

Leave a comment

Your comment