JSFiddle - React, Tailwind, and code Playground
by kzima
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.4.0/leaflet.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.4.0/leaflet.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Turf.js/5.1.5/turf.min.js"></script>
<div id="map"></div>
<input
id="angle"
type="range"
min="-90"
max="90"
value="0"
step="1"
/>
CSS
#map {
height: 400px;
width: 600px;
}
JavaScript
var map = L.map('map').setView([-31.922933, 115.876763], 21);
var osm = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxNativeZoom: 19,
maxZoom: 23}).addTo(map);
// initial shape
var initialPolyCoords = [
[-31.9229, 115.8767],
[-31.9229, 115.8768],
[-31.922987, 115.8768],
[-31.922987, 115.8767],
[-31.9229, 115.8767]
];
var polyGeoJson = turf.flip(turf.polygon([initialPolyCoords]));
var polyCenter = turf.center(polyGeoJson);
var polyCenterCoords = turf.getCoords(polyCenter);
// this layer will update on user interaction
var polyLayer = L.geoJSON(polyGeoJson).addTo(map);
// icon for the marker
var centerIcon = L.icon({
iconUrl: 'http://www.alikilic.org/src/img/center.svg',
iconSize: [30, 30],
iconAnchor: [15, 15],
popupAnchor: [-3, -30],
});
// marker is used to move layer with it
var marker = L.marker({lat: polyCenterCoords[1], lng: polyCenterCoords[0]}, {icon: centerIcon, draggable: true}).addTo(map);
// angle handler is used to rotate shape
const angle = document.getElementById("angle");
var currentAngle = 0;
const getMovedPolyGeoJson = (newCenter, geoJson) => {
const offsetPoints = [];
// loop through new coords and create an offset points relative to original poly center
turf.coordEach(geoJson, function (currentCoord, coordIndex) {
offsetPoints.push([currentCoord[0] - polyCenterCoords[0], currentCoord[1] - polyCenterCoords[1]]);
});
// loop through offsetpoints and adjust coords to new center
const newPoints = offsetPoints.map(offsetPoint => [newCenter.lng + offsetPoint[0], newCenter.lat + offsetPoint[1]]);
return turf.polygon([newPoints]);
}
const getRotatedGeoJson = (angle, geoJson) => {
return turf.transformRotate(geoJson, Number(angle));
}
const setLayer = (geoJson) => {
polyLayer.remove();
polyLayer = L.geoJSON(
geoJson,
{
id: "structure",
width: 0.1,
color: "grey"
}).addTo(map);
}
// rotate initial object...