Skip to content

Google Maps - Quick Guide

This guide provides a concise summary of the key concepts covered in the introductory chapters for the Maps JavaScript API.

Core Idea: Display a basic map on a web page.

  • Get API Key: Obtain from Google Cloud Console, enable Maps JavaScript API, and secure the key.
  • HTML Structure: Create an HTML file with a <div> element having a specific id (e.g., id="map") and set its height via CSS.
  • Load API: Include the API script using https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&v=weekly (use async defer).
  • Callback Function: Define an async function initMap() which will be executed when the API loads.
  • Import Library: Inside initMap, use await google.maps.importLibrary("maps") to load the Map class.
  • Instantiate Map: Create the map object: new google.maps.Map(document.getElementById('map'), { center: {lat: ..., lng: ...}, zoom: ..., mapId: 'YOUR_MAP_ID' });.

Basic Example Code Snippet (initMap function):

Section titled “Basic Example Code Snippet (initMap function):”
async function initMap() {
const position = { lat: -34.397, lng: 150.644 }; // Sydney
const { Map } = await google.maps.importLibrary("maps");
const map = new Map(document.getElementById("map"), {
zoom: 8,
center: position,
mapId: "DEMO_MAP_ID" // Use your Map ID for styling
});
}

Core Idea: Choose the visual style of the base map.

Available Types (set via mapTypeId in MapOptions or map.setMapTypeId()):

Section titled “Available Types (set via mapTypeId in MapOptions or map.setMapTypeId()):”
  • 'roadmap' (Default): Standard street map.
  • 'satellite': Aerial/satellite photos.
  • 'hybrid': Satellite photos with road/label overlays.
  • 'terrain': Physical relief map showing elevation, rivers etc.

Modern Approach: Use mapId linked to Cloud-based Map Styles for extensive visual customization beyond these basic types.

const mapOptions = {
zoom: 11,
center: { lat: 48.8566, lng: 2.3522 }, // Paris
mapId: "DEMO_MAP_ID",
mapTypeId: 'terrain' // Show terrain view initially
};

Core Idea: Control the magnification of the map.

  • Initial: Set the zoom property (number) in MapOptions.
  • Programmatic: Use map.setZoom(newZoomLevel);.
  • Get Current: Use map.getZoom();.
  • 1: World
  • 5: Continent / Large Country
  • 10: City
  • 15: Streets
  • 20: Individual Buildings
const mapOptions = {
zoom: 15, // Street level detail
center: { lat: 51.5074, lng: -0.1278 }, // London
mapId: "DEMO_MAP_ID"
};

Core Idea: Display map labels and controls in a specific language and format.

Add language and optionally region parameters to the API script URL.

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&v=weekly&language=ja&region=JP" async defer></script>
<!-- language=ja (Japanese), region=JP (Japan) -->

Supported Languages: See official list.

Core Idea: Manage the interactive elements on the map.

  • disableDefaultUI: true : Hides all default controls.
  • Individual controls (booleans, default true unless noted): zoomControl, mapTypeControl, streetViewControl, fullscreenControl, rotateControl.
  • scaleControl: Default is false, set to true to show map scale.
  • Positioning: Use controlOptions (e.g., zoomControlOptions: { position: google.maps.ControlPosition.LEFT_BOTTOM }). Requires importing ControlPosition.
const { Map, ControlPosition } = await google.maps.importLibrary("maps");
// ... in initMap ...
const mapOptions = {
zoom: 12,
center: { lat: 37.7749, lng: -122.4194 }, // San Francisco
mapId: "DEMO_MAP_ID",
streetViewControl: false, // Hide Pegman
fullscreenControl: false, // Hide fullscreen button
scaleControl: true, // Show scale
mapTypeControlOptions: {
position: ControlPosition.TOP_RIGHT // Move map type selector
}
};

Core Idea: Indicate specific points on the map.

  • Import Library: const { Marker } = await google.maps.importLibrary("marker"); (and add &libraries=marker to script URL).
  • Instantiate: new google.maps.Marker({ position: {lat:..., lng:...}, map: map, title: 'Optional Tooltip' });.
  • Modern Alternative: AdvancedMarkerView offers more customization and performance benefits.
  • Animation: Set animation: google.maps.Animation.DROP or BOUNCE.
  • Custom Icon: Set icon: 'URL_to_image' or use a Symbol object.
  • Draggable: Set draggable: true.
  • Label: Set label: 'A' or a MarkerLabel object.
  • Remove: Call marker.setMap(null);.
const { Marker } = await google.maps.importLibrary("marker");
const { Animation } = await google.maps.importLibrary("maps"); // If using animation
const marker = new Marker({
position: { lat: -33.8688, lng: 151.2093 }, // Sydney
map: map,
title: 'Sydney Opera House vicinity',
icon: 'https://maps.google.com/mapfiles/ms/icons/blue-dot.png',
animation: Animation.DROP
});

7. Shapes (Polylines, Polygons, Circles, Rectangles)

Section titled “7. Shapes (Polylines, Polygons, Circles, Rectangles)”

Core Idea: Draw lines and areas on the map.

  • Import Library: Often part of the base maps library, but check specific class docs if needed.
  • Instantiate: Use new google.maps.Polyline({...}), Polygon({...}), Rectangle({...}), Circle({...}).
  • Key Properties:
  • - `path` (Polyline/Polygon): Array of `{lat: ..., lng: ...}` coordinates.
  • - `bounds` (Rectangle): A `google.maps.LatLngBounds` object.
  • - `center` & `radius` (Circle): Center coordinates and radius in meters.
  • - `map: map`: Associate with the map.
  • - Style Options: `strokeColor`, `strokeOpacity`, `strokeWeight`, `fillColor`, `fillOpacity`.
  • - Interactivity: `editable: true`, `draggable: true`.
  • Remove: Call shape.setMap(null);.
const flightPlanCoordinates = [
{ lat: 37.772, lng: -122.214 },
{ lat: 21.291, lng: -157.821 },
{ lat: -18.142, lng: 178.431 },
{ lat: -33.951, lng: 151.177 }
];
const flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true, // Makes the line follow Earth's curvature
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});

Core Idea: Display information in a pop-up window, often attached to a marker.

  • Import Library: Usually part of the base maps library.
  • Instantiate: new google.maps.InfoWindow({ content: 'HTML content string or DOM Node', maxWidth: 200, ariaLabel: 'Accessibility label' });.
  • Open: Call infowindow.open({ map: map, anchor: marker }); (modern way) or infowindow.open(map, marker); (older way).
  • Close: Call infowindow.close();.
  • Common Use: Open an InfoWindow when a marker is clicked (see Events).
const infowindow = new google.maps.InfoWindow({
content: '<h3>Marker Title</h3><p>Some details about this place.</p>',
ariaLabel: 'Marker Details'
});
marker.addListener('click', () => {
infowindow.open({ anchor: marker, map });
});

Core Idea: Use predefined vector icons (circles, arrows) as markers or on polylines.

  • Import Library: Part of the base maps library (google.maps.SymbolPath).
  • As Marker Icon: Set the marker’s icon property to a google.maps.Symbol object: { path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW, scale: 5, fillColor: 'red', ... }.
  • On Polylines: Use the icons property of PolylineOptions, providing an array of IconSequence objects: [{ icon: symbolObject, offset: '100%', repeat: '50px' }].
const { Marker } = await google.maps.importLibrary("marker");
const { SymbolPath } = await google.maps.importLibrary("core"); // SymbolPath is in core
const symbolMarker = new Marker({
position: { lat: 45.5231, lng: -122.6765 }, // Portland
map: map,
icon: {
path: SymbolPath.CIRCLE,
scale: 8,
fillColor: '#00F',
fillOpacity: 0.8,
strokeWeight: 1
},
title: 'Circle Symbol'
});

Core Idea: Respond to user interactions (clicks, drags) or map state changes (zoom, center).

  • Add Listener: Use the addListener method on the object (map, marker, etc.): map.addListener('click', (event) => { ... }); or marker.addListener('dragend', (event) => { ... });.
  • Event Object: The handler function usually receives an event object containing relevant data (e.g., event.latLng for click events).
  • Common Events:
  • - `Map`: `click`, `dblclick`, `zoom_changed`, `center_changed`, `bounds_changed`, `idle`.
  • - `Marker`: `click`, `dblclick`, `dragstart`, `drag`, `dragend`.
  • - `InfoWindow`: `closeclick`.
  • Remove Listener: Store the listener object returned by addListener and call its remove() method: const listener = map.addListener(...); listener.remove();.
map.addListener('click', (mapsMouseEvent) => {
console.log('Map clicked at:', mapsMouseEvent.latLng.toString());
// Example: Place a marker where the user clicked
// new google.maps.Marker({ position: mapsMouseEvent.latLng, map: map });
});