Google Maps - Quick Guide
Google Maps Platform - Quick Guide
Section titled “Google Maps Platform - Quick Guide”This guide provides a concise summary of the key concepts covered in the introductory chapters for the Maps JavaScript API.
1. Getting Started
Section titled “1. Getting Started”Core Idea: Display a basic map on a web page.
Key Steps:
Section titled “Key Steps:”- 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 specificid(e.g.,id="map") and set itsheightvia CSS. - Load API: Include the API script using
https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&v=weekly(useasync defer). - Callback Function: Define an
async function initMap()which will be executed when the API loads. - Import Library: Inside
initMap, useawait google.maps.importLibrary("maps")to load theMapclass. - 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 });}2. Map Types
Section titled “2. Map Types”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.
Example (MapOptions):
Section titled “Example (MapOptions):”const mapOptions = { zoom: 11, center: { lat: 48.8566, lng: 2.3522 }, // Paris mapId: "DEMO_MAP_ID", mapTypeId: 'terrain' // Show terrain view initially};3. Zoom Levels
Section titled “3. Zoom Levels”Core Idea: Control the magnification of the map.
Setting Zoom:
Section titled “Setting Zoom:”- Initial: Set the
zoomproperty (number) inMapOptions. - Programmatic: Use
map.setZoom(newZoomLevel);. - Get Current: Use
map.getZoom();.
Typical Zoom Levels:
Section titled “Typical Zoom Levels:”- 1: World
- 5: Continent / Large Country
- 10: City
- 15: Streets
- 20: Individual Buildings
Example (MapOptions):
Section titled “Example (MapOptions):”const mapOptions = { zoom: 15, // Street level detail center: { lat: 51.5074, lng: -0.1278 }, // London mapId: "DEMO_MAP_ID"};4. Localization
Section titled “4. Localization”Core Idea: Display map labels and controls in a specific language and format.
How To:
Section titled “How To:”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®ion=JP" async defer></script><!-- language=ja (Japanese), region=JP (Japan) -->Supported Languages: See official list.
5. UI Controls
Section titled “5. UI Controls”Core Idea: Manage the interactive elements on the map.
Controlling Controls (in MapOptions):
Section titled “Controlling Controls (in MapOptions):”disableDefaultUI: true: Hides all default controls.- Individual controls (booleans, default
trueunless noted):zoomControl,mapTypeControl,streetViewControl,fullscreenControl,rotateControl. scaleControl: Default isfalse, set totrueto show map scale.- Positioning: Use
controlOptions(e.g.,zoomControlOptions: { position: google.maps.ControlPosition.LEFT_BOTTOM }). Requires importingControlPosition.
Example (MapOptions):
Section titled “Example (MapOptions):”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 }};6. Markers
Section titled “6. Markers”Core Idea: Indicate specific points on the map.
Adding Markers:
Section titled “Adding Markers:”- Import Library:
const { Marker } = await google.maps.importLibrary("marker");(and add&libraries=markerto script URL). - Instantiate:
new google.maps.Marker({ position: {lat:..., lng:...}, map: map, title: 'Optional Tooltip' });. - Modern Alternative:
AdvancedMarkerViewoffers more customization and performance benefits. - Animation: Set
animation: google.maps.Animation.DROPorBOUNCE. - Custom Icon: Set
icon: 'URL_to_image'or use aSymbolobject. - Draggable: Set
draggable: true. - Label: Set
label: 'A'or aMarkerLabelobject. - Remove: Call
marker.setMap(null);.
Example (Inside initMap):
Section titled “Example (Inside initMap):”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.
Adding Shapes:
Section titled “Adding Shapes:”- Import Library: Often part of the base
mapslibrary, 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);.
Example (Polyline):
Section titled “Example (Polyline):”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});8. Info Windows
Section titled “8. Info Windows”Core Idea: Display information in a pop-up window, often attached to a marker.
Adding Info Windows:
Section titled “Adding Info Windows:”- Import Library: Usually part of the base
mapslibrary. - 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) orinfowindow.open(map, marker);(older way). - Close: Call
infowindow.close();. - Common Use: Open an InfoWindow when a marker is clicked (see Events).
Example (Open on Marker Click):
Section titled “Example (Open on Marker Click):”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 });});9. Symbols
Section titled “9. Symbols”Core Idea: Use predefined vector icons (circles, arrows) as markers or on polylines.
Using Symbols:
Section titled “Using Symbols:”- Import Library: Part of the base
mapslibrary (google.maps.SymbolPath). - As Marker Icon: Set the marker’s
iconproperty to agoogle.maps.Symbolobject:{ path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW, scale: 5, fillColor: 'red', ... }. - On Polylines: Use the
iconsproperty ofPolylineOptions, providing an array ofIconSequenceobjects:[{ icon: symbolObject, offset: '100%', repeat: '50px' }].
Example (Symbol as Marker):
Section titled “Example (Symbol as Marker):”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'});10. Events
Section titled “10. Events”Core Idea: Respond to user interactions (clicks, drags) or map state changes (zoom, center).
Handling Events:
Section titled “Handling Events:”- Add Listener: Use the
addListenermethod on the object (map, marker, etc.):map.addListener('click', (event) => { ... });ormarker.addListener('dragend', (event) => { ... });. - Event Object: The handler function usually receives an event object containing relevant data (e.g.,
event.latLngfor 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
addListenerand call itsremove()method:const listener = map.addListener(...); listener.remove();.
Example (Log Map Clicks):
Section titled “Example (Log Map Clicks):”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 });});