如何将纬度和经度值传递到wunderground API中

时间:2016-12-16 11:24:13

标签: javascript jquery ajax

所以我设法得到我的地理位置,我测试了它,它的工作原理。然后我将经度和纬度值设置为变量,如下所示

var lat;
var long;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat= position.coords.latitude;
var long=position.coords.longitude;
// $(".data-now").html("latitude: " + lat  + "<br>longitude: " +long );
});

所以现在当我将这些变量传递给我的API并且在我的API中传递时它不起作用,这就是我如何做到的

$.ajax({
    url :        "//api.wunderground.com/api/8c89bxxxxf56bc94/conditions/q/lat,long.json",
    dataType : "jsonp",
    success : function(answer) {
        var location = answer['current_observation']['display_location']['full'];
        var temp_f = answer['current_observation']['temp_f'];
        var temp_c = answer['current_observation']['temp_c'];
        var weather = answer['current_observation']['weather'];
        var icon = answer['current_observation']['icon_url'];

任何帮助??

1 个答案:

答案 0 :(得分:1)

你应该改为连接变量,所以url应该是:

"//api.wunderground.com/api/8c89bxxxxf56bc94/conditions/q/"+lat+","+long+".json"

完整代码:

var lat;
var long;

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        lat= position.coords.latitude;
        long=position.coords.longitude;
});

var url = "//api.wunderground.com/api/8c89bxxxxf56bc94/conditions/q/"+lat+","+long+".json";
$.ajax({
    url : url,
    dataType : "jsonp",
    success : function(answer) {

    }
})

注意: var关键字应该在if块中移除(正如评论中 @Rowland Shaw 所述),您的变量已在块之前定义:

var lat= position.coords.latitude;
var long=position.coords.longitude;

应该是:

lat= position.coords.latitude;
long=position.coords.longitude;

希望这有帮助。