-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathScriptGoogleMaps.vue
More file actions
461 lines (424 loc) · 15.4 KB
/
ScriptGoogleMaps.vue
File metadata and controls
461 lines (424 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
<script lang="ts">
/// <reference types="google.maps" />
import type { ElementScriptTrigger } from '#nuxt-scripts/types'
import type { HTMLAttributes, ReservedProps, ShallowRef } from 'vue'
export { MAP_INJECTION_KEY } from './useGoogleMapsResource'
export interface ScriptGoogleMapsProps {
/**
* Defines the trigger event to load the script.
* @default ['mouseenter', 'mouseover', 'mousedown']
*/
trigger?: ElementScriptTrigger
/**
* Defines the Google Maps API key. Must have access to the Static Maps API as well.
*/
apiKey?: string
/**
* A latitude / longitude of where to focus the map.
*/
center?: google.maps.LatLng | google.maps.LatLngLiteral | `${string},${string}`
/**
* Zoom level for the map (0-21). Reactive: changing this will update the map.
* Takes precedence over mapOptions.zoom when provided.
*/
zoom?: number
/**
* Options for the map.
*/
mapOptions?: google.maps.MapOptions
/**
* Defines the region of the map.
*/
region?: string
/**
* Defines the language of the map.
*/
language?: string
/**
* Defines the version of google maps js API.
*/
version?: string
/**
* Defines the width of the map.
* @default 640
*/
width?: number | string
/**
* Defines the height of the map.
* @default 400
*/
height?: number | string
/**
* Customize the root element attributes.
*/
rootAttrs?: HTMLAttributes & ReservedProps & Record<string, unknown>
/**
* Map IDs for light and dark color modes.
* When provided, the map will automatically switch styles based on color mode.
* Requires @nuxtjs/color-mode or manual colorMode prop.
*/
mapIds?: { light?: string, dark?: string }
/**
* Manual color mode control. When provided, overrides auto-detection from @nuxtjs/color-mode.
* Accepts 'light' or 'dark'.
*/
colorMode?: 'light' | 'dark'
}
export interface ScriptGoogleMapsExpose {
/**
* A reference to the loaded Google Maps API, or `undefined` if not yet loaded.
*/
googleMaps: ShallowRef<typeof google.maps | undefined>
/**
* A reference to the Google Map instance, or `undefined` if not yet initialized.
*/
map: ShallowRef<google.maps.Map | undefined>
/**
* Utility function to resolve a location query (e.g. "New York, NY") to latitude/longitude coordinates.
* Uses a caching mechanism and a server-side proxy to avoid unnecessary client-side API calls.
*/
resolveQueryToLatLng: (query: string) => Promise<google.maps.LatLng | google.maps.LatLngLiteral | undefined>
/**
* Utility function to dynamically import additional Google Maps libraries (e.g. "marker", "places").
* Caches imported libraries for efficient reuse.
*/
importLibrary: {
(key: 'marker'): Promise<google.maps.MarkerLibrary>
(key: 'places'): Promise<google.maps.PlacesLibrary>
(key: 'geometry'): Promise<google.maps.GeometryLibrary>
(key: 'drawing'): Promise<google.maps.DrawingLibrary>
(key: 'visualization'): Promise<google.maps.VisualizationLibrary>
(key: string): Promise<any>
}
}
export interface ScriptGoogleMapsEmits {
/**
* Fired when the Google Maps instance is fully loaded and ready to use. Provides access to the maps API.
*/
ready: [payload: ScriptGoogleMapsExpose]
/**
* Fired when the Google Maps script fails to load.
*/
error: []
}
export interface ScriptGoogleMapsSlots {
/**
* Default slot for rendering child components (e.g. markers, info windows) that depend on the map being ready.
*/
default?: () => any
/**
* Slot displayed while the map is loading. Can be used to show a custom loading indicator.
*/
loading?: () => any
/**
* Slot displayed when the script is awaiting user interaction to load (based on the `trigger` prop).
*/
awaitingLoad?: () => any
/**
* Slot displayed if the script fails to load.
*/
error?: () => any
/**
* Slot displayed as a placeholder before the map is ready. Useful for showing a static map or skeleton.
*/
placeholder?: () => any
}
</script>
<script lang="ts" setup>
import { useScriptTriggerElement } from '#nuxt-scripts/composables/useScriptTriggerElement'
import { useScriptGoogleMaps } from '#nuxt-scripts/registry/google-maps'
import { scriptRuntimeConfig, scriptsPrefix } from '#nuxt-scripts/utils'
import { defu } from 'defu'
import { tryUseNuxtApp, useHead, useRuntimeConfig } from 'nuxt/app'
import { computed, onBeforeUnmount, onMounted, provide, ref, shallowRef, toRaw, useAttrs, useTemplateRef, watch } from 'vue'
import ScriptAriaLoadingIndicator from '../ScriptAriaLoadingIndicator.vue'
import { MAP_INJECTION_KEY, waitForMapsReady } from './useGoogleMapsResource'
const props = withDefaults(defineProps<ScriptGoogleMapsProps>(), {
// @ts-expect-error untyped
trigger: ['mouseenter', 'mouseover', 'mousedown'],
width: 640,
height: 400,
})
const emits = defineEmits<ScriptGoogleMapsEmits>()
defineSlots<ScriptGoogleMapsSlots>()
const DIGITS_ONLY_RE = /^\d+$/
const DIGITS_PX_RE = /^\d+px$/i
const apiKey = props.apiKey || scriptRuntimeConfig('googleMaps')?.apiKey
const runtimeConfig = useRuntimeConfig()
const nuxtColorMode = computed(() => {
const value = (tryUseNuxtApp()?.$colorMode as { value: string } | undefined)?.value
return value === 'dark' || value === 'light' ? value : undefined
})
const currentColorMode = computed(() => props.colorMode || nuxtColorMode.value || 'light')
const currentMapId = computed(() => {
if (!props.mapIds)
return props.mapOptions?.mapId
return props.mapIds[currentColorMode.value] || props.mapIds.light || props.mapOptions?.mapId
})
const mapsApi = shallowRef<typeof google.maps | undefined>()
if (import.meta.dev) {
if (!apiKey)
throw new Error('GoogleMaps requires an API key. Enable it in your nuxt.config:\n\n scripts: {\n registry: {\n googleMaps: true\n }\n }\n\nThen set NUXT_PUBLIC_SCRIPTS_GOOGLE_MAPS_API_KEY in your .env file.\n\nAlternatively, pass `api-key` directly on the <ScriptGoogleMaps> component (note: this exposes the key client-side).')
const attrs = useAttrs()
const removedProps: Record<string, string> = {
markers: 'Use child <ScriptGoogleMapsMarker> components instead.',
centerMarker: 'Use a child <ScriptGoogleMapsMarker :position="center" /> instead.',
placeholderOptions: 'Use <ScriptGoogleMapsStaticMap> inside the #placeholder slot instead.',
placeholderAttrs: 'Use <ScriptGoogleMapsStaticMap> with :img-attrs instead.',
aboveTheFold: 'Use <ScriptGoogleMapsStaticMap loading="eager"> inside #placeholder instead.',
}
for (const [prop, message] of Object.entries(removedProps)) {
if (prop in attrs)
console.warn(`[nuxt-scripts] <ScriptGoogleMaps> prop "${prop}" was removed in v1. ${message} See https://scripts.nuxt.com/docs/migration-guide/v0-to-v1`)
}
}
const rootEl = useTemplateRef<HTMLElement>('rootEl')
const mapEl = useTemplateRef<HTMLElement>('mapEl')
const centerOverride = ref()
const trigger = useScriptTriggerElement({ trigger: props.trigger, el: rootEl })
const { load, status, onLoaded } = useScriptGoogleMaps({
apiKey: props.apiKey,
scriptOptions: {
trigger,
},
region: props.region,
language: props.language,
v: props.version,
})
const options = computed(() => {
const mapId = props.mapOptions?.styles ? undefined : (currentMapId.value || 'map')
return defu({ center: centerOverride.value, mapId, zoom: props.zoom }, props.mapOptions, {
center: props.center,
zoom: 15,
})
})
const isMapReady = ref(false)
const map: ShallowRef<google.maps.Map | undefined> = shallowRef()
function isLocationQuery(s: string | any) {
return typeof s === 'string' && (s.split(',').length > 2 || s.includes('+'))
}
const queryToLatLngCache = new Map<string, google.maps.LatLng | google.maps.LatLngLiteral>()
async function resolveQueryToLatLng(query: string) {
if (query && typeof query === 'object')
return Promise.resolve(query)
if (queryToLatLngCache.has(query)) {
return Promise.resolve(queryToLatLngCache.get(query))
}
// Use geocode proxy if available (avoids loading Places library client-side)
const endpoints = (runtimeConfig.public['nuxt-scripts'] as any)?.endpoints
if (endpoints?.googleMaps) {
const data = await $fetch<{ results: Array<{ geometry: { location: { lat: number, lng: number } } }>, status: string }>(`${scriptsPrefix()}/proxy/google-maps-geocode`, {
params: { address: query },
})
if (data.status === 'OK' && data.results?.[0]?.geometry?.location) {
const loc = data.results[0].geometry.location
const latLng = { lat: loc.lat, lng: loc.lng }
queryToLatLngCache.set(query, latLng)
return latLng
}
throw new Error(`No location found for ${query}`)
}
// Fallback: use Places API client-side. Wait for both the maps API and a
// Map instance: resolveQueryToLatLng is publicly exposed and may be called
// before onLoaded has populated map.value, so constructing PlacesService
// without map would throw.
await waitForMapsReady({ mapsApi, map, status, load })
const placesService = new mapsApi.value!.places.PlacesService(map.value!)
const result = await new Promise<google.maps.LatLng>((resolve, reject) => {
placesService.findPlaceFromQuery(
{
query,
fields: ['name', 'geometry'],
},
(results, status) => {
if (status === 'OK' && results?.[0]?.geometry?.location) {
resolve(results[0].geometry.location)
}
else {
reject(new Error(`No location found for ${query}`))
}
},
)
})
queryToLatLngCache.set(query, result)
return result
}
const libraries = new Map<string, any>()
function importLibrary(key: 'marker'): Promise<google.maps.MarkerLibrary>
function importLibrary(key: 'places'): Promise<google.maps.PlacesLibrary>
function importLibrary(key: 'geometry'): Promise<google.maps.GeometryLibrary>
function importLibrary(key: 'drawing'): Promise<google.maps.DrawingLibrary>
function importLibrary(key: 'visualization'): Promise<google.maps.VisualizationLibrary>
function importLibrary(key: string): Promise<any>
function importLibrary<T>(key: string): Promise<T> {
if (libraries.has(key))
return libraries.get(key)
const p = mapsApi.value?.importLibrary(key) || new Promise((resolve) => {
const stop = watch(mapsApi, (api) => {
if (api) {
const p = api.importLibrary(key)
resolve(p)
stop()
}
}, { immediate: true })
})
// Clear cache on failure to allow retry
const cached = Promise.resolve(p).catch((err) => {
libraries.delete(key)
throw err
})
libraries.set(key, cached)
return cached as Promise<T>
}
const googleMaps: ScriptGoogleMapsExpose = {
googleMaps: mapsApi,
map,
resolveQueryToLatLng,
importLibrary,
}
defineExpose<ScriptGoogleMapsExpose>(googleMaps)
// Shared InfoWindow group: only one InfoWindow open at a time within this map
let activeInfoWindow: google.maps.InfoWindow | undefined
provide(MAP_INJECTION_KEY, {
map,
mapsApi,
activateInfoWindow(iw: google.maps.InfoWindow) {
if (activeInfoWindow && activeInfoWindow !== iw) {
activeInfoWindow.close()
}
activeInfoWindow = iw
},
})
onMounted(() => {
watch(isMapReady, (v) => {
if (v) {
emits('ready', googleMaps)
}
})
watch(status, (v) => {
if (v === 'error') {
emits('error')
}
})
watch(options, () => {
if (!map.value)
return
// Exclude center and zoom — they have dedicated watchers that avoid
// resetting user interactions (pan/zoom) on unrelated re-renders.
const { center: _, zoom: __, ...rest } = options.value
map.value.setOptions(rest)
})
watch(() => options.value.zoom, (zoom) => {
if (map.value && zoom != null)
map.value.setZoom(zoom)
})
watch([() => options.value.center, isMapReady, map], async (next) => {
if (!map.value) {
return
}
let center = toRaw(next[0])
if (center) {
if (isLocationQuery(center) && isMapReady.value) {
center = await resolveQueryToLatLng(center as string)
}
// Skip setCenter if the map is already at the same position to avoid
// resetting user pan interactions on unrelated re-renders.
const current = map.value!.getCenter()
if (current) {
const newLat = typeof (center as any).lat === 'function' ? (center as any).lat() : (center as any).lat
const newLng = typeof (center as any).lng === 'function' ? (center as any).lng() : (center as any).lng
if (current.lat() === newLat && current.lng() === newLng)
return
}
map.value!.setCenter(center as google.maps.LatLng)
}
}, {
immediate: true,
})
onLoaded(async (instance: any) => {
mapsApi.value = await instance.maps
// may need to transform the center before we can init the map
const center = options.value.center as string
const _options: google.maps.MapOptions = {
...options.value,
// @ts-expect-error broken
center: !center || isLocationQuery(center) ? undefined : center,
}
map.value = new mapsApi.value!.Map(mapEl.value!, _options)
if (center && isLocationQuery(center)) {
centerOverride.value = await resolveQueryToLatLng(center)
if (centerOverride.value)
map.value?.setCenter(centerOverride.value)
}
isMapReady.value = true
})
})
if (import.meta.server) {
useHead({
link: [
{
rel: 'dns-prefetch',
href: 'https://maps.googleapis.com',
},
],
})
}
function toCssUnit(value: string | number | undefined): string | undefined {
if (value === undefined)
return undefined
if (typeof value === 'number')
return `${value}px`
return value
}
function isPixelValue(value: string | number | undefined): boolean {
if (typeof value === 'number')
return true
if (typeof value === 'string')
return DIGITS_ONLY_RE.test(value) || DIGITS_PX_RE.test(value)
return false
}
const rootAttrs = computed(() => {
return defu(props.rootAttrs, {
'aria-busy': status.value === 'loading',
'aria-label': status.value === 'awaitingLoad'
? 'Google Maps'
: status.value === 'loading'
? 'Google Maps Loading'
: 'Google Maps',
'aria-live': 'polite',
'role': 'application',
'style': {
cursor: 'pointer',
position: 'relative',
maxWidth: '100%',
width: toCssUnit(props.width),
height: isPixelValue(props.width) && isPixelValue(props.height) ? 'auto' : toCssUnit(props.height),
aspectRatio: isPixelValue(props.width) && isPixelValue(props.height) ? `${props.width}/${props.height}` : undefined,
},
...(trigger instanceof Promise ? trigger.ssrAttrs || {} : {}),
}) as HTMLAttributes
})
onBeforeUnmount(() => {
// Synchronous cleanup — Vue does not await async lifecycle hooks,
// so anything after an `await` runs as a detached microtask.
// Note: do NOT null mapsApi here — children unmount AFTER onBeforeUnmount
// and need mapsApi.value for clearInstanceListeners in their cleanup.
map.value?.unbindAll()
map.value = undefined
mapEl.value?.firstChild?.remove()
libraries.clear()
queryToLatLngCache.clear()
})
</script>
<template>
<div ref="rootEl" v-bind="rootAttrs">
<div v-show="isMapReady" ref="mapEl" :style="{ width: '100%', height: '100%', maxWidth: '100%' }" />
<slot v-if="!isMapReady" name="placeholder" />
<slot v-if="status !== 'awaitingLoad' && !isMapReady" name="loading">
<ScriptAriaLoadingIndicator />
</slot>
<slot v-if="status === 'awaitingLoad'" name="awaitingLoad" />
<slot v-else-if="status === 'error'" name="error" />
<slot />
</div>
</template>