-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmapScript.js
326 lines (285 loc) · 9.45 KB
/
mapScript.js
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
require('dotenv').config();
let map;
let my_latitude, my_longitude;
let markersArray = [];
let userMarkersArray = [];
let new_icon;
let directionsRenderer;
const apiKey = process.env.GOOGLE_MAPS_API_KEY;
const mapId = process.env.MAP_ID;
import { interest_locations } from './initialLocationsInitializer.js';
import { hotels } from './hotelLocationsInitializer.js';
import { restaurants } from './restaurantLocationsInitializer.js';
import { waterfalls } from './waterfallLocationsInitializer.js';
async function initMap()
{
let mohawkloc = { lat: 43.2387, lng: -79.8881 };
map = new google.maps.Map(document.getElementById("map"),
{
center: mohawkloc,
zoom: 12,
mapId: mapId,
});
setInitialMarkers();
}
function setInitialMarkers()
{
for(let i = 0; i < interest_locations.length; i++)
{
let place = interest_locations[i];
new_icon = "http://maps.google.com/mapfiles/kml/paddle/red-blank.png";
getCoordinatesAndSetMarker(place, new_icon);
}
}
function setHotelMarkers()
{
for(let i = 0; i < hotels.length; i++)
{
let hotel = hotels[i];
new_icon = "http://maps.google.com/mapfiles/kml/paddle/ylw-blank.png";
getCoordinatesAndSetMarker(hotel, new_icon);
}
}
function setRestaurantMarkers()
{
for(let i = 0; i < restaurants.length; i++)
{
let restaurant = restaurants[i];
new_icon = "http://maps.google.com/mapfiles/kml/paddle/blu-blank.png";
getCoordinatesAndSetMarker(restaurant, new_icon);
}
}
function setWaterfallMarkers()
{
for(let i = 0; i < waterfalls.length; i++)
{
let waterfall = waterfalls[i];
new_icon = "http://maps.google.com/mapfiles/kml/paddle/grn-blank.png";
getCoordinatesAndSetMarker(waterfall, new_icon);
}
}
function getCoordinatesAndSetMarker(place, new_icon, isUserMarker = false)
{
const cityLocation = ", Hamilton, ON";
const actualLocation = (place.name !== undefined && place.name !== null) ? place.name : place;
const geoCodeURL = generateGeocodeURL(actualLocation, cityLocation);
fetchCoordinates(geoCodeURL)
.then(location => {
const marker = createMarker(location, actualLocation, new_icon);
if(isUserMarker)
{
userMarkersArray.push(marker);
}
else
{
markersArray.push(marker);
}
setupMarkerClickListener(marker, place);
})
.catch(error => console.error('Error fetching data:', error));
}
function generateGeocodeURL(name, cityLocation)
{
return `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(name + cityLocation)}&key=${apiKey}`;
}
function fetchCoordinates(geoCodeURL)
{
return fetch(geoCodeURL)
.then(response => response.json())
.then(data => {
if (data.status === 'OK')
{
return data.results[0].geometry.location;
}
else
{
throw new Error(`Geocode failed with status: ${data.status}`);
}
});
}
function createMarker(location, place, new_icon)
{
const icon_content = document.createElement("img");
icon_content.src = new_icon;
return new google.maps.marker.AdvancedMarkerElement({
map: map,
position: location,
title: place.name,
content: icon_content
});
}
function setupMarkerClickListener(marker, place)
{
const contentString = generateInfoWindowContent(place);
const infowindow = new google.maps.InfoWindow({ content: contentString });
marker.addListener("click", function () {
infowindow.open({
anchor: marker,
map: map,
shouldFocus: false,
});
const markerLatLng = getMarkerLatLng(marker);
console.log("Latitude: ", markerLatLng.latitude);
console.log("Longitude: ", markerLatLng.longitude);
updateInfoWindowUI(place, markerLatLng);
});
}
function getMarkerLatLng(marker) {
const latitude = marker.position.lat;
const longitude = marker.position.lng;
return { latitude, longitude };
}
function generateInfoWindowContent(place)
{
return `
<h6>${place.name}</h6>
<p>${place.content}</p>
<p><strong>Address:</strong> ${place.address}</p>
<p><strong>Phone:</strong> ${place.phone}</p>
<p><strong>Email:</strong> <a href="mailto:${place.email}">${place.email}</a></p>
`;
}
function getDirection(destLat, destLng)
{
console.log("in getDirection 1: ",destLat);
console.log("in getDirection 2: ",destLng);
navigator.geolocation.getCurrentPosition(function(position) {
const my_location = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
traceRoute(my_location, { lat: destLat, lng: destLng });
}, showError);
}
function traceRoute(origin, destination) {
const directionsService = new google.maps.DirectionsService();
if(directionsRenderer)
{
directionsRenderer.setMap(null);
}
directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);
const request = {
origin: origin,
destination: destination,
travelMode: 'DRIVING' // travel modes: WALKING, BICYCLING
};
directionsService.route(request, function(result, status) {
if (status === 'OK')
{
directionsRenderer.setDirections(result);
console.log("Directions traced successfully!", result);
}
else
{
console.error("Failed to retrieve directions: " + status);
}
});
}
function updateInfoWindowUI(place, markerLatLng)
{
console.log("in updateInfoWindowUI: ", markerLatLng.latitude, markerLatLng.longitude);
document.getElementById("infowindow").innerHTML = `
<div class="infowindow-image-container">
<img src="${place.image}" alt="${place.name}" class="infowindow-image" style="width: 100%; max-height: 200px; object-fit: cover; margin-bottom: 10px;">
</div>
<h5 class="card-title infowindow-font-format"><strong>${place.name}</strong></h5>
<p class="card-text infowindow-font-format">${place.content}</p>
<p class="infowindow-font-format"><strong>Address:</strong> ${place.address}</p>
<p class="infowindow-font-format"><strong>Phone:</strong> ${place.phone}</p>
<p class="infowindow-font-format"><strong>Email:</strong> <a href="mailto:${place.email}">${place.email}</a></p>
<button class="btn btn-primary-route" id="get-directions">Get Directions</button>
`;
document.getElementById('get-directions').addEventListener("click", function() {
getDirection(markerLatLng.latitude, markerLatLng.longitude);
});
}
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
else
{
window.alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position)
{
my_latitude = position.coords.latitude;
my_longitude = position.coords.longitude;
let my_location = {lat: my_latitude, lng: my_longitude};
const my_location_marker = new google.maps.Marker({
map,
position: my_location,
title: "You are here",
icon: {
url: "http://maps.google.com/mapfiles/kml/shapes/ranger_station.png"
}
});
}
function showError(error)
{
switch (error.code)
{
case error.PERMISSION_DENIED:
window.alert("User denied the request for Geolocation.")
break;
case error.POSITION_UNAVAILABLE:
window.alert("Location information is unavailable.")
break;
case error.TIMEOUT:
window.alert("The request to get user location timed out.")
break;
case error.UNKNOWN_ERROR:
window.alert("An unknown error occurred.")
break;
}
}
function removeMarkers(array)
{
for(let i = 0; i < array.length; i++)
{
array[i].map = null;
}
}
window.initMap = initMap;
document.getElementById("add_hotels").addEventListener("click", function(){
removeMarkers(markersArray);
markersArray = [];
setHotelMarkers();
});
document.getElementById("add_restaurants").addEventListener("click", function(){
removeMarkers(markersArray);
markersArray = [];
setRestaurantMarkers();
});
document.getElementById("add_waterfalls").addEventListener("click", function(){
removeMarkers(markersArray);
markersArray = [];
setWaterfallMarkers();
});
document.getElementById("add_my_location").addEventListener("click", function(){
getLocation();
});
document.getElementById("find_my_address").addEventListener("click", function(){
let address = document.getElementById("floatingInput").value;
if(address != "")
{
removeMarkers(userMarkersArray);
userMarkersArray = [];
console.log("in the event ", address);
let icon = "http://maps.google.com/mapfiles/kml/shapes/ranger_station.png";
getCoordinatesAndSetMarker(address, icon, true);
document.getElementById("floatingInput").value = "";
}
else
{
window.alert("Enter an address to place the marker on the map.");
}
});
window.getDirection = getDirection;
window.addEventListener('resize', () => {
google.maps.event.trigger(map, "resize");
});