-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap.html
More file actions
291 lines (264 loc) · 12.6 KB
/
Copy pathmap.html
File metadata and controls
291 lines (264 loc) · 12.6 KB
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
<!DOCTYPE html>
<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>
<html lang="zh-HK">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>導航應用程式</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
<style>
body {
padding: 20px;
font-size: 1.5em; /* Increase font size */
}
#map {
height: 400px;
width: 100%;
}
#instructions {
margin-top: 20px;
}
.blinking {
animation: blinkingBackground 1s infinite;
}
@keyframes blinkingBackground {
0% { background-color: #ffcccc; }
50% { background-color: #ffffff; }
100% { background-color: #ffcccc; }
}
</style>
</head>
<body>
<div class="container">
<h1>導航應用程式</h1>
<form>
<div class="form-group">
<label for="currentLocation">當前位置</label>
<input type="text" class="form-control" id="currentLocation" readonly>
</div>
<div class="form-group">
<label for="destination">目的地</label>
<input type="text" class="form-control" id="destination">
</div>
<div class="form-group">
<label for="timeRemaining">剩餘時間</label>
<input type="text" class="form-control" id="timeRemaining" readonly>
</div>
</form>
<div class="btn-group btn-group-lg" role="group">
<button type="button" class="btn btn-primary" onclick="getCurrentLocation()">獲取GPS位置</button>
<button type="button" class="btn btn-secondary" onclick="startVoiceInput()">語音輸入</button>
<button type="button" class="btn btn-success" onclick="generateRoute()">立即路線</button>
<button type="button" class="btn btn-danger" onclick="startNavigation()">開始導航</button>
</div>
<div id="map"></div>
<div id="instructions" class="list-group"></div>
</div>
<script>
let currentLat, currentLng;
let watchId;
const checkpoints = [];
let map, directionsRenderer, directionsService;
let currentLocationMarker;
let cantoneseVoice;
let totalDuration = 0;
let startTime;
function getCurrentLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
currentLat = position.coords.latitude;
currentLng = position.coords.longitude;
document.getElementById('currentLocation').value = `${currentLat}, ${currentLng}`;
});
} else {
alert("此瀏覽器不支持地理定位。");
}
}
function startVoiceInput() {
if ('SpeechRecognition' in window) {
const recognition = new SpeechRecognition();
recognition.lang = 'yue-Hant-HK'; // Cantonese language code
recognition.start();
recognition.onresult = function(event) {
const transcript = event.results[0][0].transcript;
document.getElementById('destination').value = transcript;
};
recognition.onerror = function(event) {
console.error(event.error);
};
} else if ('webkitSpeechRecognition' in window) {
const recognition = new webkitSpeechRecognition();
recognition.lang = 'yue-Hant-HK'; // Cantonese language code
recognition.start();
recognition.onresult = function(event) {
const transcript = event.results[0][0].transcript;
document.getElementById('destination').value = transcript;
};
recognition.onerror = function(event) {
console.error(event.error);
};
} else {
alert("此瀏覽器不支持語音輸入。");
}
}
function generateRoute() {
const destination = document.getElementById('destination').value;
if (!destination) {
alert("請輸入目的地。");
return;
}
const origin = { lat: parseFloat(currentLat), lng: parseFloat(currentLng) };
const directionsRequest = {
origin: origin,
destination: destination,
travelMode: 'TRANSIT'
};
directionsService.route(directionsRequest, (result, status) => {
if (status === 'OK') {
directionsRenderer.setDirections(result);
const route = result.routes[0];
checkpoints.length = 0;
const instructions = [];
totalDuration = 0;
route.legs[0].steps.forEach(step => {
const stepDuration = step.duration.value; // Duration in seconds
totalDuration += stepDuration;
if (step.transit) {
checkpoints.push({
lat: step.transit.departure_stop.location.lat(),
lng: step.transit.departure_stop.location.lng(),
name: step.transit.departure_stop.name
});
instructions.push({
instruction: step.instructions,
vehicle: step.transit.line.vehicle.name,
line: step.transit.line.short_name,
departureStop: step.transit.departure_stop.name,
arrivalStop: step.transit.arrival_stop.name,
departureTime: step.transit.departure_time.text,
arrivalTime: step.transit.arrival_time.text,
headsign: step.transit.headsign,
duration: step.duration.text // Duration text
});
} else {
instructions.push({
instruction: step.instructions,
duration: step.duration.text // Duration text
});
}
});
displayInstructions(instructions);
document.getElementById('timeRemaining').value = formatDuration(totalDuration);
} else {
alert("無法生成路線:" + status);
}
});
}
function displayInstructions(instructions) {
const instructionsList = document.getElementById('instructions');
instructionsList.innerHTML = '';
instructions.forEach((step, index) => {
const listItem = document.createElement('a');
listItem.className = 'list-group-item list-group-item-action';
listItem.innerHTML = `<strong>步驟 ${index + 1}:</strong> ${step.instruction} (${step.duration})`;
if (step.vehicle) {
listItem.innerHTML += `<br><strong>交通工具:</strong> ${step.vehicle}`;
listItem.innerHTML += `<br><strong>線路:</strong> ${step.line}`;
listItem.innerHTML += `<br><strong>出發站:</strong> ${step.departureStop}`;
listItem.innerHTML += `<br><strong>到達站:</strong> ${step.arrivalStop}`;
listItem.innerHTML += `<br><strong>出發時間:</strong> ${step.departureTime}`;
listItem.innerHTML += `<br><strong>到達時間:</strong> ${step.arrivalTime}`;
listItem.innerHTML += `<br><strong>方向:</strong> ${step.headsign}`;
}
listItem.onclick = () => {
let msg = new SpeechSynthesisUtterance(step.instruction);
if (step.vehicle) {
msg.text += `,交通工具:${step.vehicle},線路:${step.line},出發站:${step.departureStop},到達站:${step.arrivalStop},出發時間:${step.departureTime},到達時間:${step.arrivalTime},方向:${step.headsign}`;
}
if (cantoneseVoice) {
msg.voice = cantoneseVoice;
}
window.speechSynthesis.speak(msg);
};
instructionsList.appendChild(listItem);
});
}
function startNavigation() {
if (navigator.geolocation) {
startTime = new Date();
watchId = navigator.geolocation.watchPosition(onPositionUpdate, null, { maximumAge: 60000, timeout: 5000, enableHighAccuracy: true });
} else {
alert("此瀏覽器不支持地理定位。");
}
}
function onPositionUpdate(position) {
const lat = position.coords.latitude;
const lng = position.coords.longitude;
document.getElementById('currentLocation').value = `${lat}, ${lng}`;
const currentLocation = new google.maps.LatLng(lat, lng);
if (!currentLocationMarker) {
currentLocationMarker = new google.maps.Marker({
position: currentLocation,
map: map,
title: "當前位置"
});
} else {
currentLocationMarker.setPosition(currentLocation);
}
map.setCenter(currentLocation);
map.setZoom(16);
const nearestCheckpoint = checkpoints[0];
const checkpointLocation = new google.maps.LatLng(nearestCheckpoint.lat, nearestCheckpoint.lng);
const distance = google.maps.geometry.spherical.computeDistanceBetween(currentLocation, checkpointLocation);
if (distance > 50) {
document.body.classList.add('blinking');
const msg = new SpeechSynthesisUtterance('您已偏離路線!');
if (cantoneseVoice) {
msg.voice = cantoneseVoice;
}
window.speechSynthesis.speak(msg);
const alertSound = new Audio('alert.mp3'); // Ensure you have an alert.mp3 file
alertSound.play();
} else {
document.body.classList.remove('blinking');
const msg = new SpeechSynthesisUtterance(`當前位置: ${lat}, ${lng}`);
if (cantoneseVoice) {
msg.voice = cantoneseVoice;
}
window.speechSynthesis.speak(msg);
}
// Recalculate remaining time
recalculateRemainingTime();
}
function recalculateRemainingTime() {
const currentTime = new Date();
const elapsedTimeInSeconds = (currentTime - startTime) / 1000;
const remainingTimeInSeconds = totalDuration - elapsedTimeInSeconds;
document.getElementById('timeRemaining').value = formatDuration(remainingTimeInSeconds);
}
function formatDuration(seconds) {
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${mins} 分鐘 ${secs} 秒`;
}
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8
});
directionsRenderer = new google.maps.DirectionsRenderer();
directionsService = new google.maps.DirectionsService();
directionsRenderer.setMap(map);
}
function loadVoices() {
const voices = window.speechSynthesis.getVoices();
cantoneseVoice = voices.find(voice => voice.lang === 'zh-HK' || voice.lang === 'zh-Hant-HK' || voice.lang === 'zh-yue');
console.log(voices);
}
window.speechSynthesis.onvoiceschanged = loadVoices;
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD95rSqkw6pXe8BBztDXh0B101HjTksy-4&callback=initMap&libraries=geometry&language=zh-HK" async defer></script>
</body>
</html>