首页 > 解决方案 > 如何使用 HERE API 填充两个表单字段 - 一个带有坐标,一个带有地址?

问题描述

我要实现的是一个按钮,单击该按钮时会返回用户最接近的地址并使用此数据填充表单字段。到目前为止,我已经能够使用 HTML Geolocation API 并将用户的当前坐标返回到表单字段。因此,我想在此基础上添加的是将这些坐标反向地理编码到街道地址并返回到不同的表单字段。我正在尝试使用 HERE API 来实现此问题的反向地理编码部分,但是 - 正如我所说 - 我很讨厌 JS,并且不知道代码应该是什么样子。

我用于返回用户坐标的代码在这里并且工作正常:

window.onload = function() {
    var currentLocation = document.getElementById('coordinatesStore');
    document.querySelector('.add-button').addEventListener('click', () => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(({
                coords: {
                    latitude,
                    longitude
                }
            }) => {
                currentLocation.value = latitude + ", " + longitude;
            });
        } else {
            currentLocation.value = "Geolocation is not supported by this browser.";
        }
    });
}

API文档中示例的反向地理编码坐标的代码如下,但我无法弄清楚如何将两者集成:

var platform = new H.service.Platform({
    app_id: 'blahblahblah',
    app_code: 'rararararararr'
});

function reverseGeocode(platform) {
  var geocoder = platform.getGeocodingService(),
    parameters = {
      prox: latitude + ", " + longitude,
      mode: 'retrieveAddresses',
      maxresults: '1'};

  geocoder.reverseGeocode(parameters,
    function (result) {
      alert(result);
    }, function (error) {
      alert(error);
    });
}

标签: javascriptgeocodinghere-api

解决方案


下面是一个例子。如果您有任何问题,请告诉我。

async function getLongLat() {
  //adding promise just for safe side to get it resolve first
  return new Promise((resolve, reject) => {
    let longitude = 'a',
        latitude = 'b'
    resolve( {
      longitude,
      latitude
    });   
  });
}

async function reverseGeocode(platform) {
  //var geocoder = platform.getGeocodingService(),
  try {
    const {latitude, longitude} = await getLongLat();
    console.log(latitude, longitude);
  }catch(err){
    //here error is getLongLat reject for any XYZ reason
  }
  
}

reverseGeocode()


推荐阅读