正如对错误报告和 API 文档的评论中所指出的,response
回调中的对象不是纯 JSON。为了得到一个 JSON 对象,我需要自己创建一个,如下所示:
//assume status is ok
var bestResult = getBestResultFromJSON(results);
var bounds = {'northeast' : {'lat' : 0, 'lng' : 0}, 'southwest' : {'lat' : 0, 'lng' : 0}};
var location = {'lat' : 0, 'lng' : 0};
var viewport = {'northeast' : {'lat' : 0, 'lng' : 0}, 'southwest' : {'lat' : 0, 'lng' : 0}};
// bounds not always available (https://developers.google.com/maps/documentation/javascript/reference#GeocoderGeometry)
if(bestResult.geometry.hasOwnProperty(bounds)) {
bounds.southwest.lat = bestResult.geometry.bounds.getSouthWest().lat();
bounds.southwest.lng = bestResult.geometry.bounds.getSouthWest().lng();
bounds.northeast.lat = bestResult.geometry.bounds.getNorthEast().lat();
bounds.northeast.lng = bestResult.geometry.bounds.getNorthEast().lng();
}
else {
bounds = null;
}
viewport.southwest.lat = bestResult.geometry.viewport.getSouthWest().lat();
viewport.southwest.lng = bestResult.geometry.viewport.getSouthWest().lng();
viewport.northeast.lat = bestResult.geometry.viewport.getNorthEast().lat();
viewport.northeast.lng = bestResult.geometry.viewport.getNorthEast().lng();
location.lat = bestResult.geometry.location.lng();
location.lng = bestResult.geometry.location.lng();
var jsonResults = {'results' : [{'address_components' : bestResult.address_components,
'formatted_address': bestResult.formatted_address,
'geometry' : {'bounds' : bounds, 'location' : location, 'location_type' : bestResult.location_type, 'viewport' : viewport},
'types' : bestResult.types}], 'status' : status};