Bookmark and Share

Simple Map Example Google Maps Api Tutorial

With a few lines of code, you can add Google Maps into your website.
There are 3 basic steps.

  1. In your html, between the HEAD tags, put the following code.
    <script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=YOUR-GOOGLE-MAPS-API-KEY-HERE"
                type="text/javascript"></script>
        <script type="text/javascript">
    
        function initialize() {
          if (GBrowserIsCompatible()) {
            var map = new GMap2(document.getElementById("mymap"));
            map.setCenter(new GLatLng(40.756054, -73.986951), 12);
            map.setUIToDefault();
          }
        }
    
        </script>
    
    
  2. Second, in your html, between the BODY tags, put the following code.
    
    <div id="mymap" style="width: 480px; height: 320px"></div>
    
    
  3. Finally, in your html, we must initialize our map html body onload event.
    
    <body onload="initialize()" onunload="GUnload()">
    
    

Description of Map Javascript Code

var map = new GMap2(document.getElementById("mymap"));
We create a map object from GMap2 class, in the constructor of the GMap2, we define the div id where the map will be created in.

map.setCenter(new GLatLng(40.756054, -73.986951), 12);
After we create our map object, we use the setCenter method to define the center of map on load. setCenter method gets a GLatLng object in it. First parameter is the latitude, second one is the longitude of the point.

map.setUIToDefault();
setUIToDefault method creates the default user interface controls of the map, like zoom in out control, map type controls. You can also add these controls manually.


Output of Google Maps Api Simple Example

We will get our map like shown below.