2012-02-07 68 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); 
}