

Removing intersection of GeoJSON Multipolygons with Mapbox and Turf.js
source link: https://isaacjordan.me/blog/2016/01/remove-intersection-of-multipolygons/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Turf.js provides a lot of geospatial functions that use GeoJSON (a standard format for geographical data in JavaScript Object Notation) that allow you to easily manipulate GIS data. In this post, I’ll show you how to use Turf.js functions to remove the overlap of multiple multipolygons so that you’re left with one multipolygon that doesn’t overlap any others.
I begin by assuming you’ve got a Mapbox MultiPolygon that you’re interested in, and an array of other MultiPolygons you want to “subtract”.
We’re going to use turf.erase (or turf.difference in an upcoming release) to subtract individual polygons. To do this, we need find all the polygons in each multipolygon (of our list of multipolygons we want to subtract) that touch any polygon in our main multipolygon. We can use turf.intersect for this, and check that the function returns something non-null.
Let’s assume that 'featureGroup' is your Mapbox FeatureGroup object (a FeatureGroup containing only MultiPolygons in this case), and 'target' is the MultiPolygon you want to “shrink”.
We want to extract an array of all the polygons inside 'featureGroup' that aren’t a part of 'target'. The following code snippet generates this array, labelled 'everyOtherPolygon'.
var everyOtherPolygon = [];
featureGroup.eachLayer(function(l) {
if (l._leaflet_id !== target._leaflet_id) {
var geojson = l.toGeoJSON();
// For each polygon in this multipolygon layer
for (var i=0; i<geojson.geometry.coordinates.length; i++) {
var feat={'type':'Polygon','coordinates':geojson.geometry.coordinates[i]};
everyOtherPolygon.push(feat);
}
}
});
Now, we need an array of all the polygons inside 'target' that we want to change. The following code snippet creates this array, labelled 'thisPolygons'.
var thisPolygons = [];
var geojson = target.toGeoJSON();
for (var i=0; i<geojson.geometry.coordinates.length; i++) {
var feat={'type':'Polygon','coordinates':geojson.geometry.coordinates[i]};
thisPolygons.push(feat);
}
The main part of this algorithm is contained in the next JavaScript snippet. First, we check that we need to execute this section of the algorithm (i.e. that both 'everyOtherPolygon' and 'thisPolygons' are both non-empty). Next, we iterate through every element of 'thisPolygons' for each element of 'everyOtherPolygon'. If there is a polygon in 'thisPolygons' that intersects our current polygon, then we need to use 'turf.erase' to calculate what needs to be removed. We then combine all the polygons in 'target' back together, and save it back to our Mapbox 'target' object.
var changedAnything = false;
if (everyOtherPolygon.length > 0 && thisPolygons.length > 0) {
for (var i=0; i<everyOtherPolygon.length; i++) {
var currentPolygon = everyOtherPolygon[i];
for (var j=0; j<thisPolygons.length; j++) {
if (turf.intersect(currentPolygon, thisPolygons[j])) {
var eraseResult = turf.erase(thisPolygons[j], currentPolygon);
thisPolygons[j] = eraseResult;
changedAnything = true;
}
}
}
if (changedAnything) {
var fc = turf.featurecollection(thisPolygons);
var combined = turf.combine(fc);
target.setLatLngs(flipMultiPolyLatLng(combined.geometry.coordinates));
}
}
You may notice I used a function called 'flipMultiPolyLatLng'. This is because turf seemed to return geometry coordinates in '[Longitude, Latitude]' form (rather than the other way around). This functions just iterates through all the coordinate pairs and flips them - returning a new array.
Edit: I've found that turf has this function built in called turf.flip. Thus you can use that in place of 'flipMultiPolyLatLng'.
I’ve found this code to work in a non-performance-critical environment, so if you’re dealing with huge GeoJSON features, you may need to make certain optimizations for performant code.
Check out my other blog posts! If you found this post interesting, feel free to let me know either on Twitter (@Isaac_M_Jordan), or in the comments section below.
Enjoyed my post? Sign up to the newsletter to receive a small email when I post. No spam, I promise.
Recommend
-
30
Turf Calculator
-
10
On Mapbox, Leaflet, and Turf.js The past year I’ve worked a lot with Google Maps. I thought Google Maps were awesome. They seem to know about every “Place” on the planet! So I was a little shy about having to...
-
5
点到任意折线组的最短距离(及turf.js的实现解析)小芋头君前端职业咨询加微信 yutou-963
-
10
Javascript Intersection Observer API – removing the listener, watching only for half of the element, changing the viewport In
-
6
In Communiqués, Leader of Breakaway US Republic Signals Openness to PeaceScott Thomson of the Constitutional Republic City of Oroville denied calling Motherboard fools, but apologized if he did....
-
3
Atos Defends Its Supercomputing Turf With New Exascale Iron There are not many companies left on Earth that can field an exascale-class supercomputer. Atos, which was known primarily for its IT consultancy business in Europ...
-
3
August 17, 2022 ...
-
2
Starbucks Workers Serve Dunkin’ Donuts at Strike at Flagship NYC StoreStrike organizers allege bed bug sightings and black mold in the ice machines. by
-
10
Support is great. Feedback is even better."Thanks for checking out the TURF launch! We'd love to hear from you what you think of the art style and whether you'd ever consider gifting a TURF to your loved ones"
-
9
SpaceflightNorway Isn't Amused After Swedish Rocket Crashed on Its TurfThe research rocket took a longer trajectory th...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK