-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdriver.js
More file actions
188 lines (151 loc) · 6.52 KB
/
driver.js
File metadata and controls
188 lines (151 loc) · 6.52 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
const map = L.map('map'); // Initialize the map without a location
let userMarker;
let hospitalMarker;
let routeLine;
let routingControl; // To hold routing control
// Get the user's current location
function getUserLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
document.getElementById('status').textContent = 'Geolocation is not supported by your browser.';
}
}
// On successful location fetch
function success(position) {
const userLat = position.coords.latitude;
const userLon = position.coords.longitude;
// Center the map on the user's location
map.setView([userLat, userLon], 13);
// Add OpenStreetMap tiles
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
// Remove any existing markers, route, and routing control
if (userMarker) map.removeLayer(userMarker);
if (hospitalMarker) map.removeLayer(hospitalMarker);
if (routeLine) map.removeLayer(routeLine);
if (routingControl) map.removeControl(routingControl);
// Add a marker for the user's location
userMarker = L.marker([userLat, userLon]).addTo(map);
userMarker.bindPopup("You are here").openPopup();
}
// Establish WebSocket connection
const socket = new WebSocket('wss://post-accident-alert-system-backend.onrender.com');
socket.onopen = () => {
console.log('WebSocket connection established in map.html');
};
socket.onerror = (error) => {
console.error('WebSocket error in map.html:', error);
};
socket.onclose = () => {
console.warn('WebSocket connection closed in map.html');
};
const urlParams = new URLSearchParams(window.location.search);
const dusername = urlParams.get('username');
console.log("Username received:", dusername);
const userContent = {
"Raam": {'name': 'Raam', 'hname': "Ganga Hospital"},
"Prathap": {'name': 'Prathap', 'hname': "Amrita Clinic"},
};
document.querySelector(".hospital_name").innerHTML=`${userContent[dusername]['name']}<br>${userContent[dusername]['hname']}`
let p_name = null;
socket.onmessage = async (event) => {
// Handle Blob objects
if (event.data instanceof Blob) {
const text = await event.data.text(); // Convert Blob to text
console.log('Blob converted to text:', text);
try {
const data = JSON.parse(text); // Parse the text as JSON
console.log('Parsed JSON message:', data);
const type = data.type;
const lat = data.latt;
const lng = data.lngg;
const username = data.user;
console.log(type);
console.log(username);
console.log(lat);
console.log(lng);
p_name = data.pname;
if (type === 'map_update' && lat && lng && username === userContent[dusername]['hname']) {
console.log('Processing map update with coordinates:', lat, lng);
getRouteToReceivedLocation(lat, lng);
} else if (type !== 'map_update') {
console.log(`Ignoring message of type '${type}' in map.html`);
} else {
console.error('Invalid data received in map.html or username mismatch:', data);
}
} catch (e) {
console.error('Blob could not be parsed as JSON:', text);
}
return;
}
// Handle non-Blob messages (already JSON)
try {
const data = JSON.parse(event.data);
console.log('Parsed JSON message:', data);
const type = data.type;
const lat = data.latt;
const lng = data.lngg;
const username = data.user;
p_name = data.pname;
if (type === 'map_update' && lat && lng && username === userContent[dusername]['hname']) {
console.log('Processing map update with coordinates:', lat, lng);
getRouteToReceivedLocation(lat, lng);
} else if (type !== 'map_update') {
console.log(`Ignoring message of type '${type}' in map.html`);
} else {
console.error('Invalid data received in map.html or username mismatch:', data);
}
} catch (e) {
console.error('Invalid JSON message received:', event.data);
}
};
document.querySelector('.location-refresh-btn').addEventListener('click', function () {
document.getElementById('status').textContent = 'Fetching your current location...';
const data = { type: "hospital_update", latt: "", lngg: "", hlat: "", hlngg: "", user: p_name, eta: "", severity: ""};
console.log(data);
const message = JSON.stringify(data);
socket.send(message);
getUserLocation();
});
function getRouteToReceivedLocation(lat, lng) {
const userLocation = userMarker.getLatLng(); // Current user location
const start = L.latLng(userLocation.lat, userLocation.lng);
const end = L.latLng(lat, lng);
userMarker = L.marker([lat, lng]).addTo(map);
// Remove existing route and control
if (routingControl) map.removeControl(routingControl);
routingControl = L.Routing.control({
waypoints: [start, end],
routeWhileDragging: true,
createMarker: () => null // No markers
}).addTo(map);
routingControl.on('routesfound', function (e) {
const route = e.routes[0];
const distance = route.summary.totalDistance / 1000; // Convert to km
document.getElementById('status').textContent = `Received location is ${distance.toFixed(2)} km away via road.`;
});
}
function error() {
document.getElementById('status').textContent = 'Unable to retrieve your location.';
}
// Function to get route using Leaflet Routing Machine
function getRoute(userLat, userLon, hospitalLat, hospitalLon) {
const start = L.latLng(userLat, userLon);
const end = L.latLng(hospitalLat, hospitalLon);
// Initialize the routing control
routingControl = L.Routing.control({
waypoints: [start, end],
routeWhileDragging: true,
createMarker: function() { return null; } // Don't show markers for waypoints
}).addTo(map);
// Get the route and update status with road distance
routingControl.on('routesfound', function(e) {
const route = e.routes[0];
const roadDistance = route.summary.totalDistance / 1000; // Convert to km
document.getElementById('status').textContent = `Nearest hospital is ${roadDistance.toFixed(2)} km away via road.`;
});
}
// Initial call to get user location when page loads
getUserLocation();