everybody. I am currently creating an application that allows to plant markers in the leaflet map and according to the lat and Ing it looks for the address at the given coordinates. For address finding I am using "Nominatim" which works very well. Unfortunately, there is an asynchronization in my code that I am not able to solve.
This is my class constructor
class Ereigniss {
constructor(latlng, { info = null, time = null, isMarker = null, geoLabel = null } = {}) {
this.latlng = latlng
this.info = info
this.time = time
this.geoLabel = geoLabel
this.isMarker = isMarker
if (!isMarker) {
this.startMarker = latlng[0]
this.endMarker = latlng[latlng.length - 1]
}
this.id = Date.now()
}
setGeoLabel(geoLabel) {
this.geoLabel = geoLabel
return this
}
setInfo(info) {
this.info = info
return this
}
setTime(time) {
this.time = time
return this
}
setLatlng(latlng) {
this.latlng = latlng
return this
}
}
This is ajax function, which looks for address on given lat and lng. This work very well I would say.
function getGeoLabel(lat, lng) {
$.ajax({
url: `https://nominatim.openstreetmap.org/reverse?format=geocodejson&lat=${lat}&lon=${lng}`,
method: 'get',
success: resp => {
let label = resp.features[0].properties.geocoding.label
let trimString = label.split(',').slice(0, 4)
let labelResult = trimString.join(',');
return labelResult
},
error: resp => {
console.log(resp + 'err');
}
})
}
And finally, a function that does everything necessary. If I insert a marker into the card, the first thing created is the new Class constructor "Ereigniss". This will give me the necessary information for lat and lng, which now the function getGeoLabel has to work with, and I will use the return of this function in the third step to call setGeoLabel from the constructor, which will give my object the information about the address. Unfortunately the response is always undefined. I know that the problem will be in asynchronization but I have absolutely no idea how to solve this problem effectively. Thank you for your help
map.on('draw:created', function (e) {
let type = e.layerType,
layer = e.layer,
latlng = layer._latlngs || layer._latlng;
// console.log(latlng.lat, latlng.lng);
if (type === 'marker') {
let markerObj = new Ereigniss(latlng, { isMarker: true })
let foundLabel = getGeoLabel(latlng.lat, latlng.lng)
markerObj.setGeoLabel(foundLabel)
markerIcon = new L.marker([latlng.lat, latlng.lng], {
draggable: false
}).addTo(map)
console.log(markerObj) //undefined
}
})