SpatialTimes GeolocationAPI

Using vanilla Geolocation API to show a location in Leaflet

by Bryan McIntosh

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="divLocate">
  <button>Get Location</button>
  <div id="gnssData"></div>
</div>
<div id="map"></div>

CSS

html,
body,
#map {
  padding: 0;
  margin: 0;
  height: 100%;
  width: 100%;
}

#divLocate {
  position: fixed;
  left: 0px;
  bottom: 0px;
  margin: 15px;
  z-index: 20;
  background-color: rgba(250, 250, 250, .8);
}

#map {
  z-index: 10;
}

JavaScript

const gpsOptions = {
  enableHighAccuracy: true,
  timeout: 6000,
  maximumAge: 0
};
const gnssDiv = document.getElementById("gnssData");
const map = L.map('map').setView([44, -79], 9);
const osmTileLayer = L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
  maxZoom: 19,
  attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
const layerGpsGroup = L.layerGroup().addTo(map);

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(pos) {
      const dateObject = new Date(pos.timestamp);
      const {
        latitude,
        longitude,
        accuracy
      } = pos.coords;
      gnssDiv.innerHTML = `Date: ${dateObject} 
                <br>Lat/Long: ${latitude.toFixed(5)}, ${longitude.toFixed(5)} 
                <br>Accuracy: ${accuracy} (m)`;
      
      const radius = accuracy / 2;
      layerGpsGroup.clearLayers();
      map.setView([latitude, longitude], 16);

      L.marker([latitude, longitude]).addTo(layerGpsGroup)
        .bindPopup(`Lat/Long : ${latitude.toFixed(5)}, ${longitude.toFixed(5)}`)
        .openPopup();
      L.circle([latitude, longitude], radius).addTo(layerGpsGroup);
    }, function(err) {
    	console.log("geolocation error:", err);
      handleLocationError(true, infoWindow, map.getCenter());
    }, gpsOptions);
  } else {
    console.log("Browser doesn't support Geolocation");
  }
}

const btn = document.querySelector("button");
btn.addEventListener("click", getLocation);