First img is the javascript code. Filling the array and then trying to load them into a map through a for loop https://i.stack.imgur.com/0L0a3.png
this is the console log output of the array... https://i.stack.imgur.com/Ghsw5.png
the markers do not get placed on the specified longitude and latitude given..
error given is: cannot read properties of undefined (reading 'latitude')
var array=[];
$.getJSON('station.json', function (json) {
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
array.push({
place: item.place,
latitude: item.latitude,
longitude: item.longitude,
});
}
}
});
for (var i = 0; i < array.length; i++) {
marker[i] = new L.marker([array[i][2]['latitude'], array[i][2]]['longitude'])
.bindPopup(array[i]['place'])
.addTo(mymap);
}
console.log(array)
[1]: https://i.stack.imgur.com/d428i.png
[2]: https://i.stack.imgur.com/Syej2.png
The problem is that $.getJSON is an asynchronous function
you need to use that as a promise or handle the map into the callback function
solution 1
var arrayPromise= $.getJSON('station.json').then (json => Object.values(json).map(item => ({
place: item.place,
latitude: item.latitude,
longitude: item.longitude,
})
)
arrayPromise.then(arr => arr.forEach(({place, latitude, longitude}) => {
marker[i] = new L.marker(latitude, longitude)
.bindPopup(place)
.addTo(mymap);
})
)
solution 2
$.getJSON('station.json', function (json) {
Object.values(json).forEach((item, i) => {
marker[i] = new L.marker([item.latitude, item.longitude])
.bindPopup(item.place)
.addTo(mymap);
})
})
Try to use '''Array.foreach''' or '''Array.map''' instead of a for loop, let see the outcome
Array.foreach((item,index)=>{
marker[i]= new L.marker([item.place, item.latitude,item.longitude])});