我正在尝试引用我创建的标记数组但是当我尝试引用数组元素时,元素接收消息GLOBAL_MARK.0为null或不是对象。我认为这可能是一个范围问题,但我不知道如何处理它。这是代码。
var GLOBAL_MARK = "[]"
var vcount = 0;
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
MyLat = "47.614495"
MyLng = "-122.341861"
map.setCenter(new GLatLng(MyLat, MyLng), 13);
GDownloadUrl("allmarkers.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var id = markers[i].getAttribute("id");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers [i].getAttribute("lng")));
var marker = createMarker(point, name, address, type, id);
MyAddMarker(marker)
map.addOverlay(marker);
}
});
OutTest()
}
}
function MyAddMarker(marker) {
GLOBAL_MARK[vcount] = marker
vcount = vcount + 1
}
function OutTest() {
alert(GLOBAL_MARK[0].getLatLng)
}
function createMarker(point, name, address, type, id, date1, date2) {
var marker = new GMarker(point, customIcons[type]);
var html = "<b>" + name + "</b> <br/>" + address + "<br><br><input type=\"button\" value=\" View Posts \" onclick=\"view_posts('" + id + "','" + type + "','" + date1 + "','" + date2 + "','no')\">"
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
答案 0 :(得分:0)
此代码中有很多错误。 GLOBAL_MARK
肯定被宣称错误,被用作MyAddMarker()
中使用它的对象。我会尝试尽可能多地修复,但实际上无法运行代码:
GLOBAL_MARK = [];
GDownloadUrl("allmarkers.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var id = markers[i].getAttribute("id");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new GLatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng"))
);
var marker = createMarker(point, name, address, type, id);
MyAddMarker(marker);
map.addOverlay(marker);
}
// when the code gets here, the data from allmarkers.php is done
});
OutTest();
function MyAddMarker(marker) {
GLOBAL_MARK[vcount] = marker;
vcount = vcount + 1;
}
function OutTest() {
alert(GLOBAL_MARK[0].getLatLng);
}
另外,我没有在任何地方看到vcount的声明。
而且,我怀疑你在OutTest()
中的匿名函数完成之前正在调用GDownloadUrl
。当你调用OutTest()
时,这很可能是一个尚未完成的异步函数。