0
最近我一直在處理Leaflet和不同的地圖。我目前正在嘗試使用由onClick事件創建的標記來顯示從API提供的JSON查詢解析的當前地址。處理AJAJ返回值
我成功解析了JSON查詢的地址(控制檯登錄到MapClick(e)的getAddress)。然而,我想要做的是從回調(?)函數中返回這個值,並使其作爲標記的內容可見。
function getAddress(lat, lon, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.digitransit.fi/geocoding/v1/reverse?point.lat=' + lat + '&point.lon=' + lon + '&size=1', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (typeof callback == "function") {
callback.apply(xhr);
}
}
}
xhr.send();
}
function onMapClick(e) {
popup
.setLatLng(e.latlng)
.setContent("Address is " +
getAddress(e.latlng.lat, e.latlng.lng, function() {
var resp = JSON.parse(this.responseText);
console.log(resp.features[0].properties.label); //This gives the correct current address in console
return resp.features[0].properties.label; //This SHOULD return the correct address, verified with the console log, and replace the function call in the marker's content window, however the address appears always as undefined.
}))
.openOn(map);
}
當'setContent'把它叫做追加的'返回值getAddress()'這是未定義的,而不是內部回調的返回值,正如你所期望的那樣。 –
我明白了!我如何訪問這個內部回調函數的返回值? –
推遲彈出窗口的創建,直到獲得收到的值。這是在回調中執行你的'popup.setLatLng ...'。 –