简体   繁体   中英

How do I populate two form fields - one with coordinates, one with address - using the HERE API?

What I'm trying to implement is a button that when clicked returns the address that the user is closest to and populates a form field with this data. So far I have been able to use the HTML Geolocation API and return a user's current coordinates to a form field. So what I'd like to add on top of this is for those coordinates to be reverse geocoded into the street address and returned to a different form field. I'm trying to use the HERE API to achieve the reverse geocoding part of this problem, but - as I said - I suck at JS and don't really know how the code should look.

The code I have for returning the user's coordinates is here and works fine:

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

The code for reverse geocoding coordinates from an example on the API documentation is below but I can't work out how to integrate the two:

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

Below is an example. Let me know if you have any questions.

 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() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM