Javascript 谷歌地图地理代码-处理异步调用
我有密码:Javascript 谷歌地图地理代码-处理异步调用,javascript,html,google-maps,google-geocoder,geocode,Javascript,Html,Google Maps,Google Geocoder,Geocode,我有密码: function mapNextAddress() { var xhr, i, text, lines, address; if(window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari xhr = new XMLHttpRequest(); } else { // IE5, IE6 - next line su
function mapNextAddress() {
var xhr, i, text, lines, address;
if(window.XMLHttpRequest)
{
// IE7+, Firefox, Chrome, Opera, Safari
xhr = new XMLHttpRequest();
}
else
{
// IE5, IE6 - next line supports these dinosaurs
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
text = xhr.responseText;
lines = text.split("\n");
address = lines[numberAddress];
numberAddress = numberAddress + 1;
}
}
xhr.open("GET","OFCaddresses.txt",true);
xhr.send();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
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);
}
});
}
我有一个按钮,调用这个,我试图更新地图每次按钮被点击到文本文件中的下一个地址。我有一些问题,因为它是异步的,并且不一定按这种顺序运行。我一直在想办法解决这个问题,有什么想法吗?为什么不在
xhr.onreadystatechange
事件中调用geocode
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
text = xhr.responseText;
lines = text.split("\n");
address = lines[numberAddress];
numberAddress = numberAddress + 1;
doGeocode();
}
}
并且doGeocode函数的逻辑没有修改
function doGeocode() {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
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);
}
});
PS:如果可行的话,我真的建议你用jQuery做Ajax的工作。大多数时候,重新发明轮子并不好