How to intersect more than 2 polygons using Turf.js? - mapbox-gl-js

We use Mapbox GL JS 1.12.0 in our Vue.js project. I need to create intersection objects if I have 2 or more polygons. But, I'm able to do it with 2 polygons only. The code looks as following:
import * as turf from '#turf/turf';
export function createIntersection(features) {
// features = 3 polygons on the screen bellow
const intersection = turf.intersect(...features);
return intersection;
}
The screenshots:
Unselected polygons:
Selected polygons
After code execution
As you can see there is only 1 intersection object created.
How to do it with more than 2 polygons?

turf.intersect() can only intersect 2 polygons.
If you want to intersect multiple polygons you can intersect each polygon with each other polygon with turf.intersect() and then combine the results using turf.combine().
Here is some example code:
const polygonA = ...;
const polygonB = ...;
const polygonC = ...;
const allIntersections = {
type: 'FeatureCollections',
features: [
turf.intersect(polygonA, polygonB),
turf.intersect(polygonA, polygonC),
turf.intersect(polygonB, polygonC),
],
};
const combinedIntersection = turf.combine(allIntersections);

Related

H3 - How to get center lat long of a multi polygon?

I have created Multi polygons using h3SetToMultiPolygon from the list of H3 cell ids as shown below:
Now I want to get the center (I know it's not a perfect shape to get the center, but a rough one should be fine) of the Multi Polygon which I am unable to get using any H3 or leaflet methods.
I want to show a marker at the center of the boundary of the multi polygons as shown below roughly:
Any help would be appreciated.
Here is my code:
const clusterBoundaryCoordinates = [];
clusters?.forEach((element) => {
clusterBoundaryCoordinates.push(
h3.h3SetToMultiPolygon(element.cellIdsArr, true)
);
});
This isn't really specific to H3 - in general, you want an algorithm that can give you the centroid of a polygon, e.g. #turf/centroid. There are different centroid algorithms based on the use case - e.g. you may or may not require the centroid to be inside a concave polygon (think a C shape) or within one of many small polygons in a multipolygon (think an archipelago).
There's an interesting H3-based option here as well, though I don't know offhand how to make it performant. You can find the center cell by finding the cell whose mean distance to all other cells is lowest, e.g.
let min = Infinity;
let center = null;
for (const cell of cells) {
let total = 0;
for (const neighbor of cells) {
total += h3.h3Distance(cell, neighbor);
}
if (total < min) {
min = total;
center = cell;
}
}
This will always give you a cell in your set, so it will always be within your area, and should give a reasonable value even for pathological shapes. But, because the algorithm is O(n^2), it's going to be very slow for large sets of cells.
I found the solution. I didn't notice earlier that to find the center, I can utilize the lat longs which I receive when I do h3SetToMultiPolygon (it returns the lat long in reverse order).
const clusterBoundaryCoordinates = [];
clusters?.forEach((element) => {
clusterBoundaryCoordinates.push(
h3.h3SetToMultiPolygon(element.cellIdsArr, true); //it returns the latlong in reverse order, so need to reverse it
);
});
const getCentroid = (arr) => {
return arr.reduce(
(x, y) => {
return [x[0] + y[0] / arr.length, x[1] + y[1] / arr.length];
},
[0, 0]
);
};
const centroid = getCentroid(clusterBoundaryCoordinates);

Get Bounding Box used By queryRenderedFeatures

I have an application that serves vector tiles. The features in the tiles are clickable. When a user clicks the map, I pass mapbox-gl's queryRenderedFeatures a 5 x 5px bounding box around the clicked point.
Is there a way to ascertain the lat-lon bounding box that mapbox uses to query its cached tiles? I would like to have this bounding box so I can query the database for the features around the clicked point. I can use the ids of the features in the vector tiles, but this becomes cumbersome/untenable when there are 1000s of features.
Here's how I am getting features near point, where:
map is the mapbox map object
mapboxLayers are the names of the layers I want to query
point is point property of the click event
export const getMapFeaturesNearPoint = ({ map, mapboxLayers, point }) => {
const { x, y } = point;
const halfPixels = 5;
// set bbox as 5px rectangle around clicked point
const bbox = [
[x - halfPixels, y - halfPixels],
[x + halfPixels, y + halfPixels],
];
const features = map.queryRenderedFeatures(bbox, { layers: [...mapboxLayers] })
return features;
};
Note: I have tried doing the following with the bbox defined above: bbox.map(pt => map.unproject(pt)) to get the lat lon bounding box. From my examination of the mapboxgl source code, it seems the process to unproject queryRenderedFeatures coordinates is a bit more complex than that.
Not very clear to me what you are trying to get, but conceptually speaking, what any queryRenderedFeatures is doing with no filters, is basically find all the tiles in the cache (the ones cached are in the viewport), then per tile, get all the features on them, and merge them all into the result. So, if you use queryRenderedFeatures with no arguments or with only a options argument is equivalent to passing a bounding box encompassing the entire map viewport.
You can check the source code of query_features.js file in Mapbox github repo
With those features in the viewport, it would be easy to reduce them to a lnglat bounding box through a .reduce function that you can use, for instance, as a bounding box to use map.fitBounds.
var coordinates = points;
var bounds = coordinates.reduce(function(bounds, coord) {
return bounds.extend(coord);
}, new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]));
map.fitBounds(bounds, {
padding: { top: 50, bottom: 50, left: 50, right: 50 },
easing(t) {
return t * (2 - t);
}
});
But as said, not sure if that's what you are looking for.
Other option would be to use the canvas width and height and unproject them... I found this code while ago,
const canvas = map.getCanvas()
const w = canvas.width
const h = canvas.height
const cUL = map.unproject ([0,0]).toArray()
const cUR = map.unproject ([w,0]).toArray()
const cLR = map.unproject ([w,h]).toArray()
const cLL = map.unproject ([0,h]).toArray()
const coordinates = [cUL,cUR,cLR,cLL,cUL]

Mapbox Overlapping Circles

Does anyone know a way to make overlapping circles in mapbox show the same color and only have the border around the outer edge display?
I have this:
And I made this in photoshop for what I want:
While I don't think there is a way to style all the circles to show their group outline, you can achieve the effect you want by creating a union of all the circle geometries and applying your style to that. Unfortunately, Leaflet's L.circle class offers no way to access a circle's geometry beyond the center point, and to perform a union, you need the path of the circle itself. Fortunately, there is Leaflet Geodesy and its LGeo.circle class, which produces circular polygons with a given radius and number of segments. Once you have these polygon representations of your circles, you can use turf.union to produce the outline you want.
Say you are starting with a layer of points called pointLayer (this can be a L.geoJson, L.mapbox.featureLayer, or any other class that inherits the .eachLayer method). You can then iterate over the features, creating a circular polygon for each of them and adding it to a temporary layer group, like this:
var circleLayer = L.layerGroup();
var radius = 5000
var opts = {
parts: 144
};
pointLayer.eachLayer(function(layer) {
LGeo.circle(layer.getLatLng(), radius, opts).addTo(circleLayer);
});
where radius is in meters and the parts option is the number of segments you want your polygons to have. Next, use the .getLayers method to get an array of all the layers in the temporary group, then iterate over that to create a union of all the features:
var circleUnion = unify(circleLayer.getLayers()).addTo(map);
function unify(polyList) {
for (var i = 0; i < polyList.length; ++i) {
if (i == 0) {
var unionTemp = polyList[i].toGeoJSON();
} else {
unionTemp = turf.union(unionTemp, polyList[i].toGeoJSON());
}
}
return L.geoJson(unionTemp, {style: unionStyle});
}
where unionStyle is whatever style you want to apply to your newly-combined circles. Here is an example fiddle showing all this with some random data:
http://fiddle.jshell.net/nathansnider/L2d626hn/

How to get intersection area coordinates of two polygons on General Polygon Clipper(GPC)?

I'm using nutiteq library to draw polygons and getting the coordinates of the polygons with .getVertexList() command. Then I cast these coordinates to an array list . Then I cast these coordinates to another polygon list. GPC is calculating the intersection, union, XOR and difference areas integer values. Then I need to highlight the process area so I need processed areas coordinates but I can't get these coordinates directly from GPC.
The code I'm using for the area calculation is below. What should I do to get the coordinates of result polygon?. (I can't cast the coordinates directly by the way as you can see here...)
Thanks in advance.
public void IntersectionButton(View view) {
VectorElement selectedElement = mapView.getSelectedElement();
List<?> VisibleElements = selectedElement.getLayer().getVisibleElements();
ArrayList<Poly> polyList = new ArrayList<Poly>();
for (Object obj : VisibleElements) {
if (obj instanceof Polygon) {
Polygon poly = (Polygon) obj;
List<MapPos> geoList = poly.getVertexList();
Poly p = new PolyDefault();
for (MapPos pos : geoList) {
p.add(pos.x, pos.y);
}
polyList.add(p);
}
}
PolyDefault result = (PolyDefault) Clip.intersection(polyList.get(0), polyList.get(1));
int area = (int) (((int) result.getArea()) * (0.57417));
The result polygon seems to have all the methods you need:
getNumPoints() to get number of outer polygon points.
getX(i) to get X of specific outer polygon point, and getY(i) for Y.
getNumInnerPoly() to get number of holes in the polygon
getInnerPoly(i) to get specific hole. You iterate through hole similar way like outer polygon
You can construct new Nutiteq Polygon from this data, create list of MapPos for outer and list of list of MapPos for inner polygons (holes). What are values of X and Y, do they need further processing, is another question what you can investigate.

How can I draw a polygon on intersection coordinates on Nutiteq?

Hey people this is going to be my first question so dont hit me too hard !
Before I have already added polygons but the intersection is a bit complicating.
with pre-defined i mean for example intersection coordinates of two other polygons. I'm calculating the area of the polygon intersection but i also want to highlight the area. Thanks
You would need two steps:
calculate intersection: polygon from 2 polygons. I would use JTS for it, you would need to provide data in JTS objects.
highlight the intersection on mapview (nutiteq for example). You can just add the resulting polygon as one geometry element into geometry layer, just as any other polygon. Use special styling to make it look different. You would need to convert JTS polygon to Nutiteq Polygon object to show it on map
ArrayList<MapPos> keslist = new ArrayList<MapPos>();
for (int i = 0; i < sonuc.getNumPoints(); i++) {
double lon = sonuc.getX(i);
double lat = sonuc.getY(i);
MapPos mPos = new MapPos(lon, lat);
keslist.add(mPos);
}
PolygonStyle polygonStyle = PolygonStyle.builder().setColor(Color.GREEN).build();
StyleSet<PolygonStyle> polygonStyleSet = new StyleSet<PolygonStyle>(null);
polygonStyleSet.setZoomStyle(10, polygonStyle);
Polygon KesisimPol = new Polygon(keslist, new DefaultLabel("Kesişim"), polygonStyleSet, null);
GeometryLayer geomLayer = new GeometryLayer(mapView.getLayers().getBaseLayer().getProjection());
mapView.getLayers().addLayer(geomLayer);
geomLayer.add(KesisimPol);
}
Here is my solution. I've tried it works. Right now I'm trying to add this new polygon to editable objects layer. Because I can't use the result polygon in another intersection process.
I hope this will help the others.