简体   繁体   中英

How to get the user latitude and longitude in model

I'm intending to execute some ruby on rails code after verifying if the current user is located at a certain area. My problem is that when using the request.location values I get latitude and longitude that do not correspond to the ones I got from google maps. Is there any other way to get the user location? I would like to avoid javascript code because I need to edit a ruby model after some condition with the location and I already had been fighting for a while with that.

BTW, I'm using devise for the user model.

My user model has a field called signed_in that is a boolean that store if a user is signed in only in one specified area.

class User < ActiveRecord::Base

 def is_at_place(lat, lon)
      #place = [-17.792365,-63.182531] #this is the actual place
      place = [-17.0000, -63.0000] #this is my home
      delta = 0.003000
      #latitude range
      rlat = (place[0]+delta)..(place[0]-delta)
      #longitude range
      rlon= (place[1]+delta)..(place[1]-delta)
      if rlat.include?(lat) and rlon.include?(lon)
        return true
      else
        return false
      end
    end

def set_signed_in(latitude, longitude)
    if is_at_place(latitude, longitude)
      user = User.find(session["warden.user.user.key"][0][0])
      user.signed_in = true
      user.save
      flash.alert = "Succesfully logged in"
    else
      flash.alert = "Succesfully logged in but as a outside user"
    end
  end

I will need to pass the latitude and longitude to the set_signed_in method in the user model.

I don't know if you want it for mobile or computer.

On mobile, you'll be able to get it working with and accurate position, on a computer a mac can use the wifi to have a more precise location but most computers won't.

The thing is that if your server is available from outside this will be a security issue because location spoofing is easy.

I'm guessing that this is a small personal website what you could do that would be safer to have an automatic login is to use your connection IP and signin base on that instead.

Also look at maxmind's geoip database, in case browsers don't send you the headers; they have a web-based version and also one you can store locally. There were also Teliza and Freegeoip.net.

Don't expect too much accuracy unless users are in some big city with location setvices on (GPS/AGPS)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM