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="-20"
  max="20"
  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);
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);
var marker = L.marker({lat: polyCenterCoords[1], lng: polyCenterCoords[0]}, {draggable: true}).addTo(map);
const angle = document.getElementById("angle");

/* const getOffsets = () => {
  const polyJson = poly.toGeoJSON();
  const center = turf.getCoords(turf.center(polyJson));
  console.log(turf.getCoords(center))
  const points = [];
  turf.coordEach(polyJson, function (currentCoord, coordIndex) {
   // console.log(currentCoord)
   points.push([currentCoord[0] - center[0], currentCoord[1] - center[1]]);
  });
  return points;
}
const setPosition = (position) => {
    const offsets = getOffsets();
    return offsets.map(offsetPoint => [position.lng + offsetPoint[0], position.lat + offsetPoint[1]]);

}
// move shape
// take initial points and move by offset (change of the center)
// show a new layer on the map from offseted points
marker.on("drag", (e) => {
  const newPoints = setPosition(e.latlng);
  poly.remove();
  poly = L.geoJSON(turf.polygon([newPoints])).addTo(map);
  const geoJSON = poly.toGeoJSON();
  const newPoint = turf.point([e.latlng.lng, e.latlng.lat]);
  const centroid = turf.centroid(geoJSON);
  const distance = turf.distance(newPoint, centroid);
  const bearing = turf.bearing(newPoint, centroid)
  // poly.remove();
  L.geoJSON(turf.transformTranslate(geoJSON, distance, -bearing)).addTo(map);
});
*/

// rotate initial object and move to the position by offset
angle.addEventListener("change", (e) => {
 ...