返回未定义的Javascript Google地理代码(Can';t图形回调函数)
我试图存储从Google地理编码API得到的响应中得到的纬度和经度值。现在我在加州使用一个固定的位置。我的HTTP请求一直返回未定义 我一直在四处寻找,我发现人们也有同样的问题,但我不能全神贯注地做一个回调函数,这似乎是解决问题的办法,有人能告诉我怎么做吗?我知道我的CORS请求正在工作,因为我正在使用它从我设置的Heroku服务器上获取信息返回未定义的Javascript Google地理代码(Can';t图形回调函数),javascript,google-maps,geocode,Javascript,Google Maps,Geocode,我试图存储从Google地理编码API得到的响应中得到的纬度和经度值。现在我在加州使用一个固定的位置。我的HTTP请求一直返回未定义 我一直在四处寻找,我发现人们也有同样的问题,但我不能全神贯注地做一个回调函数,这似乎是解决问题的办法,有人能告诉我怎么做吗?我知道我的CORS请求正在工作,因为我正在使用它从我设置的Heroku服务器上获取信息 var geocode = new XMLHttpRequest(); geocode = createCORSRequest('GET', 'https
var geocode = new XMLHttpRequest();
geocode = createCORSRequest('GET', 'https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=');
geocode.onload = function() {
var geoData = JSON.parse(geocode.responseText); // parse the JSON from geocode response
var results = geoData["results"]; // create variable for results
var userLong = results["geometry"]["location"]["lng"]; // parse the latitude
var userLat = results["geometry"]["location"]["lat"]; // parse the longitude
console.log(userLong);
console.log(userLat);
}
createCORSRequest()
假设
createCORSRequest
返回一个类似xhr
或xhr
的对象(这似乎是HTML5 Rocks网站上createCORSRequest的典型样板文件),则需要包含geocode.send()代码>在代码末尾。否则,请求永远不会触发,因此不会调用onload
处理程序。看起来您正在关注HTML5Rocks
站点文章
创建xhr
请求后。您必须调用send()
方法来触发ajax调用
var geocode = new XMLHttpRequest();
geocode = createCORSRequest('GET', 'https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=');
geocode.onload = function() {
var geoData = JSON.parse(geocode.responseText); // parse the JSON from geocode response
var results = geoData["results"]; // create variable for results
var userLong = results["geometry"]["location"]["lng"]; // parse the latitude
var userLat = results["geometry"]["location"]["lat"]; // parse the longitude
console.log(userLong);
console.log(userLat);
}
geocode.send();
除非您调用geocode.send()
,否则该值将是未定义的,因为未触发任何请求。js中的错误是什么?告诉我们createCORSRequest()@Kushal,这意味着它无法到达未定义的几何体。您是否也可以添加geoData变量content这完全有意义。真不敢相信我竟然忘了!虽然我确实在代码末尾添加了它,但我仍然得到了一个错误,它仍然表示响应未定义谢谢。需要更改var userLong=results[“geometry”][“location”][“lng”]代码>以使其工作var userLong=results[0][“geometry”][“location”][“lng”]代码>。您需要指向“result”数组的第一个元素
var geocode = new XMLHttpRequest();
geocode = createCORSRequest('GET', 'https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=');
geocode.onload = function() {
var geoData = JSON.parse(geocode.responseText); // parse the JSON from geocode response
var results = geoData["results"]; // create variable for results
var userLong = results["geometry"]["location"]["lng"]; // parse the latitude
var userLat = results["geometry"]["location"]["lat"]; // parse the longitude
console.log(userLong);
console.log(userLat);
}
geocode.send();