ruby-on-rails - 如何将 HTML5 Geolocation API 坐标传递给我的 Rails 控制器?
问题描述
我正在尝试使用 Open Weather API gem 创建一个简单的添加,用户可以在其中单击一个按钮并显示他们所在位置的当前天气。我想使用 HTML5 Geolocation API 返回用户的当前位置坐标,并使用这些从 Open Weather API 获取数据。如何将我的 JS 中的latitude
和longitude
值传递给我的控制器或服务类?目前我有这个代码:
位置.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>
解决方案
你可以做这样的事情一定要根据你的需要进行修改。
在 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"
推荐阅读
- amazon-s3 - 列出具有特定名称标签的 s3 文件夹
- php - 根据用户角色创建单独的表
- python - Python pandas - 按组有效地将函数应用于缺少日期的滚动窗口
- javascript - 删除多个电子表格中的多个工作表
- javascript - 三.js 移动触摸允许身体滚动
- c++ - 错误:请求“b”中的成员“q”,它是非类类型“const int”
- artifactory - Artifactory 7.2.1 - 如何更改 Artifactory 和 UI 的监听地址
- javascript - 并排的带有水平滚动条的代码框?
- gulp - 从 gulp 版本 3 转换到 gulp 版本 4 时面临的问题
- c# - (潜在的 Visual Studio 错误)Visual Studio 2019 错误列表显示不应存在的错误,因为该错误实际上并不存在