# some-02 ``` c = // 取得使用者當前的位置 navigator.geolocation.getCurrentPosition(function(position) { // 更新路線的起點 start = [position.coords.longitude, position.coords.latitude]; // 使用 Mapbox Directions API 取得更新後的路線 fetch('https://api.mapbox.com/directions/v5/mapbox/driving/' + start[0] + ',' + start[1] + ';' + end[0] + ',' + end[1] + '?access_token=YOUR_MAPBOX_ACCESS_TOKEN') .then(function(response) { return response.json(); }) .then(function(data) { console.log(data.routes[0].geometry); // 在地圖上更新路線 map.getSource('route').setData({ 'type': 'Feature', 'geometry': data.routes[0].geometry }); }); }); ``` ``` c = // 設定路線起點和終點的座標 var start = [-122.431297, 37.773972]; var end = [-122.408058, 37.790979]; // 使用Mapbox Directions API取得路線 fetch('https://api.mapbox.com/directions/v5/mapbox/driving/' + start[0] + ',' + start[1] + ';' + end[0] + ',' + end[1] + '?access_token=YOUR_MAPBOX_ACCESS_TOKEN') .then(function(response) { return response.json(); }) .then(function(data) { console.log(data.routes[0].geometry); // 將路線加入地圖 map.addLayer({ 'id': 'route', 'type': 'line', 'source': { 'type': 'geojson', 'data': { 'type': 'Feature', 'geometry': data.routes[0].geometry } }, 'layout': { 'line-join': 'round', 'line-cap': 'round' }, 'paint': { 'line-color': '#3887be', 'line-width': 5, 'line-opacity': 0.75 } }); }); ``` ``` c = // 創建一個新的 GeoJSON source 並將其添加到地圖上 var geojsonSource = new mapboxgl.GeoJSONSource({ data: { type: 'FeatureCollection', features: [] } }); map.addSource('locations', geojsonSource); // 為地點標記添加一個新的圖層到地圖上 map.addLayer({ id: 'location-markers', type: 'symbol', source: 'locations', layout: { 'icon-image': 'circle-15', 'icon-allow-overlap': true } }); // 監聽位置更新事件並將其添加到 GeoJSON source 上 websocket.onmessage = function(event) { var location = JSON.parse(event.data); geojsonSource.setData({ type: 'FeatureCollection', features: [{ type: 'Feature', geometry: { type: 'Point', coordinates: [location.longitude, location.latitude] } }] }); }; ```