2

我想要的是使用 Leaflet maps + 功能,我可以通过 Lat/Lng 并接收带有地址的短信。

我正在尝试使用 esri 插件,但是我做错了。目前我很想得到函数内部的地址,但我不知道如何正确地将它传递给变量。

这是我的代码:

var map = L.map('map').setView([40.725, -73.985], 7);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

var geocodeService = L.esri.Geocoding.geocodeService();

map.on('click', function(e) {
  geocodeService.reverse().latlng(e.latlng).run(function(error, result) {
    L.marker(result.latlng).addTo(map).bindPopup(result.address.Match_addr).openPopup();
  });
});

var message;

message = geocodeService.reverse().latlng([40.725, -73.985]).run(function(error, result) {
  //alert(result.address.Match_addr); //this alert works here ok and can retur addrress
  return result.address.Match_addr;
});

//this alert won't work, why I can get the address here outside the function
alert(message); 

这是完整的例子: https ://jsfiddle.net/5aq6z1vL/

如何使用地理编码器作为函数,如:

var address = convertToAddress([40.725, -73.985]);

function convertToAddress(]lat,lon])
{
  // here return address after geocoding
}
4

2 回答 2

1

只是您可以通过以下方式更改功能:

var geocodeService = L.esri.Geocoding.geocodeService();


geocodeService.reverse().latlng([36.2933693, 7.9388789]).run(function (error, result) {
  if (error) {
    return;
  }

  L.marker(result.latlng).addTo(map).bindPopup(result.address.Match_addr).openPopup();
});
于 2020-06-08T05:00:40.463 回答
0

发生这种情况是因为message它将被函数的 HTTP 响应填充run

因为该run函数需要一些时间来执行,所以alert(message)将在 run 函数完成之前执行。

这是可以解决您的问题的小提琴:JSFiddle

编辑:

好的,所以你要找的是Promises. 您的代码需要等待插件获取地址。不幸的是,我不知道如何用 vanilla JS 做到这一点,所以我导入了 jQuery(使用方法$.whenthen对象$.Deferred)。

这是新的小提琴

如果你在 vanilla JS 中需要这个,我可以查看 vanilla JS 中的 Promises。

于 2019-03-08T09:16:29.773 回答