biommap/sandbox/lines-polygons/index.html

92 lines
3.2 KiB
HTML

<!DOCTYPE html>
<html style="height:100%;margin:0;padding:0;">
<head>
<title>Tests edit line - polygon</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<script src="./leaflet/leaflet-hash.js"></script>
<style type="text/css">
.leaflet-tile-container { pointer-events: auto; }
</style>
</head>
<body style="height:100%;margin:0;padding:0;">
<div id="map" style="height:100%"></div>
<script>
const map = L.map('map').setView([50.5, 5.57], 10);
const cyclosm = L.tileLayer('https://{s}.tiles.champs-libres.be/cyclosm/{z}/{x}/{y}.png', {
subdomains: "abc",
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
maxZoom: 20
});
map.addLayer(cyclosm);
const hash = L.hash(map);
let geometryType = 'LINESTRING'; //'POINT' | 'LINESTRING' | 'POLYGON'
let myMarker = null;
let polyline = null;
let previousPolyline = null;
let previousLayerPoint = null;
const lineDraw = L.polyline([], {color: '#11aa9e', dashArray: '6', lineCap: 'butt'}).addTo(map);
const pointDistance = (pointA, pointB) => {
const SNAP_DISTANCE = 6;
let distancePixel = Math.sqrt(Math.abs((pointB.x - pointA.x)**2 - (pointB.y - pointA.y)**2));
return distancePixel < SNAP_DISTANCE;
};
const arePointsSnapped = (previousPoint, currentPoint) =>
(previousPoint && currentPoint) ? pointDistance(previousPoint, currentPoint) : false;
switch(geometryType){
case 'LINESTRING':
map.on('mousemove', (e) => {
if(polyline){
let lastDrawPoint = polyline.getLatLngs()[polyline.getLatLngs().length - 1];
lineDraw.setLatLngs([lastDrawPoint, e.latlng]);
}
});
break;
}
map.on('click', (e) => {
console.log(e);
switch(geometryType){
case 'POINT':
default:
if (myMarker !== null) {
map.removeLayer(myMarker);
}
myMarker = L.marker(e.latlng).addTo(map);
case 'LINESTRING':
lineDraw.setLatLngs([]);
if (polyline === null){
console.log(previousPolyline)
if (previousPolyline !== null){
map.removeLayer(previousPolyline);
}
polyline = L.polyline([e.latlng], {color: '#11aa9e'}).addTo(map);
} else {
if (arePointsSnapped(previousLayerPoint, e.layerPoint)) {
console.log('reset line')
previousPolyline = polyline;
polyline.setStyle({color: '#60b15c'});
polyline = null;
} else {
polyline.addLatLng(e.latlng);
previousLayerPoint = e.layerPoint;
}
}
}
});
</script>
</body>
</html>