You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Leaflet标记点击事件回调中类方法未定义问题求助

问题原因分析

你遇到的this.displayError is not a function错误,核心是函数调用时的this上下文丢失了。

当你把this.markerClick作为回调传给Leaflet的on('click')方法时,Leaflet会在触发点击事件时,将回调函数的this绑定到触发事件的marker实例上——而不是你的类实例。这就导致在markerClick里调用this.displayError时,this指向的是marker对象,而marker显然没有displayError方法,所以报错。

顺带提一句:你的代码里重复调用了marker.addTo(newMap),链式调用里已经加过一次了,后面那句可以删掉,避免重复添加标记。

解决方案

下面给你三种常用的修复方式,任选其一即可:

1. 用箭头函数包裹回调

箭头函数不会创建自己的this,它会继承外层作用域的this(也就是你的类实例):

newArray.forEach(p => { 
  let marker = L.marker(latLng)
    .on('click', (e) => this.markerClick(e)) // 箭头函数保留类的this上下文
    .addTo(newMap)
  marker.bindPopup(content)
  marker.openPopup() 
})

2. 用bind手动绑定this

通过bind(this)强制把回调函数的this绑定到类实例上:

newArray.forEach(p => { 
  let marker = L.marker(latLng)
    .on('click', this.markerClick.bind(this)) // 手动绑定类的this
    .addTo(newMap)
  marker.bindPopup(content)
  marker.openPopup() 
})

3. 把markerClick定义为箭头函数(类字段语法)

如果你的项目支持类字段语法(比如用了Babel或TypeScript),可以直接把类方法定义成箭头函数,这样它的this会永久绑定到类实例:

// 类内部修改markerClick的定义
markerClick = (e) => { 
  console.log("Inside marker click " + e.latlng.lat + " " + e.latlng.lng)
  this.displayError("You clicked on the marker") 
}

// 调用时直接传this.markerClick即可
newArray.forEach(p => { 
  let marker = L.marker(latLng)
    .on('click', this.markerClick) // 此时this已经绑定到类实例
    .addTo(newMap)
  marker.bindPopup(content)
  marker.openPopup() 
})

这三种方式都能解决this指向错误的问题,让你正常调用类里的displayError方法。

内容的提问来源于stack exchange,提问作者Usr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:18:13