-
Notifications
You must be signed in to change notification settings - Fork 0
/
select-location-on-map.html
78 lines (62 loc) · 2.12 KB
/
select-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
75
76
77
78
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Select 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>Selecione um local no mapa:</h1>
<div id="map-container"></div>
<p id="address"></p>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoiaWFnb2JydW5vIiwiYSI6ImNram41cDI1bjBhYWEyeXFscGp5ZG15bnAifQ.kGQsH0C6Li7MwXrOWr1Qmw';
const carnaubalLatLng = new mapboxgl.LngLat(-40.941498, -4.162548);
const addressEl = document.getElementById('address')
// 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('click', function (event) {
showMarkerOnMap(event.lngLat);
printAddress(event.lngLat);
});
function showMarkerOnMap(lngLat) {
marker.setLngLat(lngLat).addTo(map);
}
async function printAddress(lngLat) {
console.log('lngLat', lngLat)
addressEl.textContent = 'Carregando...';
await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${lngLat.lng},${lngLat.lat}.json?access_token=${mapboxgl.accessToken}`)
.then(res => res.json())
.then(data => data.features[0])
.then(data => {
addressEl.innerHTML = `
<h3>Endereço selecionado:</h3>
Rua: ${data.text}<br>
Número: ${data.address}
`;
})
.catch(err => {
addressEl.innerHTML = '<span style="color:red">Não foi possível obter o endereço do local selecionado :(</span>';
});
}
</script>
</body>
</html>