2013-04-18 87 views
0

目前正在爲iOS的天氣web應用程序工作。我試圖獲取用戶的座標,並將緯度和經度放在我的Ajax請求中(在api Wunderground上)。獲取ajax請求的位置座標

這裏是我的代碼(編輯):

<script type="text/javascript"> 
     $(document).ready(function() { 

     navigator.geolocation.getCurrentPosition(getLocation, unknownLocation); 

     function getLocation(pos) 
     { 
      var lat = pos.coords.latitude; 
      var lon = pos.coords.longitude; 

      $.ajax({ 
        url : "http://api.wunderground.com/api/ApiId/geolookup/conditions/q/"+ lat +","+ lon +".json", 
        dataType : "jsonp", 

        success : function(parsed_json) { 
         var location = parsed_json['location']['city']; 
         var temp_f = parsed_json['current_observation']['temp_f']; 
         alert("Current temperature in " + location + " is: " + temp_f); 
        } 
        }); 
     } 
     function unknownLocation() 
     { 
      alert('Could not find location'); 
     } 
     }); 
    </script> 

正如你可以看到我「簡單的」要創建2瓦爾緯度和經度,在我的要求添加。我嘗試了很多變體,但我無法獲得此代碼的工作。

任何想法我做錯了什麼?

非常感謝!

+0

您是否註冊了API密鑰?看起來你需要一個。 – epascarello

+0

我有一個,我只是隱藏在我的代碼,因爲你不需要它:) – MonBlaze

回答

0

您的變量聲明位於.ajax調用的中間,並且使JavaScript結構無效。另外,我不確定你爲什麼使用「function($)」,通常在jQuery中,$是保留的,不應該用作函數參數。

<script type="text/javascript"> 
$(document).ready(function() { 
    navigator.geolocation.getCurrentPosition(onPositionUpdate); 
}); 


function onPositionUpdate(position) { 
    var lat = position.coords.latitude; 
    var lon = position.coords.longitude; 
    $.ajax({ 
     url : "http://api.wunderground.com/api/ApiId/geolookup/conditions/q/"+lat+","+lon+".json", 
     dataType : "jsonp", 
     success : function(parsed_json) { 
      var location = parsed_json['location']['city']; 
      var temp_f = parsed_json['current_observation']['temp_f']; 
      alert("Current temperature in " + location + " is: " + temp_f); 
     } 
    }); 
} 
</script> 
+0

我有一個錯誤:未捕獲參考錯誤:位置未定義。我認爲這是iOS中的一個實現變量? – MonBlaze

+0

您需要使用getCurrentPosition()方法獲取位置:http://www.digimantra.com/howto/current-location-iphone-safari-firefox-browser/ –

+0

完美地工作,非常感謝您! – MonBlaze