【问题标题】:Geolocating Ruby and Javascript地理定位 Ruby 和 Javascript
【发布时间】:2015-01-24 11:16:35
【问题描述】:

我在 Rails 和 Javascript 上构建了一个应用程序,用户可以上传图片,然后我使用回形针将它们保存到 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()
    }

【问题讨论】:

    标签: javascript ruby-on-rails ruby


    【解决方案1】:

    还有另一个geolocator gem,叫做geocoder我个人没有用过,但它看起来相当不错的文档。

    我在查找I18n时发现了它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多