Leaflet with markers and line

2020-07-18 23:17发布

问题:

I'm using leafletjs with geojson, but i can't draw a polyline with the markers at the same time, so my solution is draw first a polyline then add the markers. I don't think it's a good ways, so is there any other solution?

there is my code

function DrawLine(mymap,topo){

var line={
     "type": "Feature",
     "geometry": {
         "type": "LineString",
         "coordinates" : topo.pointsForJson 
         // topo.pointsForJson is my data source like : [[5.58611,43.296665], [5.614466,43.190604], [5.565922,43.254726], [5.376992,43.302967]]
     },
     "properties": {
         "ID": topo['OMS_IDTOPO'],
         "color" : "blue"
     }
 };

var points=[];
for(var i in topo.pointsForJson){
    var point = {
        "type": "Feature",
        "geometry": {
            "type": "Point",
            "coordinates" : topo.pointsForJson[i]
        }

    };
    points.push(point);
}
//add markers
L.geoJSON(points).addTo(mymap);
// add polyline
 var polyline = L.geoJSON(line,{
     style:function (feature) {
         return {color: feature.properties.color}
     }
 }).bindPopup(function (layer) {
     return layer.feature.properties.ID;
 }).addTo(mymap);

 mymap.fitBounds(polyline.getBounds());
}

Thanks a lot

回答1:

You really do not need to build a GeoJSON object first at runtime in order to display something on your Leaflet map.

Simply loop through your coordinates and build a marker at each pair.

Then build a polyline out of the coordinates array.

You will need to revert your coordinates in the process, since they are recorded as Longitude / Latitude (compliant with GeoJSON format), whereas Leaflet expects Latitude / Longitude when directly building Markers and Polylines (instead of using L.geoJSON factory).

var pointsForJson = [
  [5.58611, 43.296665],
  [5.614466, 43.190604],
  [5.565922, 43.254726],
  [5.376992, 43.302967]
];

var map = L.map('map');

pointsForJson.forEach(function(lngLat) {
  L.marker(lngLatToLatLng(lngLat)).addTo(map);
});

var polyline = L.polyline(lngLatArrayToLatLng(pointsForJson)).addTo(map);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

map.fitBounds(polyline.getBounds());

function lngLatArrayToLatLng(lngLatArray) {
  return lngLatArray.map(lngLatToLatLng);
}

function lngLatToLatLng(lngLat) {
  return [lngLat[1], lngLat[0]];
}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css">
<script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet-src.js"></script>

<div id="map" style="height: 200px"></div>



标签: leaflet