2

I'm programming a map with OpenLayers (4.6.5) and I use this API :

https://adresse.data.gouv.fr/api

What I want to do is /reverse/, I want to retrieve coordinates that I'm using in my popup (see my Codepen) to perform a query like this :

https://api-adresse.data.gouv.fr/reverse/?lon=2.37&lat=48.357

With my code I'm retrieving a lon-lat table. How could I separate my two coordinates and integrate it in my request ? Should I create a vector layer (the API is returning GeoJSON files) or an http request ?

4

You need to make an Ajax call using fetch (it could also be the "old" XMLHttpRequest, more a question of preferences)

The relevant code you need to change is the following

map.on('singleclick', function(evt) {
  var coordinate = evt.coordinate;
  // ol.proj.toLonLat(evt.coordinate) return an array of two elements
  // We use destructuring e.g https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
  var lat, lon;
  var [lon, lat] = ol.proj.toLonLat(evt.coordinate);
  fetch(`https://api-adresse.data.gouv.fr/reverse/?lon=${lon}&lat=${lat}`).then(response => response.json()).then(json => {
    console.log(json.features[0].properties.label);
      content.innerHTML = '<p>Adresse : ' + json.features[0].properties.label + ' </p><code>' + lon + ' ' + lat +
      '</code>';
  });
  overlay.setPosition(coordinate);
});

You can see a new demo forked from your sample

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.