【发布时间】:2023-04-02 13:25:01
【问题描述】:
我正在尝试在网站中加载带有标记的地图。当我从函数外部的 js 调用 servlet 时,我得到了值(显示标记的坐标),但是当我将调用 servlet 的代码放在函数中然后创建地图时,我只看到一个没有地方的空白地图或标记。我说这是一个空白地图,因为我可以看到鼠标指针像手掌(就像在谷歌地图中一样)。
因此,地图加载,但调用 servlet 并获取坐标的函数的调用未完成。当我在没有函数的情况下将代码放在外面调用 servlet 时,它可以工作。我使用console.log() 显示来自servlet 的值数组。我只看到[]。
也许xhr.open() 没有被调用。同上。我只在 JavaScript 中工作了几天。我真的不知道它是如何工作的。请帮忙。
function initMap() {
xhr = new XMLHttpRequest();
getLocation(xhr); // calling the function that gets location from servlet
//setTimeout(function(){
var bounds = new google.maps.LatLngBounds();
var mapDiv = document.getElementById('map');
map = new google.maps.Map(mapDiv);
map.setCenter(new google.maps.LatLng(latArray[0], lngArray[0]));
map.setZoom(18);
console.log(deviceId);
console.log(latArray);
latArray.forEach(function(lat, i) {
// For each one create info window
var infoWindow = new google.maps.InfoWindow({
content: '<div id="content>' + '<p style="color:#000000">DeviceID:<p>' + '<p>' + deviceId[i] + '</p>' + '</div>'
});
marker = new google.maps.Marker({
map: map,
mapTypeId: google.maps.MapTypeId.ROADMAP,
position: new google.maps.LatLng(latArray[i], lngArray[i]),
icon: "phone6.png"
});
//marker.setPosition(new google.maps.LatLng(latArray[0],lngArray[0]));
marker.addListener("click", function() {
//infoWindow.open(map, marker);
//marker.setMap(null);
placeMarker(this.map,this.marker,latArray[i],lngArray[i]);
});
});
// },10000);
}
function open(){
xhr.open('POST', 'GetLocationFromDB', true);
xhr.send();
}
//map.fitBounds(bounds);
function getLocation(xhr) //function that gets coordinates in array from servlet
{
xhr.onreadystatechange = function() { //when I put this code above where I created the map, it works
if (xhr.readyState == 4) {
data = JSON.parse(xhr.responseText);
for (i = 0; i < data.length; i++) {
if (!((i + 1) % 3 == 0)) {
latArray.push(data[i]);
lngArray.push(data[i + 1]);
i = i + 2;
deviceId.push(data[deviceIdLoopCount]);
deviceIdLoopCount += 3;
}
}
}
}
}
编辑:
我刚刚读到你不能调用函数xhr.onreadystatechange,它只是参考。我尝试执行onreadystatechange(),但没有奏效。我将xhr.onreadystatechange 传递给我调用该函数的变量。如何执行?
【问题讨论】:
-
如果你能告诉我投反对票的原因,我将不胜感激
标签: javascript ajax google-maps google-maps-api-3