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 ...'。 –