I'm trying to create a JS array of Leaflet markers, but it keeps telling me that the property '0' of the Markers[] array is undefined, i think it's a problem derivated from transfering the PHP variable $data to JS var a[] via json_encode, but i'm not sure about that.
I'm working on Altervista, i tried to solve the problem in every way possible.
$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++;
}
Uncaught TypeError: Cannot read property '0' of undefined (this error comes where i'm trying to put data into Markers[i]).
console.log(a) give me:
[Array(5)]
0: Array(5)
0: "45.255091"
1: "8.514025"
2: "/images/bo.gif"
3: "wdqd"
4: "wd"
and console.log(Markers[1]) gives me:
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
Same for Markers[0] and Markers[2].
i + 3supposed to do in theforloop? Shouldn't that bei = i + 3? - Barmariis the index intoMarkers, not the index intoa, so why are you comparing it toa.length? - Barmarjis the index intoa, so you should compare that witha.length. - Barmar