我有一个使用来自数据库的数据构建的地图标记数组,该数组构建完美,但是当我尝试循环遍历数组对象时,尽管标记确实出现,并且正确的数字,内容位于信息窗口是相同的,并且我设置为输出的ID也是相同的,它似乎总是转到最后一个对象并将该数据用于每个标记。
有人可能会指出我可能做错了吗?
以下脚本完整是在数据库成功获取信息时调用的函数。因此,整个块专门用于显示从数据库中检索的标记及其相关信息。
function querySuccessMarkers(t, results) {
var markersArray = {};
var len = results.rows.length;
console.log("Markers table: " + len + " rows found");
for( var i = 0, c = results.rows.length; i < c; i++ ) {
markersArray[results.rows.item(i).markerid] = {
id: results.rows.item(i).markerid,
title: results.rows.item(i).title,
info: results.rows.item(i).info,
lat: results.rows.item(i).markerLat,
lng: results.rows.item(i).markerLng
};
}
console.log(markersArray);
var markerDetails;
for (id in markersArray) {
if( markersArray.hasOwnProperty(id) ) {
markerDetails = markersArray[id];
var bridgeIcon = new google.maps.MarkerImage("img/map_markers/warning_map_marker.png", null, null, null);
marker = new google.maps.Marker({
position: new google.maps.LatLng(markerDetails.lat, markerDetails.lng),
map: map,
icon: bridgeIcon
});
var info_window = new google.maps.InfoWindow({content: ''});
info_window.content = '<div id="marker-info-win" data-id="'+markerDetails.id+'">' +
'<h3>Marker Information</h3>' +
'<input id="warning-title" data-text="Warning Title" />'+
'<p>'+markerDetails.title+'</p>'+
'<i class="fa fa-pencil"></i>' +
'<input id="warning-additional-info" data-text="Warning Additional Information" value="'+markerDetails.info+'"/>'+
'<i class="fa fa-pencil"></i>';
google.maps.event.addListener(marker, 'click', function() {
info_window.open(map, this);
});
console.log(markerDetails);
}
}
}
答案 0 :(得分:0)
感兴趣的任何人的固定代码:
function querySuccessMarkers(t, results) {
var markersArray = [];
var len = results.rows.length;
console.log("Markers table: " + len + " rows found");
for( var i = 0, c = results.rows.length; i < c; i++) {
markersArray.push(results.rows.item(i));
}
console.log(markersArray);
var info_window = new google.maps.InfoWindow();
for (i = 0; i < markersArray.length; i++) {
var bridgeIcon = new google.maps.MarkerImage("img/map_markers/warning_map_marker.png", null, null, null);
marker = new google.maps.Marker({
position: new google.maps.LatLng(markersArray[i].markerLat, markersArray[i].markerLng),
map: map,
icon: bridgeIcon
});
console.log(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
info_window.setContent('<div id="marker-info-win" data-id="'+markersArray[i].markerid+'">' +
'<h3>Marker Information</h3>' +
'<input id="warning-title" data-text="Warning Title" />'+
'<p>'+markersArray[i].title+'</p>'+
'<i class="fa fa-pencil"></i>' +
'<input id="warning-additional-info" data-text="Warning Additional Information" value="'+markersArray[i].info+'"/>'+
'<i class="fa fa-pencil"></i>');
info_window.open(map, marker);
}
})(marker, i));
}
}
这是将WebSQL数据库输出到普通数组而不是我自己的数组对象的结果。另外,在每个标记的click事件监听器中添加闭包。
有关如何使用硬编码数组或动态实现相同功能的更深入的教程和指南:http://chrisltd.com/blog/2013/08/google-map-random-color-pins/