JSFiddle - React, Tailwind, and code Playground

by Albin Larsson

HTML

<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css">
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<div id="map"></div>

CSS

body {
  margin: 0;
}

#map {
  height: 100vh;
  width: 100vw;
}

JavaScript

function rotationDirection(latLon1, latLon2, latLon3) {
  let a = (Number(latLon3.lat) - Number(latLon1.lat)) * Number((latLon2.lon - latLon1.lon));
  let b = (Number(latLon2.lat) - Number(latLon1.lat)) * Number((latLon3.lon - latLon1.lon));
  // -1 clockwise
  //  0 none
  //  1 counter clockwise
  return (a > b + Number.EPSILON) ? 1 : (a + Number.EPSILON < b) ? -1 : 0;
}

function linesIntersects(line1, line2) {
  // #TODO readability.
  let faceRotation1 = rotationDirection(line1.p1, line1.p2, line2.p2);
  let faceRotation2 = rotationDirection(line1.p1, line1.p2, line2.p1);
  let faceRotation3 = rotationDirection(line1.p1, line2.p1, line2.p2);
  let faceRotation4 = rotationDirection(line1.p2, line2.p1, line2.p2);

  // possible edge case would be lines non top of etch other but it's unlikely for our use case
  return faceRotation1 != faceRotation2 && faceRotation3 != faceRotation4;
}

const osm = L.tileLayer('https://{s}.tile.openstreetmap.se/hydda/full/{z}/{x}/{y}.png', {
  maxZoom: 18,
  subdomains: 'abc',
  attribution: 'OpenStreetMap',
});

var map = L.map('map', {
    center: [51.505, -0.09], // ursprungs-centrum
    zoom: 13, // ursprungs-zoom
    layers: [osm] // vilka lager som ska visas från start
});

var line = new L.Polyline([
    [51.509, -0.08],
    [51.503, -0.06]
]).addTo(map);

var marker = L.marker([51.50751376820967, -0.0668621063232422]).addTo(map);

map.on('click', (e) => {
  var line1 = {p1: { lat: 51.50751376820967, lon: -0.0668621063232422}, p2: { lat: e.latlng.lat, lon: e.latlng.lng}}
  var line2 = {p1: { lat: 51.509, lon: -0.08}, p2: { lat: 51.509, lon: -0.08}}
  console.log(linesIntersects(line1, line2));
});