我正在制作一个 vue 项目,我想在我的组件中使用传单。我显示了 map ,但当我尝试添加标记时遇到错误。我明白了
Uncaught TypeError: Cannot read property 'lat' of undefined
和
TypeError: Cannot read property 'latlng' of undefined
我认为这是因为我没有正确设置 map 边界?
<template>
<div id="app" class="container">
<div class="row">
<div class="col-md-9">
<div id="map" @click="onClick" class="map" style="height: 781px;">
</div>
</div>
<div class="col-md-3">
<!-- The layer checkboxes go here -->
</div>
</div>
<router-view/>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
map: null,
marker: null,
mapSW: [0, 4096],
mapNE: [4096, 0]
},
mounted() {
this.initMap();
this.onClick();
},
methods: {
initMap() {
this.map = L.map("map").setView([0, 0], 1);
this.tileLayer = L.tileLayer("/static/map/{z}/{x}/{y}.png", {
maxZoom: 4,
minZoom: 3,
continuousWorld: false,
noWrap: true,
crs: L.CRS.Simple
});
this.tileLayer.addTo(this.map);
// this.map.unproject(this.mapSW, this.map.getMaxZoom());
// this.map.unproject(this.mapNW, this.map.getMaxZoom());
this.map.setMaxBounds(
L.LatLngBounds(L.latLng(this.mapSW), L.latLng(this.mapNW))
);
},
onClick(e) {
this.marker = L.marker(e.latlng, {
draggable: true
}).addTo(this.map);
}
}
};
</script>
最佳答案
您的 onClick
监听器在 DOM 映射容器的 Vue 的 @click="onClick"
属性上调用。因此它收到 plain "click"
event ,其中没有传单的 latlng
添加了属性。
既然您想在 map 上而不是直接在其容器上执行某些操作,那么您可能想听 Leaflet 的 map "click"
事件。在这种情况下,您可以简单地附加您的监听器:
this.map.on('click', onClick, this);
(通常可以在初始化 map 后附加它)
请注意,通过使用 Leaflet 的 on
的第三个参数,它将极大地帮助您绑定(bind) this
上下文。 ,否则监听器中的 this
将引用 Vue 组件实例以外的其他内容(请参阅 Leaflet- marker click event works fine but methods of the class are undefined in the callback function )
关于javascript - 未捕获的类型错误 : Cannot read property 'lat' of undefined Leaflet and VueJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48860038/