3

I developed an open-source APP in Cordova (it uses Javascript) and I'm using the Google Maps API, though as the APP is becoming popular my bill is increasing (not nice for a free, ad-free APP). Thus I'd like to move to Open Street Maps.

I've been reading the docs about the Overpass API but I see no simple clear examples of code implementation. I know the sever to use, that I should use HTTP GET requests and use their special XML syntax. But it's not clear how do I pass that XML to the GET request. Furthermore the examples regarding coordinates provides as input a boundary box, not a point (or a point is regarded as a square whose corners are the same?).

<union>
  <bbox-query s="51.249" w="7.148" n="51.251" e="7.152"/>
  <recurse type="up"/>
</union>
<print mode="meta"/>

Could you kindly provide a simple example in Javascript (for example with $.ajax) on how to get the address of a certain location by providing the geo-coordinates to the API?

João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109

2 Answers2

6

After some hours around, I share with you the working solution. Apparently, we should use the Nominatim service from Open Street Maps, and therein the reverse geocoding service. Please read the usage policy to avoid abuses, since this is a completely free service.

const coord = [38.748666, -9.103002] 
fetch(`https://nominatim.openstreetmap.org/reverse?lat=${coord[0]}&lon=${coord[1]}&format=json`, {
  headers: {
    'User-Agent': 'ID of your APP/service/website/etc. v0.1'
  }
}).then(res => res.json())
  .then(res => {
    console.log(res.display_name)
    console.log(res.address)
})
João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
  • Note that your code doesn't follow the usage policy. Now, I would say that's not strictly your responsibility as the answerer (SO answers are really a jumping-off point), but it's something to be aware of. – Julia Mar 06 '21 at 19:03
  • @Julia thanks, I amended accordingly. Do you think is OK now? – João Pimentel Ferreira Mar 07 '21 at 13:09
  • 1
    Yeah, I think it should be fine. In the end it’s the responsibility of the person who copies this code from SO anyway. – Julia Mar 07 '21 at 13:28
4

Another endpoint, and a short snippet:

fetch("https://nominatim.openstreetmap.org/search.php?q=48.886,2.343&polygon_geojson=1&format=json")
    .then(response => response.json())
    .then(j => {
      console.log(j[0].display_name)
})
NVRM
  • 11,480
  • 1
  • 88
  • 87