Show Location on Map
Description
This demonstrates how to detect your current location then display it on a Map as a semi-transparent radius.
Demonstration
How To Use
- As the page loads, accept any request from your browser to grant it permission to access you location
- If the location can be found, the map will reposition to your location and a radius of your location with then display
How it Works
var map;
var latlng = [0,0];
var zoom = 2;
var mapDivID = "map_canvas";
var circleColor="#E84343";
var circleFillColor="#E3E3E3";
var circleWeight="1";
var circleFillOpacity=0.5;
var midmarker;
var showmidmarker=true;
var circle;
var radiustouse=150;
var zoomToLevel=16;
var userposition;
function initialize()
{
document.getElementById(mapDivID).style.cursor = "crosshair";
map = L.map(mapDivID,{
fullscreenControl: true,
fullscreenControlOptions: {
position: 'topleft'
}
}).setView(latlng, zoom);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'mapbox.streets'
}).addTo(map);
var openstreetmap = L.tileLayer('https://{s}.'+tileProviderURL+'/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: tileProviderAttribution
});
var ESRIImg = L.esri.basemapLayer('Imagery');
var ESRIImbLab = L.esri.basemapLayer('ImageryLabels');
var baseLayers = {
"OSM": openstreetmap,
"Satellite": ESRIImg
};
var overlays = {
"Labels": ESRIImbLab,
};
ESRIImg.addTo(map);
L.control.layers(baseLayers,overlays).addTo(map);
L.control.locate().addTo(map); //Add "Show me where I am" control
//Start the Geolocation
tryGeolocation();
//Check if cb_keepupdating is ticked
setInterval(recurring,5000); // Time in milliseconds
}
var tryGeolocation = function() {
document.getElementById("msg").innerHTML="GeoLocating...";
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
browserGeolocationSuccess,browserGeolocationFail,
{maximumAge: 50000, timeout: 20000, enableHighAccuracy: true});
}
};
var browserGeolocationSuccess = function(position) {
showPosition(position.coords.latitude,position.coords.longitude);
};
function recurring()
{
if (document.getElementById("cb_keepupdating").checked)
{
tryGeolocation();
}
}
function showPosition(lat,lng) {
document.getElementById("msg").innerHTML="GeoLocation Found";
userposition = L.latLng(Number(lat).toFixed(4),Number(lng).toFixed(4));
map.setView(userposition,zoomToLevel)
//Plot marker
if (showmidmarker)
{
if (midmarker)
{
midmarker.remove();
}
midmarker = L.marker(userposition,{title:''}).addTo(map);
}
//Plot Circle
plotcircle(userposition,radiustouse);
}
function plotcircle(point,distance)
{
if (circle)
{
circle.remove();
}
circle = makecircle(point,distance);
}
function makecircle(point,distance)
{
thiscircle = ftn_DrawCircle(point,distance);
thiscircle.addTo(map);
return thiscircle;
}
function ftn_DrawCircle(point,rad) {
draw_circle =L.circle(point, rad, {
color: circleColor,
fillColor: circleFillColor,
fillOpacity: circleFillOpacity,
weight: circleWeight
});
return draw_circle;
}
var browserGeolocationFail = function(error) {
switch (error.code) {
case error.TIMEOUT:
console.log("Browser geolocation error !\n\nTimeout.");
break;
case error.PERMISSION_DENIED:
if(error.message.indexOf("Only secure origins are allowed") == 0) {
console.log("error");
}
break;
case error.POSITION_UNAVAILABLE:
console.log("Browser geolocation error !\n\nPosition unavailable.");
break;
}
};
Further Uses and Ideas
- Use Geolocation API watchPosition() method
Version History
- Version 1 (31st October 2016) - Initial Version
- Version 2 (7th November 2018) - Switched to use Leaflet maps