Skip to content

Instantly share code, notes, and snippets.

@geografa
Created August 19, 2016 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geografa/26af79b77866bb1a432a03927b734e29 to your computer and use it in GitHub Desktop.
Save geografa/26af79b77866bb1a432a03927b734e29 to your computer and use it in GitHub Desktop.
geolocation
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title></title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.17.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.17.0/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
button { position: absolute; margin-left: 100px; z-index: 1;}
</style>
</head>
<body>
<style>
.ui-button {
background:#3887BE;
color:#FFF;
display:block;
position:absolute;
top:50%;left:50%;
width:160px;
margin:-20px 0 0 -80px;
z-index:100;
text-align:center;
padding:10px;
border:1px solid rgba(0,0,0,0.4);
border-radius:3px;
}
.ui-button:hover {
background:#3074a4;
color:#fff;
}
</style>
<a href='#' id='geolocate' class='ui-button'>Find me</a>
<div id='map'></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoiZ3JhZmEiLCJhIjoiZjk3Mjk2YWYzZTNlYjM3ODdlNzJlOWJlM2VjZGI0ZDEifQ.OTT9oT7CqAc9vZsnJLT51Q';
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/streets-v8', //stylesheet location
center: [-74.50, 40], // starting position
zoom: 9 // starting zoom
});
var geolocate = document.getElementById('geolocate');
if (!navigator.geolocation) {
geolocate.innerHTML = 'Geolocation is not available';
} else {
geolocate.onclick = function (e) {
e.preventDefault();
e.stopPropagation();
map.locate();
};
}
map.on('locationfound', function(e) {
map.fitBounds(e.bounds);
map.addSource('single-point', {
"type": "geojson",
"data": {
"type": "FeatureCollection",
"features": []
}
});
map.addLayer({
"id": "point",
"source": "single-point",
"type": "circle",
"paint": {
"circle-radius": 10,
"circle-color": "#007cbf"
}
});
map.getSource('single-point').setData(e.result.geometry);
// And hide the geolocation button
geolocate.parentNode.removeChild(geolocate);
});
// If the user chooses not to allow their location
// to be shared, display an error message.
map.on('locationerror', function(e) {
geolocate.innerHTML = 'Position could not be found';
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment