const proj4 = require('proj4');
const turf = require('@turf/turf');
// from https://epsg.io/3857
const PSEUDO_MERC_DATUM = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs";
// from https://epsg.io/4326
const WGS84_DATUM = "+proj=longlat +datum=WGS84 +no_defs";
const xyCoordsToLatLong = (xy_pair) => {
return proj4(PSEUDO_MERC_DATUM, WGS84_DATUM, xy_pair);
}
const latLongCoordsToXY = (latlong_pair) => {
return proj4(WGS84_DATUM, PSEUDO_MERC_DATUM, latlong_pair);
}
const xyToLatLonBBOX = (xy_bbox, return_as_poly = false) => {
const bbox_poly = turf.bboxPolygon(xy_bbox);
bbox_poly.geometry.coordinates = [bbox_poly.geometry.coordinates[0].map(pair => xyCoordsToLatLong(pair))];
return return_as_poly ? bbox_poly : turf.bbox(bbox_poly);
}
const latLongToXYbbox = (latlon_bbox, return_as_poly = false) => {
const bbox_poly = turf.bboxPolygon(latlon_bbox);
bbox_poly.geometry.coordinates = [bbox_poly.geometry.coordinates[0].map(pair => latLongCoordsToXY(pair))];
return return_as_poly ? bbox_poly : turf.bbox(bbox_poly);
}
console.info('validate', xyToLatLonBBOX(latLongToXYbbox([-82, 35, -74, 42])));
console.info('visualize geojson', xyToLatLonBBOX(latLongToXYbbox([-82, 35, -74, 42]), true));