简体   繁体   中英

Retrieving JSON throws error: Unexpected token :

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.

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

The Google Maps API does not support direct JSONP requests.

Instead, you need to use the Javascript API .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM