对 Ruby 和 Javascript 进行地理定位

Geolocating Ruby and Javascript

本文关键字:定位 Ruby Javascript      更新时间:2023-09-26

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

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()
    }

还有另一个地理定位器宝石称为地理编码器 我个人没有使用过它,但它在文档方面看起来相当不错。

我在查找I18n时找到了它