Google Map
Google Maps with markers, a road route from A to B, and Street View, loaded once per page from a browser key.
c2-google-map shows an interactive Google map. Declare what goes on it as children: c2-google-map-marker for a
pin, c2-google-map-route for the road route between an origin and a destination (with its distance and travel
time in route-change). c2-google-street-view is a Street View panorama of its own, or the one the map’s pegman
opens when it is linked with for. Everything else the Maps JavaScript API offers stays reachable through the
element’s map property, the underlying google.maps.Map.
Import
import '@c2n/components/google-map'API key
The Maps JavaScript API runs in the browser, so its key is always visible to the page, and no server can hide it.
Protect it in the Google Cloud console instead: restrict it to your sites’ HTTP referrers, allow only the APIs the
page uses (Maps JavaScript API, plus Routes API for c2-google-map-route), and set a quota. Configure it once for
the whole page, before or after the maps render:
import { configureGoogleMaps } from '@c2n/components/google-map'
configureGoogleMaps({ apiKey: import.meta.env.VITE_GOOGLE_MAPS_API_KEY, language: 'en', region: 'VN' })An api-key attribute on the element works too, when there is only one map. Markers and route markers need a map
ID: without map-id the map uses Google’s DEMO_MAP_ID, which is for development only.
Usage
Distance and travel time
c2-google-map-route computes the route again whenever origin, destination, waypoints or travel-mode
changes, and reports it:
const route = document.querySelector('c2-google-map-route')!
route.addEventListener('route-change', (event) => {
const { distanceMeters, durationMillis, distanceText, durationText } = event.detail
console.log(`${distanceText} · ${durationText}`) // "8.1 km · 21 mins"
})