Я пытаюсь создать приложение погоды, которое использует JSON API, чтобы вы могли получить погоду в своем местоположении. Для этого мне нужно местоположение пользователя.Не удалось найти местоположение с помощью JavaScript
$(document).ready(function(){
// gets user's location; shows Earth weather if location cannot be accessed
var longitude = 0;
var latitude = 0;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
latitude = Math.floor(position.coords.latitude);
longitude = Math.floor(position.coords.longitude);
});
}
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&appid=44db6a862fba0b067b1930da0d769e98", function(json){
// gets data from json
if (json.name == "Earth") {
$("#city").html("Your browser is not giving me access to your location. \n Showing Earth weather instead.");
} else {
$("#city").html(json.name);
$("#country").html(", " + json.sys.country);
}
var weather = json.weather[0].main;
$("#weather").html(weather);
var tempInKelvin = parseFloat(json.main.temp);
var tempInCelsius = Math.round((tempInKelvin - 273.15)*10)/10;
var tempInFahrenheit = tempInCelsius + 32;
$("#temperature").html(tempInFahrenheit); // shows temperature in Fahrenheit by default
// switches between Fahrenheit and Celsius when clicked
var iterator = 1; // because .toggle() was deprecated in jQuery 1.9
$("#unit").on("click", function(){
if (iterator % 2 == 1) {
$("#unit").html("℃"); // change to Celsius
$("#temperature").html(tempInCelsius);
} else {
$("#unit").html("℉"); // change back to Fahrenheit
$("#temperature").html(tempInFahrenheit);
}
iterator++;
});
// Changes background according to time of day
var time = new Date();
time = time.getHours();
// adds icon, depending on time and weather
switch (weather.toLowerCase()) {
case "clouds":
$("#icon").html('<p style = "color: white;">☁</p>');
break;
case "rain":
$("#icon").html('<p style = "color: blue;">☂</p>');
break;
case "snow":
$("#icon").html('<p style = "color: blue;">❄</p>');
break;
case "clear":
if (time >= 19 || time <= 4) {
$("#icon").html("fa-moon-o");
} else {
$("#icon").addClass("fa-sun-o");
}
break;
default:
$("#icon").html("No icon found :(");
}
});
});
По какой-то причине он просто сохраняет мою долготу и широту равными 0, не получая места. Я был в этом часами, но я не могу понять это.
И я знаю, что Chrome не предоставит страницу доступа к моему местоположению, но я поставил свой код на Codepen, который запрашивает доступ и получает его. Однако мой код по-прежнему не вносит никаких изменений в широту и долготу.
Возможный дубликат [Как вернуть ответ от асинхронного вызова?] (Http://stackoverflow.com/questions/14220321/how-do-return-the-response-from-an-asynchronous- звонок) – Andreas
@ Андреас частично прав, речь идет о асинхронном вызове, см. мой ответ ниже, чтобы понять это. – Farside
Попробуйте это http://jsfiddle.net/deepumohanp/a4g2J/ –