Search code examples
mapsleafletmapboxgeojsonturfjs

Leaflet: How to use `getLatLngs` on a geoJSON polyline?


I create a geoJSON polyline object called bezier using turf.js like this:

var linestring = turf.linestring(
        [[121.465, 31.233], [121.500634, 31.233499], [121.588107, 31.190172], [121.501545, 31.207394], [121.337514, 31.196079]]
        , {
            "stroke": "#25561F",
            "stroke-width": 5
        });

var bezier = turf.bezier(linestring, 50000, 0.85);

bezier.properties = {
    "stroke": "#6BC65F",
    "stroke-width": 5,
    "description": "Bezier line from polyline"
}

L.mapbox.featureLayer().setGeoJSON(bezier).addTo(map);

Then, I used bezier.geometry.coordinates to access its point array.. But what I really need is the array of LatLng object (because the L.animatedMarker in this plugin needs latlngs), I was wondering whether there is a way to extract the LatLng array like what getLatLngs method did on leaflet object.


Solution

  • You'll first need to get a reference to the actual layer from the layer you've added it to, in this instance that would be your L.mapbox.featureLayer. Once you've got that, you can just use the getLatLngs method. You can do this in multiple ways:

    Use the layeradd event, the cleanest way:

    var featureLayer = L.mapbox.featureLayer().addTo(map);
    
    featureLayer.on('layeradd', function (e) {
        var latLngs = e.layer.getLatLngs();
    })
    
    var featureLayer = L.mapbox.featureLayer().setGeoJSON(bezier).addTo(map);
    

    If you're only going to insert one layer like you're doing now you could also fetch it directly from the layers object contained in the featurelayer:

    var key = Object.keys(featureLayer._layers)[0];
    var latLngs = featureLayer._layers[key].getLatLngs();
    

    Or if you've got multiple layers in your featureLayer and don't want to use events you can loop over the featureLayer and grab it from there:

    featureLayer.eachLayer(function (layer) {
        var latLngs = layer.getLatLngs();
    });