Tenz Tenz - 26 days ago 10
Javascript Question

LeafLet: add array object into slider

If I have an Array of Objects that were parsed from JSON such as:

var results = [
{
"time": 1478542485,
"lat": 50.64470631082,
"lng": 13.9902814650912
},
{
"time": 1479542485,
"lat": 50.64570631082,
"lng": 13.9902814650912
},
{
"time": 1578542485,
"lat": 50.64473631082,
"lng": 13.9902814650912
}
}
]


How can I push them into array so that each array object will look like:

var marker = L.marker([50.64470631082, 13.9902814650912], {time: 1478542485});


This is what I have done so far

var markers = [];
for (var i = 0; i < results.length; i++){
var latln = new L.LatLng(results[i].lat, results[i].lng);
var time = results[i].time;
var t = '{time: ' + time + '}';
var mark = L.marker(latln, t.replace("\'",""));
markers.push(mark);
}


I have the LatLng right, but the time doesn't come out right. I am trying to use the Leaflet Slider and display data onto map.

Answer

This is a pretty straight forward use of Array.prototype.map. .map() is called with a function (in this case an arrow function) that produces a new element that is based on the existing element (the argument passed to the function). The return value from map is a new Array containing the new elements.

// ------------------8<----------------------
// LeafletStub is just here to provide mock ups of the functions called in the `L` object 
function LeafletStub() {
}
LeafletStub.prototype.LatLng = function(lat, lng) {
  return `lat: ${lat}, lng: ${lng}`; }
LeafletStub.prototype.marker = function(latlng, time) {
  return `latlng: {${latlng}}, time: ${time.time}`; }
var L = new LeafletStub();
// ------------------8<----------------------

var inputObj = [{
  "time": 1478542485,
  "lat": 50.64470631082,
  "lng": 13.9902814650912
}, {
  "time": 1479542485,
  "lat": 50.64570631082,
  "lng": 13.9902814650912
}, {
  "time": 1578542485,
  "lat": 50.64473631082,
  "lng": 13.9902814650912
}]

// answer really starts here.
var markers = inputObj.map( element => L.marker(L.LatLng(element.lat, element.lng), { time: element.time } ) );

console.log(markers);

Comments