0

I have used the geolocation API to return a user's coordinates. Instead of returning the latitude and longitude I would like to return the address of these coordinates. Is there any way I can do this? I'm using Rails for the backend so thought about using the geocoder gem but it would probably make more sense to do it with JS and keep all of the geocoding logic in one place. I have the following code at the moment.

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.";
  }
});
Steve
  • 418
  • 1
  • 4
  • 16

1 Answers1

0

You can use google reverse geocoding to get the address details from the coordinates.

After fetching the coordinates use geocoding to get the location from it. You can see sample from here

uday
  • 1,421
  • 10
  • 19
  • Thanks for the link. I'm terrible with JS though and can't work out how to make the code in the example work with my code. – Steve May 13 '19 at 11:43
  • how are you fetching the coordinates? – uday May 13 '19 at 13:40
  • using the [HTML Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API) – Steve May 13 '19 at 19:56
  • you can refer [this](https://stackoverflow.com/questions/14580715/get-my-current-address-using-javascript) & [this](https://stackoverflow.com/questions/19511597/how-to-get-address-location-from-latitude-and-longitude-in-google-map) SO answers and [this](https://www.w3schools.com/html/html5_geolocation.asp) resource which will solve you're problem. If any issues with that feel free to ask. – uday May 14 '19 at 04:41