Google Maps JavaScript API v3

Shapes

  1. Introduction
  2. Polylines
    1. Add a polyline
    2. Remove a polyline
    3. Inspect a polyline
    4. Customize a polyline
  3. Polygons
    1. Add a polygon
    2. Remove a polygon
    3. Inspect a polygon
  4. Rectangles
    1. Add a rectangle
    2. Remove a rectangle
  5. Circles
    1. Add a circle
    2. Remove a circle
  6. User-editable and draggable shapes
    1. Make a shape editable
    2. Make a shape draggable
    3. Listen to editing events
    4. Listen to dragging events

Introduction

You can add various shapes to your map. A shape is an object on the map, tied to a latitude/longitude coordinate. The following shapes are available: lines, polygons, circles and rectangles. You can also configure your shapes so that users can edit or drag them.

Polylines

To draw a line on your map, use a polyline. The Polyline class defines a linear overlay of connected line segments on the map. A Polyline object consists of an array of LatLng locations, and creates a series of line segments that connect those locations in an ordered sequence.

Add a polyline

The Polyline constructor takes a set of PolylineOptions specifying the LatLng coordinates of the line and a set of styles to adjust the polyline's visual behavior.

Polyline objects are drawn as a series of straight segments on the map. You can specify custom colors, weights, and opacities for the stroke of the line within the PolylineOptions when constructing your line, or you can change those properties after construction. A polyline supports the following stroke styles:

  • strokeColor specifies a hexadecimal HTML color of the format "#FFFFFF". The Polyline class does not support named colors.
  • strokeOpacity specifies a numerical value between 0.0 and 1.0 to determine the opacity of the line's color. The default is 1.0.
  • strokeWeight specifies the width of the line in pixels.

The polyline's editable property specifies whether users can edit the shape. See user-editable shapes below. Similarly, you can set the draggable property to allow users to drag the line.

// This example creates a 2-pixel-wide red polyline showing
// the path of William Kingsford Smith's first trans-Pacific flight between
// Oakland, CA, and Brisbane, Australia.

function initialize() {
  var mapOptions = {
    zoom: 3,
    center: new google.maps.LatLng(0, -180),
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  var flightPlanCoordinates = [
    new google.maps.LatLng(37.772323, -122.214897),
    new google.maps.LatLng(21.291982, -157.821856),
    new google.maps.LatLng(-18.142599, 178.431),
    new google.maps.LatLng(-27.46758, 153.027892)
  ];
  var flightPath = new google.maps.Polyline({
    path: flightPlanCoordinates,
    geodesic: true,
    strokeColor: '#FF0000',
    strokeOpacity: 1.0,
    strokeWeight: 2
  });

  flightPath.setMap(map);
}

google.maps.event.addDomListener(window, 'load', initialize);

View example (polyline-simple.html).

Remove a polyline

To remove a polyline from the map, call the setMap() method passing null as the argument. In the following example, flightPath is a polyline object:

flightPath.setMap(null);

Note that the above method does not delete the polyline. It simply removes the polyline from the map. If instead you wish to delete the polyline, you should remove it from the map, and then set the polyline itself to null.

View example (polyline-remove.html).

Inspect a polyline

A polyline specifies a series of coordinates as an array of LatLng objects. These coordinates determine the line's path. To retrieve the coordinates, call getPath(), which will return an array of type MVCArray. You can manipulate and inspect the array using the following operations:

  • getAt() returns the LatLng at a given zero-based index value.
  • insertAt() inserts a passed LatLng at a given zero-based index value. Note that any existing coordinates at that index value are moved forward.
  • removeAt() removes a LatLng at a given zero-based index value.
// This example creates an interactive map which constructs a
// polyline based on user clicks. Note that the polyline only appears
// once its path property contains two LatLng coordinates.

var poly;
var map;

function initialize() {
  var mapOptions = {
    zoom: 7,
    // Center the map on Chicago, USA.
    center: new google.maps.LatLng(41.879535, -87.624333)
  };

  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  var polyOptions = {
    strokeColor: '#000000',
    strokeOpacity: 1.0,
    strokeWeight: 3
  };
  poly = new google.maps.Polyline(polyOptions);
  poly.setMap(map);

  // Add a listener for the click event
  google.maps.event.addListener(map, 'click', addLatLng);
}

/**
 * Handles click events on a map, and adds a new point to the Polyline.
 * @param {google.maps.MouseEvent} event
 */
function addLatLng(event) {

  var path = poly.getPath();

  // Because path is an MVCArray, we can simply append a new coordinate
  // and it will automatically appear.
  path.push(event.latLng);

  // Add a new marker at the new plotted point on the polyline.
  var marker = new google.maps.Marker({
    position: event.latLng,
    title: '#' + path.getLength(),
    map: map
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

View example (polyline-complex.html).

Customize a polyline

You can add vector-based images to a polyline in the form of symbols. With a combination of symbols and the PolylineOptions class, you have a lot of control over the look and feel of polylines on your map. See Symbols for information about arrows, dashed lines, custom symbols and animated symbols.

Polygons

A polygon represents an area enclosed by a closed path (or loop), which is defined by a series of coordinates. Polygon objects are similar to Polyline objects in that they consist of a series of coordinates in an ordered sequence. Polygons are drawn with a stroke and a fill. You can define custom colors, weights, and opacities for the edge of the polygon (the stroke) and custom colors and opacities for the enclosed area (the fill). Colors should be indicated in hexadecimal HTML format. Color names are not supported.

Polygon objects can describe complex shapes, including:

  • Multiple non-contiguous areas defined by a single polygon.
  • Areas with holes in them.
  • Intersections of one or more areas.

To define a complex shape, you will use a polygon with multiple paths.

Add a polygon

Because a polygonal area may include several separate paths, the Polygon object's paths property specifies an array of arrays, each of type MVCArray. Each array defines a separate sequence of ordered LatLng coordinates.

For simple polygons consisting of only one path, you can construct a Polygon using a single array of LatLng coordinates. The Google Maps JavaScript API will convert the simple array into an array of arrays upon construction when storing it within the paths property. The API provides a simple getPath() method for polygons consisting of one path.

The polygon's editable property specifies whether users can edit the shape. See user-editable shapes below. Similarly, you can set the draggable property to allow users to drag the shape.

// This example creates a simple polygon representing the Bermuda Triangle.

function initialize() {
  var mapOptions = {
    zoom: 5,
    center: new google.maps.LatLng(24.886436490787712, -70.2685546875),
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  var bermudaTriangle;

  var map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  // Define the LatLng coordinates for the polygon's path.
  var triangleCoords = [
    new google.maps.LatLng(25.774252, -80.190262),
    new google.maps.LatLng(18.466465, -66.118292),
    new google.maps.LatLng(32.321384, -64.75737),
    new google.maps.LatLng(25.774252, -80.190262)
  ];

  // Construct the polygon.
  bermudaTriangle = new google.maps.Polygon({
    paths: triangleCoords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });

  bermudaTriangle.setMap(map);
}

google.maps.event.addDomListener(window, 'load', initialize);

View example (polygon-simple.html).

Polygon auto-completion

The Polygon in the example above consists of four sets of LatLng coordinates, but notice that the first and last sets define the same location, which completes the loop. In practice, however, since polygons define closed areas, you don't need to specify the last set of coordinates. The Google Maps JavaScript API will automatically complete the polygon by drawing a stroke connecting the last location back to the first location for any given path.

The following example is identical to the previous one, except that the last LatLng is omitted: View example (polygon-autoclose.html).

Remove a polygon

To remove a polygon from the map, call the setMap() method passing null as the argument. In the following example, bermudaTriangle is a polygon object:

bermudaTriangle.setMap(null);

Note that the above method does not delete the polygon. It simply removes the polygon from the map. If instead you wish to delete the polygon, you should remove it from the map, and then set the polygon itself to null.

Inspect a polygon

A polygon specifies its series of coordinates as an array of arrays, where each array is of type MVCArray. Each "leaf" array is an array of LatLng coordinates specifying a single path. To retrieve these coordinates, call the Polygon object's getPaths() method. Since the array is an MVCArray you will need to manipulate and inspect it using the following operations:

  • getAt() returns the LatLng at a given zero-based index value.
  • insertAt() inserts a passed LatLng at a given zero-based index value. Note that any existing coordinates at that index value are moved forward.
  • removeAt() removes a LatLng at a given zero-based index value.
// This example creates a simple polygon representing the Bermuda Triangle.
// When the user clicks on the polygon an info window opens, showing
// information about the polygon's coordinates.

var map;
var infoWindow;

function initialize() {
  var mapOptions = {
    zoom: 5,
    center: new google.maps.LatLng(24.886436490787712, -70.2685546875),
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  var bermudaTriangle;

  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  // Define the LatLng coordinates for the polygon.
  var triangleCoords = [
      new google.maps.LatLng(25.774252, -80.190262),
      new google.maps.LatLng(18.466465, -66.118292),
      new google.maps.LatLng(32.321384, -64.75737)
  ];

  // Construct the polygon.
  bermudaTriangle = new google.maps.Polygon({
    paths: triangleCoords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 3,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });

  bermudaTriangle.setMap(map);

  // Add a listener for the click event.
  google.maps.event.addListener(bermudaTriangle, 'click', showArrays);

  infoWindow = new google.maps.InfoWindow();
}

/** @this {google.maps.Polygon} */
function showArrays(event) {

  // Since this polygon has only one path, we can call getPath()
  // to return the MVCArray of LatLngs.
  var vertices = this.getPath();

  var contentString = '<b>Bermuda Triangle polygon</b><br>' +
      'Clicked location: <br>' + event.latLng.lat() + ',' + event.latLng.lng() +
      '<br>';

  // Iterate over the vertices.
  for (var i =0; i < vertices.getLength(); i++) {
    var xy = vertices.getAt(i);
    contentString += '<br>' + 'Coordinate ' + i + ':<br>' + xy.lat() + ',' +
        xy.lng();
  }

  // Replace the info window's content and position.
  infoWindow.setContent(contentString);
  infoWindow.setPosition(event.latLng);

  infoWindow.open(map);
}

google.maps.event.addDomListener(window, 'load', initialize);

View example (polygon-arrays.html).

Rectangles

In addition to a generic Polygon class, the Google Maps JavaScript API includes a specific class for Rectangle objects, to simplify their construction.

Add a rectangle

A Rectangle is similar to a Polygon in that you can define custom colors, weights, and opacities for the edge of the rectangle (the stroke) and custom colors and opacities for the area within the rectangle (the fill). Colors should be indicated in hexadecimal numeric HTML style.

Unlike a Polygon, you do not define paths for a Rectangle. Instead, a rectangle has a bounds property which defines its shape by specifying a google.maps.LatLngBounds for the rectangle.

The rectangle's editable property specifies whether users can edit the shape. See user-editable shapes below. Similarly, you can set the draggable property to allow users to drag the rectangle.

// This example adds a red rectangle to a map.

function initialize() {
  var map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 11,
    center: new google.maps.LatLng(33.678176, -116.242568),
    mapTypeId: google.maps.MapTypeId.TERRAIN
  });

  var rectangle = new google.maps.Rectangle({
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35,
    map: map,
    bounds: new google.maps.LatLngBounds(
      new google.maps.LatLng(33.671068, -116.25128),
      new google.maps.LatLng(33.685282, -116.233942))
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

View example (rectangle-simple.html).

The following code creates a rectangle each time the user changes the zoom on the map. The size of the rectangle is determined by the viewport.

// This example creates a rectangle based on the viewport
// on any 'zoom-changed' event.

function initialize() {

  var coachella = new google.maps.LatLng(33.6803003, -116.173894);
  var rectangle;

  var mapOptions = {
    zoom: 11,
    center: coachella,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  rectangle = new google.maps.Rectangle();

  google.maps.event.addListener(map, 'zoom_changed', function() {

    // Get the current bounds, which reflect the bounds before the zoom.
    var rectOptions = {
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.35,
      map: map,
      bounds: map.getBounds()
    };
    rectangle.setOptions(rectOptions);
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

View example (rectangle-zoom.html).

Remove a rectangle

To remove a rectangle from the map, call the setMap() method passing null as the argument.

rectangle.setMap(null);

Note that the above method does not delete the rectangle. It simply removes the rectangle from the map. If instead you wish to delete the rectangle, you should remove it from the map, and then set the rectangle itself to null.

Circles

In addition to the generic Polygon class, the Google Maps JavaScript API includes a specific class for Circle objects, to simplify their construction.

Add a circle

A Circle is similar to a Polygon in that you can define custom colors, weights, and opacities for the edge of the circle (the stroke) and custom colors and opacities for the area within the circle (the fill). Colors should be indicated in hexadecimal numeric HTML style.

Unlike a Polygon, you do not define paths for a Circle. Instead, a circle has two additional properties which define its shape:

  • center specifies the google.maps.LatLng of the center of the circle.
  • radius specifies the radius of the circle, in meters.

The circle's editable property specifies whether users can edit the shape. See user-editable shapes below. Similarly, you can set the draggable property to allow users to drag the circle.

// This example creates circles on the map, representing
// populations in the United States.

// First, create an object containing LatLng and population for each city.
var citymap = {};
citymap['chicago'] = {
  center: new google.maps.LatLng(41.878113, -87.629798),
  population: 2842518
};
citymap['newyork'] = {
  center: new google.maps.LatLng(40.714352, -74.005973),
  population: 8143197
};
citymap['losangeles'] = {
  center: new google.maps.LatLng(34.052234, -118.243684),
  population: 3844829
};
var cityCircle;

function initialize() {
  // Create the map.
  var mapOptions = {
    zoom: 4,
    center: new google.maps.LatLng(37.09024, -95.712891),
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  // Construct the circle for each value in citymap.
  // Note: We scale the population by a factor of 20.
  for (var city in citymap) {
    var populationOptions = {
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.35,
      map: map,
      center: citymap[city].center,
      radius: citymap[city].population / 20
    };
    // Add the circle for this city to the map.
    cityCircle = new google.maps.Circle(populationOptions);
  }
}

google.maps.event.addDomListener(window, 'load', initialize);

View example (circle-simple.html).

Remove a circle

To remove a circle from the map, call the setMap() method passing null as the argument.

circle.setMap(null);

Note that the above method does not delete the circle. It simply removes the circle from the map. If instead you wish to delete the circle, you should remove it from the map, and then set the circle itself to null.

User-editable and draggable shapes

Making a shape editable adds handles to the shape, which people can use to reposition, reshape, and resize the shape directly on the map. You can also make a shape draggable, so people can move it to a different place on the map.

User-made changes to the object do not persist between sessions. If you want to save the user's edits, you must capture and store the information yourself.

Make a shape editable

Any shape (polylines, polygons, circles, and rectangles) can be set as user-editable, by setting editable to true in the shape's options.

  var bounds = new google.maps.LatLngBounds(
      new google.maps.LatLng(44.490, -78.649),
      new google.maps.LatLng(44.599, -78.443)
  );

  // Define a rectangle and set its editable property to true.
  var rectangle = new google.maps.Rectangle({
    bounds: bounds,
    editable: true
  });

  rectangle.setMap(map);

View example (user-editable-shapes.html).

Make a shape draggable

By default, a shape drawn on the map will be fixed in position. To allow users to drag a shape to a different location on the map, set draggable to true in the shape options.

  var redCoords = [
    new google.maps.LatLng(25.774, -80.190),
    new google.maps.LatLng(18.466, -66.118),
    new google.maps.LatLng(32.321, -64.757)
  ];

  // Construct a draggable red triangle with geodesic set to true.
  new google.maps.Polygon({
    map: map,
    paths: redCoords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35,
    draggable: true,
    geodesic: true
  });

When enabling dragging on a polygon or polyline, you should also consider making the polygon or polyline geodesic, by setting its geodesic property to true.

A geodesic polygon will retain its true geographic shape when it is moved, causing the polygon to appear distorted as it is moved north or south in the Mercator projection. Non-geodesic polygons will always retain their initial appearance on the screen.

In a geodesic polyline, the segments of the polyline are drawn as the shortest path between two points on the Earth's surface, assuming the Earth is a sphere, as opposed to straight lines on the Mercator projection.

For more information on coordinate systems, consult the MapTypes documentation.

The following map shows two triangles of roughly the same size and dimensions. The red triangle has its geodesic property set to true. Notice how its shape changes as it moves north.

View example (polygon-draggable.html).

Listen to editing events

When a shape is edited, an event is fired upon completion of the edit. These events are listed below.

Shape Events
Circle radius_changed
center_changed
Polygon insert_at
remove_at
set_at

The listener must be set on the polygon's path. If the polygon has multiple paths, a listener must be set on each path.

Polyline insert_at
remove_at
set_at

The listener must be set on the polyline's path.

Rectangle bounds_changed

Some useful code snippets:

google.maps.event.addListener(circle, 'radius_changed', function() {
  console.log(circle.getRadius());
});

google.maps.event.addListener(outerPath, 'set_at', function() {
  console.log('Vertex moved on outer path.');
});

google.maps.event.addListener(innerPath, 'insert_at', function() {
  console.log('Vertex removed from inner path.');
});

google.maps.event.addListener(rectangle, 'bounds_changed', function() {
  console.log('Bounds changed.');
});

See an example of handling an editing event on a rectangle: View example (rectangle-event.html).

Listen to dragging events

When a shape is dragged, events are fired upon start and end of the dragging action as well as during the dragging. The following events are fired for polylines, polygons, circles and rectangles.

Event Description
dragstart Fired when the user starts dragging the shape.
drag Fired repeatedly while the user is dragging the shape.
dragend Fired when the user stops dragging the shape.

For more about handling events, see the documentation on events.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.