javascript Leaflet.Geosearch:从地址获取经度/纬度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30934341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:57:05  来源:igfitidea点击:

Leaflet.Geosearch: get lon/lat from address

javascriptleafletgeocoding

提问by Gromden

Without any knowledge of JS, I was forced to implement a map (OSM via Leaflet) on a webpage. On this map, there should be a marker for the actual address of a person. The address is saved as a string in the database. I can see a map, can add marker to it, but after that, I'm lost.

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

I've tested some Leaflet-geocoding-plugins, but i must confess, that they're not simple enough for my actual programmming experience.

我已经测试了一些 Leaflet-geocoding-plugins,但我必须承认,对于我的实际编程经验来说,它们不够简单。

Another questionwas about the same problem, but i didn't understand, how to get the lon/lat from an address with the L.Geosearch-plugin for Leaflet.

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

Can anyone provide me a example of looking up an address (via OSMN or something else, not google/bing or other api-key-needy provider), converting it to lon/lat and add a marker to it on a map?

谁能为我提供一个查找地址的示例(通过 OSMN 或其他方式,而不是 google/bing 或其他 api-key-needy 提供程序),将其转换为 lon/lat 并在地图上为其添加标记?

回答by Alechan

I made a jfsfiddle that

我做了一个 jfsfiddle

  1. Has an address set
  2. Looks for the coordinates of that address using geosearch
  3. Creates a marker at the coordinates of that address found by geosearch.
  1. 有地址集
  2. 使用地理搜索查找该地址的坐标
  3. 在地理搜索找到的该地址的坐标处创建一个标记。

It can be found here: https://jsfiddle.net/Alechan/L6s4nfwg/

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

The "tricky" part is dealing with the Javascript "Promise" instance returned by geosearch and that the address may be ambigous and more than one coordinate may be returned in that case. Also, be careful because the first position in the Leaflet coordinates corresponds to the latitude and the second to the longitude, which is in reverse of the Geosearch "x" and "y" results.

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

Geosearch returns a promise because it's an asynchronous call. The alternative would have to be a synchronous call and the browser would have to be freezed until an answer was retrieved. More info about promises from MDM (Mozilla)and Google.

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

In my example, I create a marker for every result found for the indicated address. However, in this case the address is unambiguous and returns only one result.

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

Breakdown of code:

代码分解:

<!-- 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>

回答by Titsjmen

First you will have to include the .js files of a geocoder in the head of your HTML code, for my example I have used this one: https://github.com/perliedman/leaflet-control-geocoder. Like this:

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

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

Then you will have to initialize the Geocoder in your .js:

然后你必须在你的 .js 中初始化 Geocoder:

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

Then you will have to specify the address that you are looking for, you can save it in a variable. For example:

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

var yourQuery = (Addres of person);    

(You can also get the address out of your database, then save it in the variable)

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

Then you can use the following code to 'geocode' your address into latitude / longitude. This function will return the latitude / longitude of the address. You can save the latitude / longitude in an variable so you can use it later for your marker. Then you only have to add the marker to the map.

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

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);
});