How to Embed Google Maps on your Website

How to Embed Google Maps, a rich interactive map, to your websites from basic copy and paste code to a full API integration.

By Tim Trott | HTML & CSS Tutorials | February 8, 2010
1,985 words, estimated reading time 7 minutes.

Google offers a multitude of methods for adding rich interactive maps to your websites from basic copy-and-paste code to a full API for a completely custom user experience. This tutorial gives you an overview of the methods and shows you how to get started adding maps.

We Are Here

By far the quickest and easiest method is to copy and paste the code directly from Google Maps. This is especially useful for sharing a specific location, for example, a head office address. This can be done by simply setting up the Google Maps website to show the map type and zoom centred on your location and clicking on the link icon. This will then let you copy the code to share the map via a URL or embed the map on your website.

Sharing Google Maps and Embedding in Website
Sharing Google Maps and Embedding in Website

Get Directions Button

You can add a get directions feature by adding a small form to the page. This will show a text box for the user to enter their location and it will produce a directions list with a route that they can follow. You should replace "INSERT YOUR ADDRESS HERE" with your actual address or location details.

xml
<form action="http://maps.google.com/maps" method="get" target="_blank">
   <label for="saddr">Enter your location:</label>
   <input type="text" name="saddr" />
   <input type="hidden" name="daddr" value="INSERT YOUR ADDRESS HERE" />
   <input type="submit" value="Get directions" />
</form>

Embedding Maps with Google API

The first thing you need to do is acquire a Google Maps API Key which is generated on your website's URL. This key is unique and can only be used on the website specified; however, you can generate as many API keys as you like. To get an API key you will need a Google account. Head over to the Google Maps API Generator  to get your key.

Google Maps
Google Maps

Once you have your key you can start to add a map to your pages.

The single most important line of code is that of loading the API. This can be done with the line below:

xml
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=***PUT YOUR KEY HERE***" type="text/javascript">

This will load the API from the Google servers.

The next thing to do is create a placeholder on your page that will contain the map. In this example, the placeholder will be a div element with a width of 550px and a height of 350px. You can use your own dimensions and CSS for this.

xml
<div id="map" style="width: 550px; height: 350px"></div>

The next section of JavaScript can be cut & paste into your page. The only thing you may need to change is the ID for the placeholder div.

javascript
<script type="text/javascript">
function initialize()
{
  if (GBrowserIsCompatible()) 
  {
    var map = new GMap2(document.getElementById("map"));
    map.setMapType(G_SATELLITE_MAP);
    map.setCenter(new GLatLng(53.0927,-4.0725), 12);
  }
}

function addLoadEvent(func) 
{
  var oldonload = window.onload;
  if (typeof window.onload != 'function') 
  {
    window.onload = func;
  } 
  else 
  {
    window.onload = function() 
    {
      if (oldonload)  
      {
        oldonload();
      }
      func();
    }
  }
}
addLoadEvent(initialize);

And that's all the script you need to get a map.

Here is an xHTML skeleton containing the necessary code to display a map. You will only need to insert your API key.

xml
<!DOCTYPE html PUBLIC "-/W3C/DTD XHTML 1.0 Transitional/EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Google Maps Example</title>
    <meta equiv="content-type" content="text/html; charset=utf-8" />
  </head >
  <body>
    <div id="map" style="width: 550px; height: 350px"></div>

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=***PUT YOUR KEY HERE***" type="text/javascript"></script>
<script type="text/javascript">
function initialize()
{
  if (GBrowserIsCompatible())
  {
    var map = new GMap2(document.getElementById("map"));
    map.setMapType(G_SATELLITE_MAP);
    map.setCenter(new GLatLng(53.0927,-4.0725), 12);
  }
}

function addLoadEvent(func)
{
  var oldonload = window.onload;
  if (typeof window.onload != 'function')
  {
    window.onload = func;
  }
  else
  {
    window.onload = function()
    {
      if (oldonload)
      {
        oldonload();
      }
      func();
    }
  }
}
addLoadEvent(initialize);
</script>

  </body>
</html>

Types of Map

You can control what type of map to show using the map.setMapType function. In this example, I'm using G_SATELLITE_MAP which is Google's aerial photography. You can also use the values below.

  • G_PHYSICAL_MAP - Normal Google Maps
  • G_SATELLITE_MAP - Satellite Photography
  • G_HYBRID_MAP - Hybrid Satellite with map overlay

You can set the map centre using map.setCenter and insert the latitude and longitude coordinates for the location. The final number (12 in this example) is used to set the zoom level with 0 being zoomed out and 20 being maximum zoom.

How to get Latitude and Longitude from Google Maps

There are a few methods to get Latitude and Longitude coordinates from maps. The easiest is to right-click on the map and select "What's Here?" which will re-centre the map and display the coordinates in the search text box. You may have to click on the green marker to get the lat/long coordinates to show.

Another way is to centre your desired location in the window and copy and paste the following JavaScript into the address bar.

javascript
javascript:void(prompt('',gApplication.getMap().getCenter()));

This will cause a little dialogue box to pop up displaying the coordinates which can be copied and pasted into your code.

Adding Controls to the Map

There are a variety of controls you can add to the map including a zoom control, navigation control and map types. They can all be added using map.addControl function. These lines should all be placed after map.setCenter in the example above.

javascript
map.addControl(new GSmallMapControl());

This will cause a small map control which has a small zoom and panning control which looks like the control below. To get any of the other views simply substitute it in place of GSmallMapControl. You can add more than one control by calling addControl again.

GSmallMapControl

GSmallMapControl
GSmallMapControl

javascript
map.addControl(new GSmallMapControl());

GSmallZoomControl3D

GSmallZoomControl3D
GSmallZoomControl3D

javascript
map.addControl(new GSmallZoomControl3D());

GLargeMapControl

GLargeMapControl
GLargeMapControl

javascript
map.addControl(new GLargeMapControl());

GLargeMapControl3D

GLargeMapControl3D
GLargeMapControl3D

javascript
map.addControl(new GLargeMapControl3D());

GScaleControl

GScaleControl
GScaleControl

javascript
map.addControl(new GScaleControl());

GMapTypeControl

GMapTypeControl
GMapTypeControl

javascript
map.addControl(new GMapTypeControl());

Adding Pins, Points and Routes to Google Maps API

So now we have maps embedded on a page, we can add pins, waypoints and routes. I'm going to expand on the examples from above.

I've set up a map view of Cheddar Gorge:

javascript
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=***YOUR KEY HERE***" type="text/javascript"></script><script type="text/javascript">function initialize() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map_canvas"));
        map.setMapType(G_SATELLITE_MAP);
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(51.2863,-2.7503), 14);
        / Extra code goes below this line

      }
}</script><div id="map_canvas" style="width: 550px; height: 350px"></div><script type="text/javascript">function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}
addLoadEvent(initialize);</script>

This will display a nice map as shown in the image below.

Google Maps API Markers
Google Maps API Markers

Adding Markers to Google Maps

Markers are used to identify points on the map. All you need to do to add a basic marker is to add the two lines below to the code above. The previous article shows you how to get latitude and longitude from Google Maps.

javascript
var point = new GLatLng(51.282798,-2.765477);
map.addOverlay(new GMarker(point));

This will show up as a simple red pin on the map. This will mark the start point of the walk (the car park).

Google Maps API Markers
Google Maps API Markers

You can change the icon from the default using some slightly different code. All this does is create an "option" parameter and add it to the addOverlay function.

javascript
var point = new GLatLng(51.282798,-2.765477);
var blueIcon = new GIcon(G_DEFAULT_ICON);
blueIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
markerOptions = { icon:blueIcon };

map.addOverlay(new GMarker(point, markerOptions));

Changing the Google Maps Pointer Icons

Sometimes you may want to add letters to identify specific points of interest on the map rather than the default dot. This can also be done quite easily using the code below.

javascript
var point = new GLatLng(51.282798,-2.765477);
var letteredIcon = new GIcon(G_DEFAULT_ICON);
letteredIcon.image = "http://www.google.com/mapfiles/markerA.png";
markerOptions = { icon:letteredIcon };
var marker = new GMarker(point, markerOptions);

The image URL points to Google markers, simply replace markerA.png with markerB.png, markerC.png and so on. The letter must be in upper case.

You can also host icons on your website and link to them, simply replace the google URL with your own. Here is a great resource for downloading Google Maps icons .

Adding Clickable Captions to Google Maps

The next logical step is to add a caption to the marker so people know what you are marking and why!

Having added the marker to the map, a caption can be added using Google API events as shown below.

javascript
var point = new GLatLng(51.282798,-2.765477);
var letteredIcon = new GIcon(G_DEFAULT_ICON);
letteredIcon.image = "http://www.google.com/mapfiles/markerA.png";
markerOptions = { icon:letteredIcon };
var marker = new GMarker(point, markerOptions);

GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml("This is the carpark at the start of the route.");
  });

map.addOverlay(marker);

This should result in a map marker as shown below. Once clicked it will expand a caption bubble with your text.

Google Maps API Markers with Text
Google Maps API Markers with Text

Adding Images

Why not add an image to the caption and show people what is there? I'm going to start adding these to my maps to show the routes walked and the views you can expect from each vantage point. The parameter to the call of openInfoWindowHtml simply takes in any HTML content, so you can add an image URL to it as well and link it to the full size.

javascript
var point = new GLatLng(51.282798,-2.765477);
var letteredIcon = new GIcon(G_DEFAULT_ICON);
letteredIcon.image = "http://www.google.com/mapfiles/markerA.png";
markerOptions = { icon:letteredIcon };
var marker = new GMarker(point, markerOptions);

GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml("This is the carpark at the start of the route.

<img src='https://lonewolfonline.net/uploads/2010/03/cheddar-gorge-views-3-150x150.jpg'/>");
  });

map.addOverlay(marker);
Adding Pictures to Google Maps
Adding Pictures to Google Maps

Adding Routes to Google Maps

The final thing I want to talk about today is adding routes to the map. Google calls these "polylines". All this is an array of points on the map. So let's create a short "polyline" route on the map. I'm not going to do it all because there are quite a few, hopefully, it will be enough to get you started. The more points you add the more accurate the route will be.

javascript
var polyline = new GPolyline([
new GLatLng(51.282356,-2.767838),
new GLatLng(51.283308,-2.767269),
new GLatLng(51.285858,-2.765284),
new GLatLng(51.286301,-2.764576),
new GLatLng(51.286221,-2.763235),
new GLatLng(51.286556,-2.761851),
new GLatLng(51.288133,-2.75875),
new GLatLng(51.289757,-2.751369),
new GLatLng(51.28969,-2.745962),
new GLatLng(51.288737,-2.745565)
], "#00ff00", 5); 
map.addOverlay(polyline);

In this example, the value "#00ff00" represents a green line. You can change this to be any valid HTML hex colour value. The single digit at the end (5) tells Google how thick to draw the line in pixels. The result should look something like this:

Google Maps Polylines and Routes
Google Maps Polylines and Routes
Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

This post has 4 comment(s). Why not join the discussion!

We respect your privacy, and will not make your email public. Learn how your comment data is processed.

  1. BO

    On Thursday 7th of January 2016, bobby said

    you're a champ! thank you kindly

  2. JT

    On Sunday 18th of November 2012, John Turcott said

    I love your tutorial.

    I'm so reluctant to use Google for programming resources mainly because most examples are nothing more than borrowed information displayed in a non-common sense format.

    Your examples were perfect, right to the point, easy to understand and even the cut and paste worked as shown!

    Thank you, John Turcott

  3. RI

    On Thursday 7th of June 2012, Richard said

    Brilliant tutorial, thanks!!

  4. MA

    On Monday 12th of December 2011, Marvin said

    Thanks for this tutorial, it was a great help in getting me started within minutes!