Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show multiple great circles on mapbox with turf.js

I am trying to add multiple great circle lines between the markers in the same map container. I managed to show one with greatCircle in turf.js.

for(var i = 0; i < 2 ;i++) {

    var getStart = json.features[0].geometry.coordinates[0];
    var getEnd = json.features[0].geometry.coordinates[1];

    //console.log(getStart) 
    //console.log(getEnd)

    var start = turf.point(getStart);
    var end = turf.point(getEnd);

    var data = turf.greatCircle(start, end);

    console.log(data) 
}

Is it possible to list all of them and applying Turf.js?

Here is my JsFiddle.

like image 714
MDB Avatar asked Oct 18 '25 02:10

MDB


1 Answers

Give map.addSource a new FeatureCollection where the features are the great circles from the turf function. There is a helper function in turf for that.

I've included the logic of your loop in a function that returns a FeatureCollection of great circles:

function getGreatArcFc() {
  var data = [];
  for (var i = 0; i < json.features.length; i++) {
    var feature = json.features[i];
    var getStart = feature.geometry.coordinates[0];
    var getEnd = feature.geometry.coordinates[1];
    var start = turf.point(getStart);
    var end = turf.point(getEnd);
    data.push(turf.greatCircle(start, end));
  }
  return turf.featureCollection(data);
}

map.on('load', function() {
    map.addSource('route', {
        "type": "geojson",
        "data": getGreatArcFc()
    });
  map.addLayer({
    "id": "route",
    "source": "route",
    "type": "line",
    "paint": {
      "line-width": 1,
      "line-color": "#000000"
    }
  });
});

Updating your fiddle with that logic gives:

enter image description here

It's a bit hard to make out in the screenshot, but there are separate great circles between what I see as London to NY and London to Boston maybe ?

like image 53
Robin Mackenzie Avatar answered Oct 19 '25 18:10

Robin Mackenzie