尝试从小叶地理编码器返回纬度和经度值 [英] Trying to return the latitude and longitude value from leaftlet geocoder

查看:99
本文介绍了尝试从小叶地理编码器返回纬度和经度值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图弄清楚如何从geocoder块中获取或返回值,以及如何在另一个function中使用该值.我不断收到variable is not defined错误

I've been trying to figure out how I can fetch or return the value from geocoder block and use the value in another function. I keep getting an variable is not defined error

geocoder = new L.Control.Geocoder.Nominatim();
var location = $('.location').text();

geocoder.geocode(location, function(results) {    
        var latLng = new L.LatLng(results[0].center.lat, results[0].center.lng);
        var marker = new L.Marker (latLng);
        // console.log(Object.values(latLng));   

        var geocodeLocation = Object.values(latLng);
});
    
function loc() {

      console.log(geocodeLocation);
      
}

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"
    integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og=="
    crossorigin=""></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/perliedman-leaflet-control-geocoder/1.9.0/Control.Geocoder.js"></script>
    
    
      <span class="location">Philippines</span>

推荐答案

正如我的评论中所述,如果您全局声明geocodeLocation并且函数geocoder.geocode是异步的,则不能保证在您执行以下操作时会设置该变量会用它.我能想到的解决此问题的唯一方法(即在其他地方使用geocodeLocation)是使用Promises.这样,您实际上就可以返回geocodeLocation.

As said in my comment, if you declare geocodeLocation globally and the function geocoder.geocode is asynchronous, then there’s no guarantee that the variable will be set when you’ll use it. The only way I can think of to solve this (that is, using geocodeLocation elsewhere) is using Promises. This way you can actually return geocodeLocation.

关于异步执行如何工作的快速说明. (不用担心,我也曾经问过如何从异步调用中返回).

A quick explanation about how asynchronous execution works. (Don't worry I also used to ask how to return from an asynchronous call).

说我们有两个功能

function1()
function2()

function1()是异步的.这意味着function2()不会等待function1()结束以开始运行.但是Geocoder.geocode的回调(您传递给它的函数)仅在完成其异步操作时才被调用.但是function2()已经被调用了.

and function1() is asynchronous. What that means is that function2() won't wait that function1() ends to start running. But Geocoder.geocode's callback (the function you pass to it) will be called only when it finishes its asynchronous operation. But function2() will have already been called..

但是有一种方法可以返回值(使用async/await),类似于以下几行:

But there is way to return a value(using async/await), something along these lines:

function geocode(location, func) { //that's the geocoder.geocode
  //calculate coordinates with location
  var results = { coordinates: { lat: '37.423021', long: '-122.083739' } }
  func(results);
}
    
async function fetchGeocodeLocation(location) {

  var promise = new Promise((resolve, reject) => { //wrap your geocoder.geocode function in a Promise
    geocode(location, function(results) { 
      //var latLng = new L.LatLng(results[0].center.lat, results[0].center.lng);
    //var marker = new L.Marker (latLng);
    // console.log(Object.values(latLng));   

    //var geocodeLocation = Object.values(latLng);  

      resolve(results.coordinates);
    });
  });

  var geoCodeLocation = await promise;
  return geoCodeLocation;
}

fetchGeocodeLocation("somewhere").then(geoCodeLocation => console.log("geoCodeLocation", geoCodeLocation))

或者说您的loc()函数是异步的,那么就像这样

Or, say your loc() function is asynchronous, then like so

function geocode(location, func) {
  //calculate coordinates with location
  var results = { coordinates: { lat: '37.423021', long: '-122.083739' } }
  func(results);
}
    
function fetchGeocodeLocation(location) {

  return new Promise((resolve, reject) => { //wrap your geocoder.geocode function in a Promise
    geocode(location, function(results) { 
      //var latLng = new L.LatLng(results[0].center.lat, results[0].center.lng);
    //var marker = new L.Marker (latLng);
    // console.log(Object.values(latLng));   

    //var geocodeLocation = Object.values(latLng);  

      resolve(results.coordinates);
    });
  });
}

async function loc() {
  var location = "somewhere";
  var geoCodeLocation = await fetchGeocodeLocation(location);
  console.log("geoCodeLocation", geoCodeLocation)
}

loc()

最后,简要介绍 async/await .

等待做什么?

在执行等待行之后的所有内容之前,它等待promise解析.无需等待,承诺之后的任何事情都会在承诺解决之前执行.您将获得未决状态的承诺.

It waits that the promise resolves before executing anything that comes after the await line. Without await, anything that comes after it will be executed before the promise resolves. You will get a promise in pending state.

我们为什么必须在异步函数中使用await?

带有await的行可能需要30秒钟执行,您的浏览器将冻结(这也是ajax调用是异步的原因).浏览器会询问您是否要终止冻结浏览器的脚本(有人做错了事).因此,异步表示该函数是异步的,在函数调用之后发生的任何事情都不会等到它完成之后再开始.但是,等待会确保在承诺完成之前不会执行任何后续操作.

The line with await might take 30 seconds to execute and your browser will freeze (that's also why ajax calls are asynchronous). The browser will ask you if you want to terminate that script that's freezing the browser (someone been doing something bad). So the async says the function is asynchronous, anything that comes after the function call won't wait that it finishes before starting. However, the await makes sure that anything that comes after it won't be executed before the promise resolves.

这篇关于尝试从小叶地理编码器返回纬度和经度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆