javascript - 未捕获的类型错误 : Cannot read property 'lat' of undefined Leaflet and VueJS

标签 javascript vue.js leaflet

我正在制作一个 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/

相关文章:

javascript - 为什么 Leaflet 不在 mouseout 事件中提供正确的 relatedTarget 元素?

javascript - 有没有办法使用 WebView 将 JavaScript 中的对象(类实例)提取到 Android?

javascript - 使用 JavaScript 获取 div 滚动位置。

vue.js - Strapi 和 Nuxt/Vue 访问图像 URL

json - 在 VueJS 中更改环境变量后,有没有办法热重新加载我的 Vue 页面?

vue.js - 如何防止在 ag-grid 中使用自定义 vue 组件验证错误时关闭单元格编辑模式

javascript - 使用 wms 或 wfs 从地理服务器获取 json 格式的 map

javascript - 如何使传单 map 根据动态面板点击动态缩放到位置?

javascript - Facebook JS API : how do I read the read_stream data?

javascript - document.querySelectorAll 在 IE、Edge 和 Safari 中的兼容性