无法使用 Vue3-leaflet 访问 Leaflet 对象
2021-07-21
3026
我试图从 leaflet 访问 flyTo 或 panTo,但不知何故它卡在错误
Uncaught TypeError: Cannot read property 'flyTo' of null
有没有指出问题可能是什么?我一直在关注这个: https://vue2-leaflet.netlify.app/faq/#how-can-i-access-the-leaflet-map-object 并且我提供了一个 ref="mymap" 和适当的 l-map 组件就绪事件来访问 mapObject。
<template>
<div class="mapContainer">
<l-map @readt="onStart()" ref="mymap" v-model="zoom" v-model:zoom="zoom" :center="center">
<l-tile-layer :url="url" :attribution="attribution"> </l-tile-layer>
<l-control class="clickControl" :position="position">
<p @click="showClick">Control</p>
</l-control>
</l-map>
<div class="controller">
Controls:
<div>
<button @click="flyToTarget()">Save</button>
</div>
</div>
</div>
</template>
<script>
// @ is an alias to /src
import {
LMap,
LTileLayer,
LControlLayers,
LControl,
} from "@vue-leaflet/vue-leaflet";
import "leaflet/dist/leaflet.css";
export default {
name: "Home",
components: {
LMap,
LTileLayer,
LControlLayers,
LControl,
},
data() {
return {
map: null,
zoom: 13,
url: "https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png",
attribution: `© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors © <a href="https://carto.com/attributions">CARTO</a>`,
center: [51.505, -0.09],
position: "topright",
latitude: "",
longitude: "",
};
},
methods: {
onStart(){
this.map = this.$refs.mymap.mapObject;
},
showClick() {
console.log("clicked");
},
flyToTarget() {
console.log("lat " + this.latitude + " and " + "lng " + this.longitude);
this.map.flyTo(this.center, 13);
},
},
};
</script>
<style scoped>
.mapContainer {
height: 65vh;
width: 100%;
z-index: 100;
border: 1px solid black;
}
.clickControl {
background: #fff;
padding: 0 0.5rem;
border: 1px solid black;
border-radius: 10px;
cursor: pointer;
user-select: none;
-moz-user-select: none;
-webkit-touch-callout: none;
-webkit-user-select: none;
}
.controller {
/* border: 1px solid black; */
height: 33vh;
width: 100%;
}
</style>
1个回答
使用此示例:
<template>
<l-map ref="map" style="height:50vh">
<l-tile-layer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"></l-tile-layer>
</l-map>
</template>
<script>
import "leaflet/dist/leaflet.css"
import { LMap, LTileLayer } from "@vue-leaflet/vue-leaflet";
import { ref, onMounted } from 'vue'
export default {
components: {
LMap,
LTileLayer
},
setup() {
const map = ref(null) // access ref...important
onMounted(async () => {
const { marker } = await import("leaflet/dist/leaflet-src.esm"); // import example
// create a marker and add to map Object usin
marker([0, 0]).addTo(map.value.leafletObject) // access leaflet object and use some properties
})
return { map } // expose map ref
}
}
</script>
OeeeYa
2022-04-22