尝试从小叶地理编码器返回纬度和经度值

问题描述 投票:0回答:1

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

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/[email protected]/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>
javascript leaflet geocoding
1个回答
0
投票

我能想到的解决此问题的唯一方法(即在其他地方使用geocodeLocation)是使用Promises。

我对此不太确定,但遵循以下原则:

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().then(geoCodeLocation => console.log("geoCodeLocation", geoCodeLocation))
© www.soinside.com 2019 - 2024. All rights reserved.