【问题标题】:Uncaught TypeError: Cannot read property 'lat' of undefined Leaflet and VueJS未捕获的类型错误:无法读取未定义 Leaflet 和 VueJS 的属性“lat”
【发布时间】:2018-07-29 07:50:02
【问题描述】:

我正在制作一个 vue 项目,我想在我的组件中使用传单。我得到了显示的地图,但是当我尝试添加标记时遇到了错误。我明白了

未捕获的类型错误:无法读取未定义的属性 'lat'

TypeError: 无法读取未定义的属性“latlng”

我认为这是因为我没有正确设置地图边界?

<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>

【问题讨论】:

  • 在您的代码中,我没有看到任何尝试访问任何东西的 lat 属性
  • @Phil 在对 Leaflet 的L.marker(e.latlng) 的调用中。这表明 OP 包含完整的错误堆栈跟踪比仅包含最终错误要好得多。

标签: javascript vue.js leaflet


【解决方案1】:

您的 onClick 侦听器在 DOM 映射容器的 Vue 的 @click="onClick" 属性上调用。因此它会收到一个plain "click" event,它没有Leaflet 的latlng 添加属性。

既然你想在地图上而不是直接在它的容器上做某事,那么你可能想听Leaflet的地图"click"事件。在这种情况下,你可以简单地附加你的监听器:

this.map.on('click', onClick, this);

(您通常可以在初始化地图后附加它)

请注意,通过使用 Leaflet 的 on 的第三个参数,它将极大地帮助您绑定 this 上下文,否则您的侦听器中的 this 将引用您的 Vue 组件实例以外的其他内容(请参阅 Leaflet- marker click event works fine but methods of the class are undefined in the callback function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-30
    • 2018-07-31
    • 2017-07-12
    • 2017-08-23
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 2021-12-22
    相关资源
    最近更新 更多