首页 > 解决方案 > 如何将 HTML5 Geolocation API 坐标传递给我的 Rails 控制器?

问题描述

我正在尝试使用 Open Weather API gem 创建一个简单的添加,用户可以在其中单击一个按钮并显示他们所在位置的当前天气。我想使用 HTML5 Geolocation API 返回用户的当前位置坐标,并使用这些从 Open Weather API 获取数据。如何将我的 JS 中的latitudelongitude值传递给我的控制器或服务类?目前我有这个代码:

位置.js

var x = document.getElementById("demo");
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude; 
}

服务/open_weather_api.rb

class OpenWeatherApi
  require 'open_weather'

  def initialize(lat, lon, units, appid = "abcdef123456")
    @options = { units: "metric", APPID: appid }
    @lat = lat
    @lon = lon
  end

  def my_location_forecast
    OpenWeather::Current.geocode(@lat, @lon, @options)
  end
end

预测控制器.rb

class ForecastsController < ApplicationController

  def current_weather
    @forecast = OpenWeatherApi.new(@lat, @lon, @options).my_location_forecast
  end
end

current_weather.html.erb

<p>Forecast: <%= @forecast['weather'][0]['description']%></p>

标签: ruby-on-railsrubyopenweathermap

解决方案


你可以做这样的事情一定要根据你的需要进行修改。

在 location.js 中,您可以发出 ajax 请求

$.ajax({
  type: "GET",
  dataType: "json",
  url: "/locations",
  data: { latitude: latitude, longitude: longitude }
  success: function(data){
 }
});

在你的控制器中

class ForecastsController < ApplicationController
  before_action :set_locations, only: [:current_weather]

 def locations
  @lat = param["data"]["latitude"]
  @lon = params["data"]["longitude"]
  respond_to do |format|
   format.json { success: "success" }
  end
 end

  def current_weather
    @forecast = OpenWeatherApi.new(@lat, @lon, @options)
  end
end

并且在

 routes.rb

get "/location", to: "forecasts#locations"

推荐阅读