Javascript 如何使用geocoder类通过ajax检索纬度和经度
包含地址列表的json数组 [ { id:0, 标题:Prassi e Ricerca Onlus社会合作社, 纬度:0, 经度:0,, 地址:伊利诺伊州罗马市12号埃莱诺拉阿博雷亚别墅 }, { id:0, 标题:圣洛伦佐, 纬度:0, 经度:0,, 地址:路易斯安那州罗马市维拉广场330号 }, { id:0, 标题:贾第内蒂, 纬度:0, 经度:0,, 地址:意大利罗马Molfetta大街45号 }, { id:0, 标题:蒙特萨克罗, 纬度:0, 经度:0,, 地址:意大利罗马的维亚勒·帕里奥利 }, { id:0, 标题:卡萨, 纬度:0, 经度:0,, 地址:意大利罗马维斯科维奥广场 } ] 由于它的复杂性,您的CodeAddressJavaScript函数对于外部调用程序myLoop不可见,因为它包含在myFunction中,因此您得到的codeAddress没有定义 试着像我没有测试过的那样重写你的代码,所以它可能无法立即工作,但你明白了:Javascript 如何使用geocoder类通过ajax检索纬度和经度,javascript,ajax,google-maps,Javascript,Ajax,Google Maps,包含地址列表的json数组 [ { id:0, 标题:Prassi e Ricerca Onlus社会合作社, 纬度:0, 经度:0,, 地址:伊利诺伊州罗马市12号埃莱诺拉阿博雷亚别墅 }, { id:0, 标题:圣洛伦佐, 纬度:0, 经度:0,, 地址:路易斯安那州罗马市维拉广场330号 }, { id:0, 标题:贾第内蒂, 纬度:0, 经度:0,, 地址:意大利罗马Molfetta大街45号 }, { id:0, 标题:蒙特萨克罗, 纬度:0, 经度:0,, 地址:意大利罗马的维亚勒
var geocoder;
var map;
var arr = [];
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(41.90832, 12.52407);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyD3Xz7-z7U_XzZiaOlx9khhtFSld8vd0k4' +
'&signed_in=true&callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
var xmlhttp = new XMLHttpRequest();
var url = "json/array.json";
var arr;
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
arr = JSON.parse(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function codeAddress(x) {
var address = arr[x].address;
console.log(arr[x].address);
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
arr[x].latitude = results[0].geometry.location.A;
console.log(arr[x].latitude);
arr[x].longitude = results[0].geometry.location.F;
console.log(arr[x].longitude);
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function myLoop() {
for (i = 0; i < arr.length; i++) {
codeAddress(i);
console.log(arr[i].address);
}
}
这是可行的,问题是要去掉muFunction