如何在传单上实时在每个点上用标记制作线串?

时间:2019-11-30 06:48:38

标签: javascript leaflet

我想要类似下图的内容: enter image description here 不知道在哪里定义线串。如果有人可以指导我,那就太好了。此外,我想更改线串的颜色。 这是我的代码:-

function createRealtimeLayer(url, container) {
    return L.realtime(url, {
        interval: 5 * 1000,
        getFeatureId: function(f) {
            return f.properties.id;
        },
        cache: true,
        container: container,
        onEachFeature(f, l) {
            date = f.properties.date;
            l.bindPopup(date);
            l.on("mouseover", function () {
                l.openPopup();
            });
            l.on("mouseout", function () {
                l.closePopup();
            });
        }
    });
}
    realtime1 = createRealtimeLayer('getPosition').addTo(map),
    realtime2 = createRealtimeLayer('getUserPositionHistory').addTo(map);

L.control.layers(null, {
    'Current': realtime1,
    'History': realtime2
}).addTo(map);

realtime1.once('update', function() {
    map.fitBounds(realtime1.getBounds(), {maxZoom: 18});
});

1 个答案:

答案 0 :(得分:0)

要在每个点上设置标记,请将其添加到onEachFeature中:

if(layer instanceof L.Path){      
      l.getLatLngs().forEach(function(latlng){
        L.marker(latlng).addTo(map);
      })
    }

如果您想给线着色,则必须像这样将线分开,但是不要在地图上附加geojson层:

if(layer instanceof L.Path){
      var lastlatlng = null;
      layer.getLatLngs().forEach(function(latlng, i){
        if(lastlatlng !== null){
             L.polyline([lastlatlng,latlng],{color: getColor(i)}).addTo(map);
        }
        lastlatlng = latlng;
      })
    }

更新

Asker希望从geojson中按点创建一条线。

您可以使用poly.addLatLng(latlng)

将这些点的latlng添加到折线中
var oldcolor = null;
var polys = [];

function onEachFeature(feature, layer) {
    if(feature.properties.color && oldcolor != feature.properties.color){
        oldcolor = feature.properties.color;

      var lastlatlng = [];

      //This block gets the last latlng from the line before. so you have one line.
      // If you  want to seperate the lines by color, deleted this block
      if( polys.length > 0){
        var lastpoly = polys[polys.length-1];
        if(lastpoly.getLatLngs() && lastpoly.getLatLngs().length > 0){
          var lastlatlngs = lastpoly.getLatLngs();
          lastlatlng = lastlatlngs[0][lastlatlngs[0].length-1];
        }
      }
      //End of block

      polys.push(L.polyline([lastlatlng],{color: oldcolor}).addTo(mymap));
    }

    var poly = polys[polys.length-1]; //get last line
    poly.addLatLng(layer.getLatLng());
}

https://jsfiddle.net/falkedesign/pksy6o8v/