检索JSON引发错误:意外的令牌:

Retrieving JSON throws error: Unexpected token :

本文关键字:意外 令牌 错误 JSON 检索      更新时间:2023-09-26

我正在通过AJAX从Google Maps API检索高程数据。

我正在取回我想要的数据,就像我在Chrome中查看控制台一样,我可以看到一个200状态代码,并可以在响应选项卡中看到数据。但它会弹出"Uncaught SyntaxError:Unexpected token:",所以我无法显示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/

我们非常感谢所有的帮助。

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

相反,您需要使用Javascript API。

意识到这个问题已经过时了,我希望这能在未来帮助到一些人。这是我第一次接触javascript,尤其是所有这些JSON内容,因此我在试图弄清楚自己做错了什么时,头都掉了下来。

这是我的解决方案,它检索客户端的位置(在lat和lng中),然后使用谷歌地理编码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);
}