'How can I get map instance in map event with leflet? [duplicate]
I want to know the latitude and longitude of the four corners of the displayed map when I drag the map. So, I make a code to get the longitude and latitude of the four courners, at a drag event occurs timing.
I test this code. The code catch the event and the event handler is fired. However, when I ran map.getBound (), the interpreter return an error.The error message is as follows
'Uncaught TypeError: Cannot read properties of undefined (reading 'getBounds')'
I'm confused. From the error message, it is possible that the map instance has not been created, but it is also possible that the event handler is working and has been created.
What's wrong and how can I get the size of the map in the event handler?
The code is here
let Map; // map instance
let X; // map position(longitude)
let Y; // map position(latitude)
let Z; // map zoom ratio
let ColorIndex; // item color index
let ColorCode; // item color code
/**
* @brief main program
* @details main program
* initialize then show contents
*/
function WebViewMain()
{
// initialize
OSM_CoreInit();
OSM_EventHandle();
}
function OSM_CoreInit()
{
this.X = 0.0; // map position(longitude)
this.Y = 0.0; // map position(latitude)
this.Z = 1; // map zoom ratio
this.Map = new L.Map('map').setView([this.X, this.Y], this.Z);
let tiles = L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
attribution: 'Map data © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
id: 'mapbox/streets-v11',
tileSize: 512,
zoomOffset: -1
});
tiles.addTo(this.Map);
}
function OSM_EventHandle()
{
this.Map.on( 'moveend', function(e){
alert( this.Map.getBounds());
});
this.Map.on( 'click', function(e){
let aa = e.latlng;
});
}
thx.
Solution 1:[1]
When you call this in a function it uses the context of the function and not your class:
this.Map.on( 'moveend', function(e){
alert( this.Map.getBounds()); // this is now the event function and not the class, so there is no this.Map object
});
You need to pass the context of the class. Change to:
this.Map.on( 'moveend', (e)=>{
alert( this.Map.getBounds());
});
or
this.Map.on( 'moveend', function(e){
alert( this.Map.getBounds());
}, this);
or
this.Map.on( 'moveend', function(e){
alert( this.Map.getBounds());
}.bind(this));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Falke Design |
