-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroute-match.html
159 lines (129 loc) · 4.21 KB
/
route-match.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
<!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' />
<script src='https://unpkg.com/@turf/turf@6/turf.min.js'></script>
<style>
html,
body {
margin: 0;
}
#map-container {
width: min(100vw, 800px);
height: min(80vw, 500px);
}
</style>
</head>
<body>
<h1>Clique em 2 ou mais lugares no mapa para ver uma rota:</h1>
<div id="map-container"></div>
<button onclick="rotate()">rotate</button>
<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 markers = []
map.on('click', function (event) {
addMarkerOnMap(event.lngLat);
});
map.on('mousedown', stopCameraRotation);
map.on('touchstart', stopCameraRotation);
function addMarkerOnMap(lngLat) {
const marker = new mapboxgl.Marker({ draggable: true })
.setLngLat(lngLat)
.addTo(map);
markers.push(marker);
marker.on('dragstart', cleanRouteLayer);
marker.on('dragend', drawRoutesOnMap);
drawRoutesOnMap();
}
async function drawRoutesOnMap() {
cleanRouteLayer()
if (markers.length < 2) return;
const coords = markers.map(item => item.getLngLat().toArray())
const routes = await getMatch(coords)
map.addLayer({
'id': 'route',
'type': 'line',
'source': {
'type': 'geojson',
'data': {
'type': 'Feature',
'properties': {},
'geometry': routes
}
},
'layout': {
'line-join': 'round',
'line-cap': 'round'
},
'paint': {
'line-color': '#03AA46',
'line-width': 5,
'line-opacity': 0.8
}
});
}
function cleanRouteLayer() {
if (map.getSource('route')) {
map.removeLayer('route');
map.removeSource('route');
}
}
// @see https://docs.mapbox.com/help/tutorials/get-started-map-matching-api/
async function getMatch(coordinates, profile = 'driving') {
const radiuses = coordinates.map(() => 25).join(';');
coordinates = coordinates.join(';');
const query = await fetch(
`https://api.mapbox.com/matching/v5/mapbox/${profile}/${coordinates}?geometries=geojson&radiuses=${radiuses}&steps=true&access_token=${mapboxgl.accessToken}`,
{ method: 'GET' }
);
const response = await query.json();
if (response.code !== 'Ok') {
alert(
`${response.code} - ${response.message}.\n\nFor more information: https://docs.mapbox.com/api/navigation/map-matching/#map-matching-api-errors`
);
return;
}
return response.matchings[0].geometry;
}
function fitMarkersInMapViewport() {
const lineGeoJson = turf.lineString(markers.map(item => item.getLngLat().toArray()));
const bbox = turf.bbox(lineGeoJson);
map.fitBounds(bbox, {
padding: 80,
duration: 0
});
}
let raf = null;
let rotation = 0;
// @see https://docs.mapbox.com/mapbox-gl-js/example/animate-camera-around-point/
function rotateCamera() {
rotation += 0.2;
map.rotateTo(rotation % 360, { duration: 0 });
raf = requestAnimationFrame(rotateCamera);
}
function stopCameraRotation() {
cancelAnimationFrame(raf);
raf = null;
}
function rotate() {
if (raf !== null) return stopCameraRotation();
if (markers.length < 2) return;
fitMarkersInMapViewport();
map.setPitch(50, { duration: 0 });
rotateCamera();
}
</script>
</body>
</html>