我正在尝试创建一个Leaflet标记的JS数组,但它一直告诉我Markers []数组的属性'0'是未定义的,我认为这是由于将PHP变量$ data传递到JS var a []通过json_encode,但是我不确定。
我正在研究Altervista,我试图以各种可能的方式解决问题。
$sql = mysqli_query($connection, "SELECT * FROM ritrovamento");
while($row = mysqli_fetch_row($sql))
{
$data[] = $row;
}
var a = <?php echo json_encode($data); ?>;
var Markers = [];
var Popups = [];
var j = 0;
var i = 0;
for(i = 0; i < a.length; i = i + 3) {
Markers[i] = L.marker([a[j][0], a[j][1]], {icon: shovelIcon});
Markers[i + 1] = L.marker([a[j][0], a[j][1]], {icon: diggingIcon});
Markers[i + 2] = L.marker([a[j][0], a[j][1]], {icon: clickedIcon});
Markers[i].addTo(mymap);
j++;
}
未捕获的TypeError:无法读取未定义的属性“ 0”(此错误来自我试图将数据放入Markers [i]的位置。)
console.log(a)给我:
[Array(5)]
0: Array(5)
0: "45.255091"
1: "8.514025"
2: "/images/bo.gif"
3: "wdqd"
4: "wd"
和console.log(Markers [1])给我:
e {options: {…}, _latlng: M, _initHooksCalled: true}
options:
icon: e
options: {iconUrl: "images/digging.gif", iconSize: Array(2), iconAnchor: Array(2), popupAnchor: Array(2)}
_initHooksCalled: true
__proto__: v
__proto__: Object
_initHooksCalled: true
_latlng: M
lat: 45.255091
lng: 8.514025
__proto__: Object
__proto__: e
标记[0]和标记[2]相同。
答案 0 :(得分:0)
由于没有递增i
,因此存在无限循环。在第二次迭代中,由于没有j[1]
,因此会出现错误。
for
循环需要增加两个变量,并且应该测试j
,因为它是您正在读取的数组的索引。
for (i = 0, j = 0; j < a.length; j++, i += 3) {
Markers[i] = L.marker([a[j][0], a[j][1]], {icon: shovelIcon});
Markers[i + 1] = L.marker([a[j][0], a[j][1]], {icon: diggingIcon});
Markers[i + 2] = L.marker([a[j][0], a[j][1]], {icon: clickedIcon});
Markers[i].addTo(mymap);
}
完整的代码。我调整了Markers
数组的内容,因为我没有L.marker()
函数,但是它仍然以相同的方式访问a
数组。
var a = [
["45.255091", "8.514025", "/images/bo.gif", "wdgd", "wd"]
];
var Markers = [];
var j, i;
var mymap = [];
for (i = 0, j = 0; j < a.length; j++, i += 3) {
Markers[i] = [[a[j][0], a[j][1]], {icon: "shovelIcon"}];
Markers[i + 1] = [[a[j][0], a[j][1]], {icon: "diggingIcon"}];
Markers[i + 2] = [[a[j][0], a[j][1]], {icon: "clickedIcon"}];
mymap.push(Markers[i]);
}
console.log(Markers);