JSFiddle - React, Tailwind, and code Playground

by cat_991

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" style="width: 600px; height: 400px;"></div>

<input id="zip" type="text" style="width: 490px" placeholder="Enter your zip code (if not automatic)" />
<button onclick="findByZip()">
Find Distance
</button>

<div id="distance">Loading...</div>

CSS

html,
body {
  height: 100%;
  margin: 0;
}

.leaflet-container {
  height: 400px;
  width: 600px;
  max-width: 100%;
  max-height: 80%;
}

#distance {
  font-size: 20px;
  padding-left: 10px;
  padding-right: 10px;
  border-radius: 3px;
}

JavaScript

//setup
const map = L.map('map').setView([33.3735, -117.5684], 12);
const tiles = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
  maxZoom: 19,
  attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}).addTo(map);

//main function
function findDistance(from, to) {
  //create map objects
  var markerFrom = L.circleMarker(from.coords, {
    color: "red",
    radius: 10
  });
  var markerTo = L.circleMarker(to.coords, {
    color: "#48a7ea",
    radius: 10
  });
  var polyline = L.polyline([from.coords, to.coords], {
    color: 'red'
  }).addTo(map);
  map.fitBounds(polyline.getBounds());

  //find distance
  var fromLL = markerFrom.getLatLng();
  var toLL = markerTo.getLatLng();
  var dist = ((fromLL.distanceTo(toLL)) / 1000 / 1.621).toFixed(2)


  map.addLayer(markerTo);
  map.addLayer(markerFrom);
  polyline.bindPopup(`${from.label} to ${to.label} is ${dist} mi`)
  markerFrom.bindPopup(from.label + (fromLL).toString());
  markerTo.bindPopup(to.label + (toLL).toString());

  return dist
}

navigator.geolocation.getCurrentPosition(success, error)

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}

function success(pos) {
  const crd = pos.coords;
  // console.log([crd.latitude, crd.longitude])

  var dist = findDistance({
    coords: [33.3735823, -117.5684443],
    label: "San Onofre Waste Site "
  }, {
    coords: [crd.latitude, crd.longitude],
    label: "you "
  })

  var container = document.getElementById('distance');
  container.innerHTML = `You are ${dist} mi from the San Onofre Waste Site.` + "<br>" +
    `Over 8 million Californians are within 50 mi of radioactive waste.`
}


async function findByZip() {
	var e = document.getElementById("zip")
	var zip = e.value;
  var response = await fetch(`https://nominatim.openstreetmap.org/search.php?q=${zip}+US&format=jsonv2`)
  var geocode = (await response.json())[0]
  
  success({
  	coords: {
    	latitude: geocode.lat,
     ...