PHP code example of willvincent / polyclip

1. Go to this page and download the library: Download willvincent/polyclip library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

willvincent / polyclip example snippets


use Polyclip\Clipper;
use GeoJson\Geometry\Polygon;

$polygon1 = new Polygon([[[0, 0], [2, 0], [2, 2], [0, 2], [0, 0]]]);
$polygon2 = new Polygon([[[1, 1], [3, 1], [3, 3], [1, 3], [1, 1]]]);

$result = Clipper::union($polygon1, $polygon2);
echo json_encode($result); // Outputs the resulting GeoJSON Feature

$result = Clipper::intersection($polygon1, $polygon2);

$result = Clipper::xor($polygon1, $polygon2);

$subject = new Polygon([[[0, 0], [2, 0], [2, 2], [0, 2], [0, 0]]]);
$clip = new Polygon([[[1, 1], [3, 1], [3, 3], [1, 3], [1, 1]]]);

$result = Clipper::difference($subject, $clip);

use GeoJson\Feature\FeatureCollection;
use GeoJson\Feature\Feature;

$collection = new FeatureCollection([
    new Feature($polygon1),
    new Feature($polygon2),
]);

$result = Clipper::union($collection);

$polygon = new Polygon([[[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]]);

$geojson = '{"type": "Polygon", "coordinates": [[[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]]}';

$polygonArray = [[[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]]; // Single polygon
$multiPolygonArray = [
    [[[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]], // Polygon 1
    [[[2, 2], [3, 2], [3, 3], [2, 3], [2, 2]]]  // Polygon 2
];

Clipper::setPrecision(0.0001); // Sets the precision for all subsequent operations

try {
    $result = Clipper::union($geom1, $geom2);
} catch (\InvalidArgumentException $e) {
    echo "Error: " . $e->getMessage();
}