尝试让 map 读取所有应该动态可见的位置。
<script>
export default {
name: "GoogleMaps",
props: {
locations: {
type: Array,
default: () => {
return [];
},
},
visibleLocations: {
type: Array,
default: () => {
return [];
},
},
center: {
center: Object,
},
},
data() {
return {
userLocation: {},
locationsVisibleOnMap: "",
};
},
mounted() {
this.$refs.gMap.$mapCreated.then(() => {
const B = new window.google.maps.LatLngBounds();
// locationsVisibleOnMap should be loaded here
B.extend({
lat: 33.972,
lng: 35.4054,
});
this.$refs.gMap.fitBounds(B);
});
},
};
</script>
<template>
<div>
<GMap
ref="gMap"
:center="center"
:options="{
fullscreenControl: false,
streetViewControl: false,
mapTypeControl: false,
zoomControl: true,
gestureHandling: 'cooperative'
}"
:zoom="12"
>
<GMapMarker
v-for="location in locations"
:key="location.id"
:position="{ lat: location.lat, lng: location.long }"
@click="currentLocation = location"
>
<GMapInfoWindow :options="{ maxWidth: 200 }">
<b>{{ location.name }}</b>
<br />
<br />
<code>
Lat: {{ location.lat }},
<br />
Lng: {{ location.long }}
</code>
</GMapInfoWindow>
</GMapMarker>
</GMap>
</div>
</template>
我不断收到 undefined reference 。我一定做错了什么。
最佳答案
我最近不得不使用 nuxt-gmaps
来处理这个问题,并弄清楚了如何做到这一点,因此添加这个答案,以防其他人偶然发现这个问题,首先在您的 模板中
有类似的东西
<GMap ref="gMap" @loaded="fitBoundsToMarkers">
在你的方法中
fitBoundsToMarkers(google) {
const bounds = new google.maps.LatLngBounds(); // creates a bounds object
this.$refs.gMap.markers.forEach((marker) => bounds.extend(marker.getPosition())); // adds all the markers to the bounds object, you can filter it if you need that
this.$refs.gMap.map.fitBounds(bounds, { left: 400 }); // fitBounds, you can also add padding, I have a left padding of 400px here
},
这应该允许您使用已经设置的标记来适应负载的界限。如果您需要将边界调整到其他一些点,可以使用 extend
将它们添加到边界对象。
如果您需要从其他函数中自行调用 fitBoundsToMarkers
,那么您可以从 this.$refs.gMap.google 访问
.google
关于google-maps - nuxt-gmaps 动态添加边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70850580/