How can I combine polygons and remove the overlap?

2020-07-17 06:44发布

I made polygons editable in Google Maps and now I can change the shape, make holes in it, combine two of more polygons to multipolygons and disaggregate them again.

See http://maps.amsterdam.nl/testshape/beheer and read the Instructions in the Legenda to try it yourself.

One question I can't figure out is how to combine two overlapping polygons to one polygon with no overlap. Something like this:

function(path1, path2) {
  algorithm...
  return newPath;
}

Thank you.

1条回答
够拽才男人
2楼-- · 2020-07-17 07:19

Thanks a lot for the lib suggestion. I used https://github.com/bjornharrtell/jsts/blob/master/examples/overlay.html with:

var union = a.union(b);
var difference = a.difference(b);

to combine shapes and to make holes in shapes or to clip shapes. Therefor I had to convert the Google Maps paths to WKT and I wrote this Javascript:

function doeWKT(dePaths) {
var deWKTarray = [];    
for (var i = 0; i < dePaths.length; i++) {
    dePath = dePaths.getArray()[i].getArray();
    var deKomma = "";
    var deCoords = "";
    for (var j = 0; j < dePath.length; j++) {
        deLatLng = dePath[j];
        if (j == 0) var deCoords0 = deKomma + deLatLng.lng().toFixed(6) + " " + deLatLng.lat().toFixed(6);
        deCoords +=  deKomma + deLatLng.lng().toFixed(6) + " " + deLatLng.lat().toFixed(6);
        deKomma = ",";
    }
    deWKTarray.push("(" + deCoords + "," + deCoords0 + ")");
}

var deHoles = [];
var deReader = new jsts.io.WKTReader();     
for (var i = 0; i < deWKTarray.length; i++) {
    var deHole = deReader.read("POLYGON("+deWKTarray[i]+")");
    if (!deHoles[i]) deHoles[i] = -1;
    for (var j =0; j < deWKTarray.length; j++) {
        if ( i != j) {
            var deContainer = deReader.read("POLYGON(" + deWKTarray[j] + ")");
            if (deHole.within(deContainer)) deHoles[i] = j;
        }
    }
}

var deKomma = "";
var deWKTstring = "";
var deMulti = false;
for (var i = 0; i < deWKTarray.length; i++) {
    if (deHoles[i] == -1) {
        deWKTstring += deKomma + "(" + deWKTarray[i] + "";
        if (i > 0) var deMulti = true;
    }
    for (var j = 0; j < deHoles.length; j++) {
        if (deHoles[j] == i) deWKTstring += "," + deWKTarray[j] + "";
    }
    if (deHoles[i] == -1) deWKTstring += ")";   
    deKomma = ",";
}

if (deMulti) deWKTstring = "MULTIPOLYGON(" + deWKTstring +")";
else deWKTstring = "POLYGON" + deWKTstring;
return deWKTstring;
}

You can try/see everthing working in http://maps.amsterdam.nl/testshape/beheer (read Instructions in the Legend)

查看更多
登录 后发表回答