简体   繁体   中英

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.

Combine the answers of Mahi and Tibrogargan, I make it works by using this

   var markers = results.map( function(b){
        return (L.marker(new L.LatLng(b.lat, b.lon), { time: b.time}))
    });

Thank you, guys

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); 

  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 } ] var a= results.map(function(b){ return [[b.lat,b.lng],{"time":b.time}]; }); console.log(a); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM