Search code examples
leafletgeojsonturfjs

TurfJS get bbox given two Points


I'm trying to move a client side method on the backend:

The client side method is using TurfJS and Leaflet to perform some operations. The only problem is that server side (nodejs) window is not available, hence I cannot use Leaflet.

I'm looking for a way to transform this piece of code in the vanilla Turf equivalent:

    const pointA = turf.point([originCoords.lng, originCoords.lat]);
    const pointB = turf.destination.default(pointA, 50, 45, { units: 'kilometers' });

    // here I'm using leaflet to get a BBox
    const latLngBounds = L.latLngBounds(
        L.latLng(pointA.geometry.coordinates[1],
            pointA.geometry.coordinates[0]),
        L.latLng(pointB.geometry.coordinates[1], pointB.geometry.coordinates[0]),
    );

    // using that BBox I then create the rectangle, again with leaflet
    tile = L.rectangle(latLngBounds);

I'm still newbie with this whole GeoJSON thing, and maybe I'm missing something, can someone help me?


Solution

  • Here is the code that uses Turf.JS only.

    var turf = require('@turf/turf');
    var pointA = turf.point([-75.343, 39.984]);
    var pointB = turf.destination(pointA, 50, 45, { units: 'kilometers' });
    //create a bbox that extends to include all the features
    var bbx = turf.bbox(turf.featureCollection([pointA, pointB]));
    var pgn = turf.bboxPolygon(bbx);  //convert it to Polygon feature
    console.log(JSON.stringify(pgn)); //output to console
    

    The output:

    {"type":"Feature","properties":{},
        "geometry":{
        "type":"Polygon",
        "coordinates":[[
            [-75.343,39.984],
            [-74.92609,39.984],
            [-74.92609,40.3012],
            [-75.343,40.3012],
            [-75.343,39.984]]]
        }
    }
    

    Edit 1

    Add ability to run the code:

    //var turf = require('@turf/turf');
    var pointA = turf.point([-75.343, 39.984]);
    var pointB = turf.destination(pointA, 50, 45, { units: 'kilometers' });
    //create a bbox that extends to include all the features
    var bbx = turf.bbox(turf.featureCollection([pointA, pointB]));
    var pgn = turf.bboxPolygon(bbx);  //convert it to Polygon feature
    console.log(JSON.stringify(pgn)); //output to console
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Turf.js/5.1.5/turf.min.js"></script>