Leaflet.Geosearch:从地址获取lon/lat

Leaflet.Geosearch: get lon/lat from address

本文关键字:lon lat 获取 地址 Geosearch Leaflet      更新时间:2023-09-26

在没有任何JS知识的情况下,我被迫在网页上实现一个地图(通过传单的OSM)。在这张地图上,应该有一个标记一个人的实际地址。地址在数据库中保存为字符串。我可以看到一张地图,可以为它添加标记,但在那之后,我迷路了。

我已经测试了一些传单地理编码插件,但我必须承认,它们对于我的实际编程经验来说还不够简单。

另一个问题是关于同样的问题,但我不明白,如何从带有 L.Geosearch 插件的传单的地址获取 lon/lat。

任何人都可以为我提供一个查找地址的示例(通过OSMN或其他东西,而不是google/bing或其他需要api密钥的提供商),将其转换为lon/lat并在地图上添加标记?

首先,

您必须在HTML代码的头部中包含地理编码器的.js文件,对于我的示例,我使用了这个:https://github.com/perliedman/leaflet-control-geocoder。喜欢这个:

<script src="Control.Geocoder.js"></script>

然后,您必须在.js中初始化地理编码器:

geocoder = new L.Control.Geocoder.Nominatim();

然后,您必须指定要查找的地址,可以将其保存在变量中。例如:

var yourQuery = (Addres of person);    

(您也可以从数据库中获取地址,然后将其保存在变量中)

然后,您可以使用以下代码将您的地址"地理编码"为纬度/经度。此函数将返回地址的纬度/经度。您可以将纬度/经度保存在变量中,以便以后将其用于标记。然后,您只需将标记添加到地图中即可。

geocoder.geocode(yourQuery, function(results) {    
       latLng= new L.LatLng(results[0].center.lat, results[0].center.lng);
       marker = new L.Marker (latLng);
       map.addlayer(marker);
});

我做了一个jfsfiddle,

  1. 设置了地址
  2. 使用地理搜索查找该地址的坐标
  3. 在地理搜索找到的该地址的坐标处创建标记。

可以在这里找到: https://jsfiddle.net/Alechan/L6s4nfwg/

"

棘手"的部分是处理地理搜索返回的Javascript"Promise"实例,并且地址可能不明确,在这种情况下可能会返回多个坐标。另外,请注意,因为传单坐标中的第一个位置对应于纬度,第二个位置对应于经度,这与地理搜索"x"和"y"结果相反。

Geosearch 返回一个承诺,因为它是一个异步调用。替代方案必须是同步调用,并且必须冻结浏览器,直到检索到答案。有关MDM(Mozilla)和Google承诺的更多信息。

在我的示例中,我为为指定地址找到的每个结果创建一个标记。但是,在这种情况下,地址是明确的,并且只返回一个结果。

代码分解:

<!-- Head, imports of Leaflet CSS and JS, Geosearch JS, etc -->
<div id='map'></div>

<script>
// Initialize map to specified coordinates
  var map = L.map( 'map', {
    center: [ 51.5, -0.1], // CAREFULL!!! The first position corresponds to the lat (y) and the second to the lon (x)
    zoom: 12
});
  // Add tiles (streets, etc)
  L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
    subdomains: ['a','b','c']
}).addTo( map );
var query_addr = "99 Southwark St, London SE1 0JF, UK";
// Get the provider, in this case the OpenStreetMap (OSM) provider.
const provider = new window.GeoSearch.OpenStreetMapProvider()
// Query for the address
var query_promise = provider.search({ query: query_addr});
// Wait until we have an answer on the Promise
query_promise.then( value => {
   for(i=0;i < value.length; i++){
     // Success!
     var x_coor = value[i].x;
     var y_coor = value[i].y;
     var label = value[i].label;
     // Create a marker for the found coordinates
     var marker = L.marker([y_coor,x_coor]).addTo(map) // CAREFULL!!! The first position corresponds to the lat (y) and the second to the lon (x)
     // Add a popup to said marker with the address found by geosearch (not the one from the user)
     marker.bindPopup("<b>Found location</b><br>"+label).openPopup();
   };
}, reason => {
  console.log(reason); // Error!
} );
</script>