地理定位Ruby和Javascript

时间:2015-01-23 16:57:52

标签: javascript ruby-on-rails ruby

我在rails上构建了一个应用程序,Javascript用户可以上传图片,然后使用paperclip将它们保存到Amazon S3。我为每个保存在数据库中的图片添加了纬度和经度。我需要做的是获取用户当前的地理位置(我已经得到了这个但是在javascript方面)并在我的数据库中过滤距离用户位置半径1英里范围内的图片,然后发回这些图片。我真的很困惑如何做到这一点,我猜geolocator gem可能会有所帮助,但我是新手。如果有人能帮我一把,我感激不尽。

模型

class Upload < ActiveRecord::Base
    has_attached_file :image, :styles => { :medium => "300x300>",:thumb =>     "100x100>" }

    validates_attachment    :image, 
                :presence => true,
                :content_type => { :content_type => /\Aimage\/.*\Z/ },
                :size => { :less_than => 2.megabyte }

    def image_url
        image.url
    end
end

控制器

class UploadsController < ApplicationController

  def index
    render json: Upload.all.to_json(:methods => [:image_url])
  end

  def new
    @upload = Upload.new
  end

  def create
    @upload = Upload.create(upload_params)
    if @upload.save
      render json: { message: "success" }, :status => 200
    else
      #need to send an error header, otherwise Dropzone
      #  will not interpret the response as an error:
      render json: { error: @upload.errors.full_messages.join(',')}, :status => 400
    end         
  end

  private
  def upload_params
    params.require(:upload).permit(:image, :latitude, :longitude)
  end
end

Javascript用于获取当前的地理位置

x = $("#demo")[0];
        function getLocation() {
         if (navigator.geolocation) {
         navigator.geolocation.getCurrentPosition(showPosition);
         } 
         else {
         x.innerHTML = "Geolocation is not supported by this browser.";
         }
        }
        function showPosition(position) {
            var lat = position.coords.latitude;
            var long = position.coords.longitude;
        x.innerHTML = "Latitude: " + lat + 
        "<br>Longitude: " + long; 

        $('#upload_latitude').attr('value', lat)
        $('#upload_longitude').attr('value', long)
        }
        getLocation()
    }

1 个答案:

答案 0 :(得分:0)

另外还有一个名为geocoder的地理定位器宝石我个人无法使用它,但它看起来非常好。

我在查找I18n

时找到了它