1. Computing

How to Add a Google Map to Your Web Page

By

3 of 5

Adding the Map to Your Web Page
Google Maps

Google Maps

Screen shot by J Kyrnin - Map image courtesy Google

First, Add the Map Script to the <head> of Your Document

Open your web page and add the following to the HEAD of your document.

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY&sensor=SET_TO_TRUE_OR_FALSE">
</script>

Change the highlighted items to your API key, which you got in step one of this article. And change the sensor to TRUE if the web page is using an automated sensor, such as a GPS locator, to find the map location, or FALSE if you're pasting it in manually. Since we got the coordinates in step two, you can write FALSE there.

But you need to do more than just install the Maps API, you need to also add some settings and define your map on the page. In the HEAD of your document add the following script:

<script type="text/javascript">
  function initialize() {
    var mapOptions = {
      center: new google.maps.LatLng(-34.397, 150.644),
      zoom: 8
    };
    var map = new google.maps.Map(document.getElementById("map-canvas"),
      mapOptions);
  }
  google.maps.event.addDomListener(window, 'load', initialize);
</script>

Change the highlighted portion to the latitude and longitude numbers you wrote down in step two.

Second, Add the Map Element to Your Page

Once you have all the script elements added to the HEAD of your document, you need to position your map on the page. You do this by adding a DIV element with the id="map-canvas" attribute. I recommend you also style this div with the width and height that will fit on your page:

<div id="map-canvas" style="width:300px; height:300px;"></div>

Finally, Upload and Test

The last thing to do is upload your page and test that your your map displays. Here is an example of a Google map on the page. Note, because of the way the About.com CMS works, you will have to click a link to get the map to appear. This will not be the case on your page.

If your map doesn't show up, try initializing it with a BODY attribute:

<body onload="initialize()">

Other things to check if your map isn't loading include:

  • Look for typos in your JavaScript, including case. JavaScript is case sensitive.
  • Make sure that you hvae the zoom and center options set.
  • Make sure that your DIV element is on the page with the correct ID.
  • Make sure that your DIV element has a height.
See More About
  1. About.com
  2. Computing
  3. Web Design / HTML
  4. Javascript and Ajax
  5. Step 3: Adding the Map to Your Web Page - How to Add a Google Map to Your Web Page

©2014 About.com. All rights reserved.