【发布时间】:2017-01-16 23:11:01
【问题描述】:
使用 googleapis 检测地理位置并使用 jQuery 从 openweathermap 接收该位置的当前天气
我正在尝试获取当前位置并获取该位置的当前天气。
这是我的 jQuery:
$(document).ready(function(){
function getCity(position) {
function getPosition() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getCity);
} else {
alert("Geolocation is not supported by this browser.");
}
}
var url = "https://maps.googleapis.com/maps/api/geocode/json? latlng=" + position.coords.latitude + "," + position.coords.longitude;
var city,
country;
$.getJSON(url, function(response) {
city = response.results[0].address_components[2].short_name;
country = response.results[0].address_components[5].short_name;
$('.yourLocationGoesHere').attr('value', city + ", " + country);
});
// Get weather by your location
var celsius, fahrenheit, iconCode, iconUrl;
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + city + "&APPID=7f5806c8f3fd28b03e2d6580a50732d6", function (data) {
celsius = Math.round(data.main.temp - 273.15);
fahrenheit = Math.round(9/5 * (data.main.temp - 273) + 32);
iconCode = data.weather[0].icon;
iconUrl = "http://openweathermap.org/img/w/" + iconCode + ".png";
$(".icon").html("<img src='" + iconUrl + "'>");
$(':radio').change(function(){
// "this" will be the checked radio element
if (this.id === 'celsius'){
$(".showDegree").html(celsius + "°C");
}else{
$(".showDegree").html(fahrenheit + "°F");
}
});
});
}
});
我做错了什么。请帮忙。
【问题讨论】:
-
iconUrl仅在$.getJSON()回调中作用域,并且不能在该回调之外访问。查看抛出的错误 "iconUrl is undefined" -
$.getJSON("api.openweathermap.org/data/2.5/weather?q=" + city + "&APPID=7f5806c8f3fd28b03e2d6580a50732d6", 函数(数据){ var celsius = Math.round(data.main.temp - 273.15); var fahrenheit = Math.round(9/5 * (data.main.temp - 273) + 32); var iconCode = data.weather[0].icon; var iconUrl = "openweathermap.org/img/w" + iconCode + ".png"; $ (".icon").html(""); });
-
@charlietfl 你能提供更多建议吗?
标签: javascript jquery json api geolocation