Question

I'm trying to merge 2 polygons (green) on Google maps (API v3 Javascript) with clipper.js.

before : http://jsfiddle.net/kevdiho/tc53Y/

My goal is to have only 1 polygon (red). The problem is that the final polygon is not exactly follow the path and sometime it's even worst.

after : http://jsfiddle.net/kevdiho/uF6ec/

to merge the 2 green polygons i used clipper.js and this function ClipperLib.ClipType.ctUnion

var clipType = ClipperLib.ClipType.ctUnion;
function mergePolygon()
  {
      for(j=0;j<array_polygon.length;j++){
          array_polygon_clipper = createarray_clipper_polygon(array_polygon[j]);
          subj_polygons.push(array_polygon_clipper);
      }
      cpr.AddPolygons(subj_polygons, ClipperLib.PolyType.ptSubject);
      var succeeded = cpr.Execute(clipType, solution_polygons);
      return solution_polygons;
  }

How can i solve this problem? Clipper.js is a good answer or there are other libraries to work with googlemaps polygons?

Was it helpful?

Solution

Your example could work if you upscale the coordinates before AddPolygons call and downscale them after union operation, eg. by 1000000000000. The scaling is needed to maintain precision, when floats are used, because Clipper uses integers innerly. This has a downside that the operation is slow, because Clipper uses big integer library, if coordinates are upscaled heavily.

To overcome the slowness (and precision) issue, there is available a new (though still experimental) "floats" Clipper: http://jsclipper.sourceforge.net/6.1.3.1_fpoint/clipper.js http://jsclipper.sourceforge.net/6.1.3.1_fpoint/clipper_unminified.js

Clipper 6 has some things changed, which you have to take into account when migrating from Clipper 5 to 6: https://sourceforge.net/p/jsclipper/wiki/migration5to6/

I made a change for you: http://jsfiddle.net/uF6ec/2/

function dummy(){}

OTHER TIPS

Here is a way to make a non-hole union that NAJ asked in the comment to the answer. The image below shows two polygons unioned so that the hole is missing:

enter image description here

FIDDLE: http://jsfiddle.net/uF6ec/121/

The reason for a hole is different orientations of subject polygons. We have to detect if the area is negative and reverse the orientation:

if (ClipperLib.JS.AreaOfPolygon(array_polygon_clipper) < 0)
{
    array_polygon_clipper.reverse();
}

(You could also make the exact opposite to achieve the same solution, by reversing all polygons whose area is positive.)

And then use pftNonZero filling rule in Execute():

var succeeded = cpr.Execute(ClipperLib.ClipType.ctUnion,
solution_polygons, ClipperLib.PolyFillType.pftNonZero, 
ClipperLib.PolyFillType.pftNonZero);

You can read more about fill rules and ReversePath.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top