Google Maps - Shapes
Google Maps - Drawing Shapes
Section titled “Google Maps - Drawing Shapes”Beyond simple markers, the Maps JavaScript API allows you to draw vector shapes like lines, polygons, circles, and rectangles directly onto the map. These are useful for highlighting routes, defining areas, or visualizing regions.
These shapes are overlays, similar to markers, and can be customized in appearance and behavior.
Polylines
Section titled “Polylines”A Polyline is a series of connected line segments defined by an ordered sequence of coordinates (LatLng). They are ideal for representing paths, routes, or boundaries.
- Define an array of coordinate objects
{lat: ..., lng: ...}representing the vertices of the line. - Instantiate
google.maps.Polyline, passing thepatharray and style options. - Set the
mapproperty to your map instance.
Key Polyline Options:
Section titled “Key Polyline Options:”path: Array of coordinates.strokeColor: Color of the line (e.g.,'#FF0000','blue').strokeOpacity: Opacity from 0.0 (transparent) to 1.0 (opaque).strokeWeight: Line thickness in pixels.geodesic:trueto draw the line following the curvature of the Earth (recommended for long lines),falsefor straight lines on the projected map.editable:trueto allow users to modify the line’s vertices.draggable:trueto allow users to drag the entire line.
Example: Drawing a Route
Section titled “Example: Drawing a Route”<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Polyline Example</title> <style>#map { height: 400px; width: 100%; } html, body { height: 100%; margin: 0; padding: 0; }</style></head><body> <div id="map"></div> <script> async function initMap() { const mapCenter = { lat: 40.7128, lng: -74.0060 }; // NYC const { Map } = await google.maps.importLibrary("maps");
const map = new Map(document.getElementById("map"), { zoom: 12, center: mapCenter, mapId: "DEMO_MAP_ID" });
const routeCoordinates = [ { lat: 40.7580, lng: -73.9855 }, // Times Square { lat: 40.7614, lng: -73.9776 }, // MoMA area { lat: 40.7679, lng: -73.9822 }, // Near Central Park South { lat: 40.7790, lng: -73.9635 } // Near Met Museum ];
const routePath = new google.maps.Polyline({ path: routeCoordinates, geodesic: true, strokeColor: '#0000FF', // Blue line strokeOpacity: 0.8, strokeWeight: 3, map: map }); } </script> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&v=weekly" async defer></script></body></html>Expected Output: A map of NYC with a blue line connecting several points, representing a path or route.
Polygons
Section titled “Polygons”A Polygon defines a closed area on the map, formed by connecting a series of coordinates where the last point implicitly connects back to the first. They are used to highlight regions, zones, or territories.
Creating a polygon is similar to a polyline, but it includes fill properties.
Key Polygon Options:
Section titled “Key Polygon Options:”path: Array of coordinates defining the boundary (implicitly closed).strokeColor,strokeOpacity,strokeWeight: Style for the border.fillColor: Color for the interior area.fillOpacity: Opacity of the fill.editable,draggable.
Example: Highlighting a Neighborhood
Section titled “Example: Highlighting a Neighborhood”<!DOCTYPE html><!-- ... head ... --><body> <div id="map"></div> <script> async function initMap() { const mapCenter = { lat: 34.0522, lng: -118.2437 }; // Los Angeles const { Map } = await google.maps.importLibrary("maps");
const map = new Map(document.getElementById("map"), { zoom: 13, center: mapCenter, mapId: "DEMO_MAP_ID" });
// Define the approximate coordinates for a neighborhood const neighborhoodCoords = [ { lat: 34.060, lng: -118.290 }, { lat: 34.075, lng: -118.280 }, { lat: 34.070, lng: -118.265 }, { lat: 34.055, lng: -118.275 }, // No need to repeat the first point ];
const neighborhoodPolygon = new google.maps.Polygon({ paths: neighborhoodCoords, // Note: 'paths' is also valid (for complex polygons with holes) strokeColor: '#FF8800', // Orange border strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#FF8800', // Orange fill fillOpacity: 0.35, map: map }); } </script> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&v=weekly" async defer></script></body></html>Expected Output: A map of LA with a semi-transparent orange polygon covering a defined area.
Rectangles
Section titled “Rectangles”A Rectangle is a specific type of polygon defined by its North-East and South-West corners (a LatLngBounds object).
Key Rectangle Options:
Section titled “Key Rectangle Options:”bounds: Agoogle.maps.LatLngBoundsobject or aLatLngBoundsLiteral({north: ..., south: ..., east: ..., west: ...}).- Stroke and Fill options (same as Polygon).
editable,draggable.
Example: Defining a Rectangular Area
Section titled “Example: Defining a Rectangular Area”<!DOCTYPE html><!-- ... head ... --><body> <div id="map"></div> <script> async function initMap() { const mapCenter = { lat: 41.8781, lng: -87.6298 }; // Chicago // Import LatLngBounds along with Map const { Map, LatLngBounds } = await google.maps.importLibrary("maps");
const map = new Map(document.getElementById("map"), { zoom: 11, center: mapCenter, mapId: "DEMO_MAP_ID" });
// Define the bounds for the rectangle const areaBounds = new LatLngBounds( { lat: 41.85, lng: -87.70 }, // Southwest corner { lat: 41.90, lng: -87.60 } // Northeast corner ); /* Alternatively using a literal: const areaBoundsLiteral = { north: 41.90, south: 41.85, east: -87.60, west: -87.70 }; */
const areaRectangle = new google.maps.Rectangle({ strokeColor: '#800080', // Purple border strokeOpacity: 0.7, strokeWeight: 2, fillColor: '#800080', // Purple fill fillOpacity: 0.3, map: map, bounds: areaBounds // Use the LatLngBounds object or literal }); } </script> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&v=weekly&libraries=maps" async defer></script> <!-- Note: Explicitly include 'maps' library for LatLngBounds --></body></html>Expected Output: A map of Chicago with a semi-transparent purple rectangle highlighting a specific area.
Circles
Section titled “Circles”A Circle defines a circular area based on a center point (LatLng) and a radius (in meters).
Key Circle Options:
Section titled “Key Circle Options:”center: A{lat: ..., lng: ...}object for the circle’s center.radius: The radius of the circle in meters.- Stroke and Fill options (same as Polygon).
editable,draggable.
Example: Highlighting an Area Around a Point
Section titled “Example: Highlighting an Area Around a Point”<!DOCTYPE html><!-- ... head ... --><body> <div id="map"></div> <script> async function initMap() { const mapCenter = { lat: 39.9526, lng: -75.1652 }; // Philadelphia const { Map } = await google.maps.importLibrary("maps");
const map = new Map(document.getElementById("map"), { zoom: 13, center: mapCenter, mapId: "DEMO_MAP_ID" });
const cityCircle = new google.maps.Circle({ strokeColor: '#008000', // Green border strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#008000', // Green fill fillOpacity: 0.35, map: map, center: mapCenter, // Center the circle on the map center radius: 1500 // Radius in meters (1.5 km) }); } </script> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&v=weekly" async defer></script></body></html>Expected Output: A map of Philadelphia with a semi-transparent green circle with a 1.5km radius centered on the initial map view.
Removing Shapes
Section titled “Removing Shapes”Just like markers, you remove any shape overlay from the map by calling its setMap() method with null.
// Assuming 'routePath' is your Polyline objectroutePath.setMap(null);
// Assuming 'cityCircle' is your Circle objectcityCircle.setMap(null);