It’s pretty common that we want to convert between a given address or postcode, a lat/long coordinate or a place name. For example to show the user’s current city or town we’d need to get their lat/long from their browser through the HTML Geolocation API and then we’d need to somehow work out what town or city that corresponds to. Or to search on a map for a certain town or city, we need to convert that into coordinates that we can use to set our map centre.
Fortunately OpenStreetMap have created a API called Nominatim to make all of this very easy for us.
All the documentation is in the link above but a couple of quick examples to get the information needed for the above situations.
Place name from Lat/Long
This call will return a JSON response for the selected coordinates (which happen to be for a Mitsubishi garage) and to give us just the city rather than the long full address (“Mitsubishi Motors, Feeder Road, St Philip’s, Bristol, City of Bristol, South West England, England, BS2 0TB, United Kingdom”) we add the extra query parameter “addressdetails=1”.
Lat/Long from place name
This call gives us a JSON response containing a number of results for the search term “bristol”. In this case Bristol, UK is the first result but in some cases your or the user’s desired result might be further down the list so be careful with assuming that your “bristol” is the most important “bristol” (though in this case it is!).