I am currently working on a Typescript Vue project involving Leaflet. I came across some code for lazy-loading map markers, but it was written in Javascript. Although the code works fine, I keep receiving errors and warnings from VSCode because this
is not properly typed. How can I add type annotations to this
?
Update 1: With @aplet123's suggestion, I managed to resolve the first type issue. However, I am stuck with the second one related to this._updateIconVisibility
. It seems that this problem arises because I am extending existing functionality (i.e., _updateIconVisibility
does not actually exist as a type). What should be my next step? I assume it might be best practice to create a custom class with the necessary methods, but I am unsure if using an anonymous object or another approach is more common...
L.Marker.addInitHook(function (this: L.Marker) {
this.on(
'add',
function () {
this._updateIconVisibility = function () {
var map = this._map,
isVisible = map.getBounds().contains(this.getLatLng()),
wasVisible = this._wasVisible,
icon = this._icon,
iconParent = this._iconParent,
shadow = this._shadow,
shadowParent = this._shadowParent
// remember parent of icon
if (!iconParent) {
iconParent = this._iconParent = icon.parentNode
}
if (shadow && !shadowParent) {
shadowParent = this._shadowParent = shadow.parentNode
}
// add/remove from DOM on change
if (isVisible != wasVisible) {
if (isVisible) {
iconParent.appendChild(icon)
if (shadow) {
shadowParent.appendChild(shadow)
}
} else {
iconParent.removeChild(icon)
if (shadow) {
shadowParent.removeChild(shadow)
}
}
this._wasVisible = isVisible
}
}
// on map size change, remove/add icon from/to DOM
this._map.on(
'resize moveend zoomend',
this._updateIconVisibility,
this
)
this._updateIconVisibility()
},
this
)
})