LeafLet:将数组对象添加到滑块中

时间:2016-11-08 19:13:02

标签: javascript leaflet

如果我有一个从JSON解析的对象数组,例如:

 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 marker = L.marker([50.64470631082, 13.9902814650912], {time: 1478542485});

这是我到目前为止所做的事情

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

我有LatLng权利,但时机不对。我正在尝试使用Leaflet Slider并将数据显示在地图上。

3 个答案:

答案 0 :(得分:1)

结合Mahi和Tibrogargan的答案,我使用此

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

谢谢你们,伙计们

答案 1 :(得分:0)

这是对Array.prototype.map的直接使用。使用函数(在本例中为箭头函数)调用.map(),该函数生成基于现有元素(传递给函数的参数)的新元素。 map的返回值是一个包含新元素的新数组。

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

答案 2 :(得分:0)

&#13;
&#13;
 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);
&#13;
&#13;
&#13;