简体   繁体   中英

Uncaught TypeError: Cannot read property 'lat' of undefined Leaflet and VueJS

I am making a vue project and I want to use leaflet inside of my components. I got the map showing but I run into an error when I try to add a marker. I get

Uncaught TypeError: Cannot read property 'lat' of undefined

and

TypeError: Cannot read property 'latlng' of undefined

I think it's because I'm not setting my map bounds correctly?

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

Your onClick listener is called on Vue's @click="onClick" attribute of your DOM map container. Therefore it receives a plain "click" event , which does not have the Leaflet's latlng added property.

Since you want to do something on the map and not directly on its container, then you probably meant to listen to Leaflet's map "click" event. In that case, you can simply attach your listener with:

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

(you can attach it typically just after you initialize your map)

Note that it will greatly help you binding the this context by using the 3rd argument of Leaflet's on , otherwise this in your listener will refer to something else than your Vue component instance (see Leaflet- marker click event works fine but methods of the class are undefined in the callback function )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM