greiner-hormann
Version:
Greiner-Hormann clipping algorithm
119 lines (103 loc) • 3.63 kB
JavaScript
import L from 'leaflet';
import leafletDraw from 'leaflet-draw';
import * as greinerHormann from '../../src/leaflet';
// Hong Kong
var map = L.map('map')
.setView([22.2670, 114.188], 18),
geoJSON = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[ ],
[ ],
[ ],
[ ],
[ ],
[ ],
[ ],
[ ],
[ ],
[ ],
[ ],
[ ],
[ ],
[ ]
]
]
}
}]
};
// add an OpenStreetMap tile layer
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© ' +
'<a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
})
.addTo(map);
// Initialise the FeatureGroup to store editable layers
var drawnItems = new L.GeoJSON(geoJSON);
map.addLayer(drawnItems);
var markers = new L.FeatureGroup();
map.addLayer(markers);
// Initialise the draw control and pass it the FeatureGroup of
// editable layers
var drawControl = new L.Control.Draw({
draw: {
polyline: false,
circle: false,
marker: false,
circlemarker: false
},
edit: {
featureGroup: drawnItems
}
}),
polygons;
map.addControl(drawControl);
// add it to the map
map.on('draw:created', function(evt) {
drawnItems.addLayer(evt.layer);
});
// scan for collisions
map.on('draw:created', function(evt) {
var features = drawnItems.getLayers(),
feature = evt.layer,
collisionPolygonOptions = {
color: '#f00',
fillColor: '#f00'
},
otherFeature, intersection, polygon;
function addIntersectionPolygon(intersection) {
var polygon = new L.Polygon(intersection, collisionPolygonOptions)
polygon.addTo(map);
polygons.push(polygon);
}
for (var i = 0, len = features.length; i < len; i++) {
otherFeature = features[i];
if (otherFeature === feature) {
continue;
}
intersection = greinerHormann.intersection(otherFeature, feature);
console.log(otherFeature, feature);
console.log(intersection);
polygons = [];
if (intersection) {
if (typeof intersection[0][0] === 'number') {
addIntersectionPolygon(intersection);
} else { // multiple
for (var i = 0, len = intersection.length; i < len; i++) {
addIntersectionPolygon(intersection[i]);
}
}
}
}
});
// expose
window.map = map;
window.drawnItems = drawnItems;
window.polygons = polygons;
window.markers = markers;