inocan-group / vue3-google-map

A set of composable components for easy use of Google Maps in your Vue 3 projects.
https://vue3-google-map.com
MIT License
285 stars 56 forks source link

how to use fitBounds on map markers #197

Closed charliestrafe closed 7 months ago

charliestrafe commented 7 months ago

Hi there,

I want to ensure my map shows all the markers currently on display. Previously with my own maps I have used something similar to the following:

const bounds = new window.google.maps.LatLngBounds();
markers.forEach(marker => bounds.extend(marker.getPosition()));
map.fitBounds(bounds);

This moves the map center point and adjusts the zoom to show all the current markers.

I'm struggling to replicate this on the vue-google-map package though. The closest I've got is the following:

watch(() => mapRef.value?.ready, (ready) => {
    if (!ready) return
    const bounds = new window.google.maps.LatLngBounds()
    computedProperties.value.forEach((marker) => {
        bounds.extend(marker.center)
    })
    mapRef.value.fitBounds(bounds)
})

And the map itself:

<GoogleMap
    class="w-full h-full absolute"
    :api-key="apiKey"
    :center="center"
    :zoom="4"
    ref="mapRef"
>
    <template #default="{ ready, api, map, mapTilesLoaded }">

The above results in the following error: Uncaught (in promise) TypeError: mapRef.value.fitBounds is not a function

Anyone got any suggestions on how to approach? Thanks!

HusamElbashir commented 7 months ago

You probably meant to do mapRef.value.map.fitBounds(bounds)

charliestrafe commented 7 months ago

Thank you, solved