user12564127
user12564127

Reputation:

Uncaught TypeError: Cannot read property 'openPopup' of undefined

im currently using leaflet to get coord on click, but when i try to display the popup using the code on the documentation, i get this : << Uncaught TypeError: Cannot read property 'openPopup' of undefined >> i precise that i can see the map, she is created with no error logged, it's when i trigger the onclick event that i catch the error, ty in advance, here is my code :

export class CarteCodeAffaires {

constructor() {

    this._root                      = document.getElementById("fa-carte-codes-affaires")

    this._infos_carte               = JSON.parse(this._root.dataset.infos_carte)
    const bordures = L.latLngBounds(
        L.latLng(this._infos_carte.bordures.nord, this._infos_carte.bordures.ouest),
        L.latLng(this._infos_carte.bordures.sud, this._infos_carte.bordures.est)
    )

    this._carte = new L.Map(this._root,{
        closePopupOnClick: true,
        center: this._infos_carte.centre,
        zoom: this._infos_carte.zoom,
        maxBounds: bordures
    })

    // Arrière plan
    this._carte.addLayer(new L.TileLayer(OSM_URL, {minZoom: this._infos_carte.zoom_min, maxZoom: this._infos_carte.zoom_max, attribution: OSM_ATTRIB}))

    // Empèche de sortir des bordures
    this._carte.on('drag', () => this._carte.panInsideBounds(bordures, { animate: false }))

    // Donne les coordonnées au clique
    var popup = L.popup();

    function onMapClick(e) {
        popup
            .setLatLng(e.latlng)
            .setContent("Coordonnées : " + e.latlng.toString())
            .openOn(this._carte);
    }

    this._carte.on('click', onMapClick);
}

invalidateSize(){
    this._carte.invalidateSize()
}

cacher(){
    this._root.classList.add('d-none')
}

montrer(){
    this._root.classList.remove('d-none')
}

}

Upvotes: 1

Views: 2008

Answers (1)

Falke Design
Falke Design

Reputation: 11338

This is because the context of this in the onMapClick is not the same as the this outside.

Change your code to: this._carte.on('click', onMapClick, this); then it is the same context and this._carte is found

Upvotes: 1

Related Questions