2012-02-07 39 views
1

我正在通過AJAX從Google Maps API檢索高程數據。正在檢索JSON拋出錯誤:意外的令牌:

我正在收回數據,我希望看到Chrome中的控制檯我可以看到200狀態代碼,並可以在響應選項卡中看到數據。但是被拋出'未捕獲的SyntaxError:意外的標記:'所以我不能顯示JSON文件中的任何東西。

這是我的代碼:

var theURL = 'http://maps.googleapis.com/maps/api/elevation/json?locations=' + longitude + ',' + latitude + '&sensor=false&callback=?';  
$.ajax({ 
     url: theURL, 
     type: 'get', 
     dataType: 'json', 
     cache: false, 
     crossDomain: true, 
     success: function (data) { 
      var theData = $.parseJSON(data); 
      console.log(theData); 
     } 
    }); 

活代碼是在這裏:http://map.colouringcode.com/

所有幫助是極大的讚賞。

回答

0

Google Maps API不支持直接的JSONP請求。

取而代之,您需要使用Javascript API

+0

那麼如果不接受JSONP請求,我該如何獲取數據呢? – 2012-02-07 14:48:56

+0

相反,您需要使用[Javascript API](http://code.google.com/apis/maps/documentation/javascript/elevation.html)。 – SLaks 2012-02-07 15:14:14

0

認識到這個問題已經過時了,我希望這可以幫助未來的某個人。這是我第一次遇到javascript,尤其是所有這些JSON的東西,因此造成了很多讓我頭昏眼花的問題,試圖弄清楚我做錯了什麼。

這是我的解決方案,它檢索客戶端位置(以lat和lng),然後使用google地理編碼api以「人類可讀」格式確定其位置。

function currentLocation() { 
    navigator.geolocation.getCurrentPosition(foundLocation, errorLocation); 

    function foundLocation(position) { 
     var lat = position.coords.latitude; 
     var lng = position.coords.longitude; 

     //This is where the geocoding starts 
     var locationURL= "http://maps.googleapis.com/maps/api/geocode/json?latlng=" 
      + lat + "," + lng + "&sensor=false&callback=myLocation" 

     //This line allows us to get the return object in a JSON 
     //instead of a JSONP object and therefore solving our problem 
     $.getJSON(locationURL, myLocation); 
    } 

    function errorLocation() { 
     alert("Error finding your location."); 
    } 
} 

function myLocation(locationReturned) { 
    var town = locationReturned.results[0].address_components[1].short_name; 
    var state = locationReturned.results[0].address_components[4].short_name; 
    console.log(town, state); 
}