I am using vue3, leaflet and vue-leaflet with composition api.
I want to zoomIn the map when multi markers were added.
But when I use mapRef.value?.fitBounds(bounds, { padding: [50,50] })
,
it will show => TypeError: mapRef.value?.fitBounds is not a function.
I found many answer if I use option api.
Is there an answer for composition api or other better ways?
<template>
<l-map
ref="mapRef"
:zoom="zoom"
:center="center"
:use-global-leaflet="false"
>
<l-tile-layer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
<l-marker
v-for="(item, i) in markers"
:key="i"
:lat-lng="[item.LAT, item.LNG]"
/>
</l-map>
</template>
- JS:
<script setup>
const mapRef = ref(null)
const zoom = ref(9.5)
const center = ref([22.7, 120.25])
const markers = computed(() => data.map(item => {
return {
ID: parseInt(item.ID),
DTYPE: item.DTYPE,
LAT: parseFloat(item.LAT),
LNG: parseFloat(item.LNG)
}
}))
watch(markers, () => {
if (markers.value.length > 0 && mapRef.value) {
const minLat = Math.min(...markers.value.map(marker => marker.LAT))
const maxLat = Math.max(...markers.value.map(marker => marker.LAT))
const minLng = Math.min(...markers.value.map(marker => marker.LNG))
const maxLng = Math.max(...markers.value.map(marker => marker.LNG))
const boundsObj = L.latLngBounds(L.latLng(minLat, minLng), L.latLng(maxLat, maxLng))
// center
const centerObj = boundsObj.getCenter()
center.value = [centerObj.lat, centerObj.lng]
// zoom
// console.log(mapRef.value) // Proxy
mapRef.value?.fitBounds(boundsObj, { padding: [50, 50] })
}
})
I had saw an answer in another question.
It said bounds
in fitBounds(bounds)
is an array not an latLngBounds object.
But when I used typescipt it said the array type is not allowed.
Hazel Yang is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1