Get Latitude and Longitude in Ruby On Rails

by Conor   Last Updated July 13, 2019 01:26 AM

In JavaScript, I can easily get my current Latitude and Longitude Coordinates and I'm trying to implement this in Ruby On Rails

In Javascript, I can use the following code to get my current Latitude and Longitude.

var x = document.getElementById("demo");

    function getLocation() {
  if (navigator.geolocation) {
  } else { 
    x.innerHTML = "Geolocation is not supported by this browser.";

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude;

In Rails, I am able to get my current IP address using the following


However, I am unable to convert this to a latitude and longitude,

The Javascript approach asks the users permission to use their current location which would be ideal for the scenario I am facing. I realise that there are gems out there that tackle this problem however I need this to work on localhost which the javascript method does.

Answers 1

you can use geocoder gem

first open your Gemfiles and add this line

gem 'geocoder'

from terminal run bundle install to install gem files then run rails console to test it here is sample to search for latitude and longitude for 10 downing street, london

results ="10 Downing Street, london")
latitude = results.first.coordinates[0]
longitude = results.first.coordinates[1]
July 13, 2019 01:24 AM

Related Questions

How do I validate coordinates in my Rails model?

Updated March 11, 2019 15:26 PM