-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshow-current-location-on-map.html
74 lines (60 loc) · 2 KB
/
show-current-location-on-map.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Show current location on map</title>
<script src='https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.css' rel='stylesheet' />
<style>
html, body {
margin: 0;
}
#map-container {
width: min(100vw, 800px);
height: min(80vw, 500px);
}
</style>
</head>
<body>
<h1>Mostra a localização atual do usuário no mapa:</h1>
<div id="map-container"></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoiaWFnb2JydW5vIiwiYSI6ImNram41cDI1bjBhYWEyeXFscGp5ZG15bnAifQ.kGQsH0C6Li7MwXrOWr1Qmw';
const carnaubalLatLng = new mapboxgl.LngLat(-40.941498, -4.162548);
// Init map
const map = new mapboxgl.Map({
container: document.getElementById('map-container'),
center: carnaubalLatLng, // starting position [lng, lat]
zoom: 13.4, // starting zoom
style: 'mapbox://styles/mapbox/streets-v11', // stylesheet location
});
const marker = new mapboxgl.Marker();
map.on('load', showUserLocationOnMap);
function showUserLocationOnMap() {
if (!('geolocation' in navigator)) {
return alert('Seu navegador não suporta geolocalização :(');
}
// Get user latitude and longitude
navigator.geolocation.getCurrentPosition(
successCallback,
errorCallback,
{
enableHighAccuracy: true,
}
);
function successCallback(position) {
const userLatLng = new mapboxgl.LngLat(position.coords.longitude, position.coords.latitude);
map.setCenter(userLatLng);
showMarkerOnMap(userLatLng);
}
function errorCallback() {
alert('Não foi possível determinar sua localização automaticamente :(');
}
}
function showMarkerOnMap(lngLat) {
marker.setLngLat(lngLat).addTo(map);
}
</script>
</body>
</html>