Retrieving JSON throws error: Unexpected token :

最后都变了- 提交于 2020-01-05 03:33:08

问题


I'm retrieving the elevation data from the Google Maps API by AJAX.

I'm getting the data back I want as if I look at the console in Chrome I can see a 200 status code and can see the data in the response tab. But is throws up 'Uncaught SyntaxError: Unexpected token :' so I can't display anything from the JSON file.

This is my code:

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);
        }
    });

The live code is here: http://map.colouringcode.com/

All help is greatly appreciated.


回答1:


The Google Maps API does not support direct JSONP requests.

Instead, you need to use the Javascript API.




回答2:


Realizing this question is well outdated, I hope that this might be able to help someone in the future. This was my first encounter with javascript and especially all this JSON stuff and therefore caused a lot of hitting my head off the desk trying to figure out what I was doing wrong.

Here is my solution that retrieves the clients location (in lat and lng) and then uses the google geocoding api to determine their location in "human readable" format.

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);
}


来源:https://stackoverflow.com/questions/9177947/retrieving-json-throws-error-unexpected-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!