MaxDBN MaxDBN - 1 year ago 175
Ajax Question

Pass HTML5 geolocation to the controller

I want to get the user's coordinates using HTML5 Geolocation and send them to a helper method.
Geocoder gem is not an option because the IP geolocation is not accurate enough for my application.

Is that possible?
I'm using coffeescript and slim-lang

my helper method, located in application_helper.rb:

def get_station(location)
type = not relevant
key = not relevant
radius = 5000
url = "{location}&radius=#{radius}&type=#{type}&key=#{key}"
data = JSON.load(open(url))["results"][0]["name"]

the coffeescript part in my view (.slim template):

set_location = ->
if (navigator.geolocation)

setLocation = (position) ->
coords = position.coords.latitude + ", " + position.coords.longitude;

Threads I reviewed before posting:

Answer Source

It's not exactly answers the question itself but it does that I needed to do in the first place using AJAX and a controller method instead. It successfully passes the LAT,LNG params from HTML5 Geolocation to the controller method.


def location
    respond_to do |format|
      format.json {
        lat = params["lat"]
        lng = params["lng"]
        radius = 5000
        type = "restraunt"
        key = "-"
        url = "{lat},#{lng}&radius=#{radius}&types=#{type}&key=#{key}"
        data = JSON.load(open(url))
        results = []
        data["results"].each do |result|
          results.push({ "name":result["name"], "vicinity":result["vicinity"], "lat":result["geometry"]["location"]["lat"], "lng":result["geometry"]["location"]["lng"] })
        render json: { :data => results, :lat => lat, :lng => lng }


get "/location" => "application#location"


function getLocation(){
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position){
            type: 'GET',
            url: '/location',
            data: { lat: position.coords.latitude, lng: position.coords.longitude },
            contentType: 'application/json',
            dataType: 'json'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download