所以,我无法弄清楚为什么这不起作用:
$.getJSON('http://www.mapquestapi.com/geocoding/v1/reverse?key=KEY&callback=renderReverse&json&location=' + lat + ',' + longi, function(geo) {
$('#location').html(geo.response.results[0].locations[0].adminArea4);
});
返回的json是:
{
"results": [
{
"locations": [
{
"latLng": {
"lng": -1,
"lat": 51
},
"adminArea4": "Hamp",
"adminArea5Type": "City",
"adminArea4Type": "County",
"adminArea5": "Ba and De",
"street": "Teal Crescent",
"adminArea1": "GB",
"adminArea3": "England",
"type": "s",
"displayLatLng": {
"lng": -1.145731,
"lat": 51.240441
},
"linkId": 0,
"postalCode": "RG3",
"sideOfStreet": "N",
"dragPoint": false,
"adminArea1Type": "Country",
"geocodeQuality": "ADDRESS",
"geocodeQualityCode": "L1AAA",
"mapUrl": "http://www.mapquestapi.com/staticmap/v4/getmap?key=Fmjtd|luubnu0yn5,7g=o5-9072ur&type=map&size=225,160&pois=purple-1,51.2401563,-1.1463337,0,0|¢er=51,-17&zoom=15&rand=-859825484",
"adminArea3Type": "State"
}
],
"providedLocation": {
"latLng": {
"lng": -1.146334,
"lat": 51.240156
}
}
}
],
"options": {
"ignoreLatLngInput": false,
"maxResults": -1,
"thumbMaps": true
},
"info": {
"copyright": {
"text": "© 2013 MapQuest, Inc.",
"imageUrl": "http://api.mqcdn.com/res/mqlogo.gif",
"imageAltText": "© 2013 MapQuest, Inc."
},
"statuscode": 0,
"messages": []
}
}
我猜是因为我的geo.response.results
位错了!
帮助将不胜感激。
答案 0 :(得分:3)
返回的JSON中没有response
个键。试试这个:
$.getJSON('http://www.mapquestapi.com/geocoding/v1/reverse?key=KEY&callback=renderReverse&json&location=' + lat + ',' + longi, function(geo) {
$('#location').html(geo.results[0].locations[0].adminArea4);
});
答案 1 :(得分:1)
虽然上面的答案是正确的,但是您的服务返回的json似乎也存在问题。它在返回错误请求时会出现无效字符。
如果你使用了json成功和错误消息,你会看到这个
var lat = -1.146334;
var longi = 51.240156;
$.getJSON( 'http://www.mapquestapi.com/geocoding/v1/reverse?key=**YOURKEY**&callback=renderReverse&json&location=' + lat + ',' + longi )
.done(function( json ) {
console.log( "JSON Data: " + json);
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
问题是因为你的回复中有json p。要解决这个问题,你需要声明jsonp,以获得正确的json对象。
var lat = -1.146334;
var longi = 51.240156;
$.getJSON( 'http://www.mapquestapi.com/geocoding/v1/reverse?key=**YOURKEY**&callback=renderReverse&json&location=' + lat + ',' + longi, {format: "jsonp"} )
.done(function( geo ) {
$('#location').html(geo.results[0].locations[0].adminArea4);
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});