-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmap.html
437 lines (385 loc) · 16.6 KB
/
map.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
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Map</title>
<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css" />
<script src="https://js.api.here.com/v3/3.1/mapsjs-core.js"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-service.js"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-ui.js"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js"></script>
<link rel="stylesheet" href="main.css">
<link rel="icon" href="logo.png">
<link href="https://fonts.googleapis.com/css2?family=Alegreya+Sans:ital@1&display=swap" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<div id="map"></div>
<div id="panel"></div>
<div id="map__form">
<div class="contact-form">
<form>
<div>
<label>
<input id="origin" type="text" placeholder="Enter your starting point" required>
<span>Enter your starting point</span>
</label>
</div>
<div>
<label>
<input id="destination" type="text" placeholder="Enter your destination point" required>
<span>Enter your destination point</span>
</label>
</div>
<!-- <input id="origin" type="text" placeholder="Enter your starting point">
<input id="destination" type="text" placeholder="Enter your destination point"> -->
<div><input type="button" value="Show Me Route" onclick="getLocationDetails()"></div>
</form>
</div>
</div>
<div class="distance">
Duration : <span id="year"></span> Hrs<br><br>
Distance : <span id="year2"></span> Kms
</div>
<!-- <script src="script.js"></script> -->
<script>
function calculateRouteFromAtoB(
platform,
originLat,
originLon,
destinationLat,
destinationLon
) {
var router = platform.getRoutingService(null, 8),
routeRequestParams = {
routingMode: "fast",
transportMode: "car",
origin: originLat + "," + originLon,
destination: destinationLat + "," + destinationLon,
return: "polyline,turnByTurnActions,actions,instructions,travelSummary",
};
router.calculateRoute(routeRequestParams, onSuccess, onError);
}
// /**
// * This function will be called once the Routing REST API provides a response
// * @param {Object} result A JSONP object representing the calculated route
// *
// * see: http://developer.here.com/rest-apis/documentation/routing/topics/resource-type-calculate-route.html
// */
var dur;
var dis;
function onSuccess(result) {
var route = result.routes[0];
console.log(route);
function round(num, dec) {
const [sv, ev] = num.toString().split('e');
return Number(Number(Math.round(parseFloat(sv + 'e' + dec)) + 'e-' + dec) + 'e' + (ev || 0));
}
window.dur = round((route.sections[0].travelSummary.duration) / 3600, 2);
window.dis = round((route.sections[0].travelSummary.length) / 1000, 2);
/*
* The styling of the route response on the map is entirely under the developer's control.
* A representitive styling can be found the full JS + HTML code of this example
* in the functions below:
*/
addRouteShapeToMap(route);
addManueversToMap(route);
addWaypointsToPanel(route);
addManueversToPanel(route);
addSummaryToPanel(route);
// ... etc.
}
// /**
// * This function will be called if a communication error occurs during the JSON-P request
// * @param {Object} error The error message received.
// */
function onError(error) {
alert("Can't reach the remote server");
}
// /**
// * Boilerplate map initialization code starts below:
// */
// // set up containers for the map + panel
var mapContainer = document.getElementById("map"),
routeInstructionsContainer = document.getElementById("panel");
// //Step 1: initialize communication with the platform
// // In your own code, replace variable window.apikey with your own apikey
var platform = new H.service.Platform({
apikey: "8j2a68P55bGbQmuKNsT08BlTea8EZ15TdTYTwVqMOI0",
});
var defaultLayers = platform.createDefaultLayers();
// //Step 2: initialize a map - this map is centered over Berlin
var map = new H.Map(mapContainer, defaultLayers.vector.normal.map, {
center: { lat: 52.516, lng: 13.3779 },
zoom: 13,
pixelRatio: window.devicePixelRatio || 1,
});
// // add a resize listener to make sure that the map occupies the whole container
window.addEventListener("resize", () => map.getViewPort().resize());
// //Step 3: make the map interactive
// // MapEvents enables the event system
// // Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// // Create the default UI components
var ui = H.ui.UI.createDefault(map, defaultLayers);
// // Hold a reference to any infobubble opened
var bubble;
// /**
// * Opens/Closes a infobubble
// * @param {H.geo.Point} position The location on the map.
// * @param {String} text The contents of the infobubble.
// */
function openBubble(position, text) {
if (!bubble) {
bubble = new H.ui.InfoBubble(
position,
// The FO property holds the province name.
{ content: text }
);
ui.addBubble(bubble);
} else {
bubble.setPosition(position);
bubble.setContent(text);
bubble.open();
}
}
// /**
// * Creates a H.map.Polyline from the shape of the route and adds it to the map.
// * @param {Object} route A route as received from the H.service.RoutingService
// */
function addRouteShapeToMap(route) {
route.sections.forEach((section) => {
// decode LineString from the flexible polyline
let linestring = H.geo.LineString.fromFlexiblePolyline(section.polyline);
// Create a polyline to display the route:
let polyline = new H.map.Polyline(linestring, {
style: {
lineWidth: 4,
strokeColor: "rgba(0, 128, 255, 0.7)",
},
});
// // Add the polyline to the map
map.addObject(polyline);
// // And zoom to its bounding rectangle
map.getViewModel().setLookAtData({
bounds: polyline.getBoundingBox(),
});
});
}
// /**
// * Creates a series of H.map.Marker points from the route and adds them to the map.
// * @param {Object} route A route as received from the H.service.RoutingService
// */
function addManueversToMap(route) {
var svgMarkup =
'<svg width="18" height="18" ' +
'xmlns="http://www.w3.org/2000/svg">' +
'<circle cx="8" cy="8" r="8" ' +
'fill="#1b468d" stroke="white" stroke-width="1" />' +
"</svg>",
dotIcon = new H.map.Icon(svgMarkup, { anchor: { x: 8, y: 8 } }),
group = new H.map.Group(),
i,
j;
route.sections.forEach((section) => {
let poly = H.geo.LineString.fromFlexiblePolyline(
section.polyline
).getLatLngAltArray();
let actions = section.actions;
// Add a marker for each maneuver
for (i = 0; i < actions.length; i += 1) {
let action = actions[i];
var marker = new H.map.Marker(
{
lat: poly[action.offset * 3],
lng: poly[action.offset * 3 + 1],
},
{ icon: dotIcon }
);
marker.instruction = action.instruction;
group.addObject(marker);
}
group.addEventListener(
"tap",
function (evt) {
map.setCenter(evt.target.getGeometry());
openBubble(evt.target.getGeometry(), evt.target.instruction);
},
false
);
// // Add the maneuvers group to the map
map.addObject(group);
});
}
// /**
// * Creates a series of H.map.Marker points from the route and adds them to the map.
// * @param {Object} route A route as received from the H.service.RoutingService
// */
function addWaypointsToPanel(route) {
var nodeH3 = document.createElement("h3"),
labels = [];
route.sections.forEach((section) => {
labels.push(section.turnByTurnActions[0].nextRoad.name[0].value);
labels.push(
section.turnByTurnActions[section.turnByTurnActions.length - 1]
.currentRoad.name[0].value
);
});
nodeH3.textContent = labels.join(" - ");
routeInstructionsContainer.innerHTML = "";
routeInstructionsContainer.appendChild(nodeH3);
}
// /**
// * Creates a series of H.map.Marker points from the route and adds them to the map.
// * @param {Object} route A route as received from the H.service.RoutingService
// */
function addSummaryToPanel(route) {
let duration = 0,
distance = 0;
route.sections.forEach((section) => {
distance += section.travelSummary.length;
duration += section.travelSummary.duration;
});
var summaryDiv = document.createElement("div"),
content = "";
content += "<b>Total distance</b>: " + distance + "m. <br/>";
content +=
"<b>Travel Time</b>: " + duration.toMMSS() + " (in current traffic)";
summaryDiv.style.fontSize = "small";
summaryDiv.style.marginLeft = "5%";
summaryDiv.style.marginRight = "5%";
summaryDiv.innerHTML = content;
routeInstructionsContainer.appendChild(summaryDiv);
}
// /**
// * Creates a series of H.map.Marker points from the route and adds them to the map.
// * @param {Object} route A route as received from the H.service.RoutingService
// */
function addManueversToPanel(route) {
var nodeOL = document.createElement("ol");
nodeOL.style.fontSize = "small";
nodeOL.style.marginLeft = "5%";
nodeOL.style.marginRight = "5%";
nodeOL.className = "directions";
route.sections.forEach((section) => {
section.actions.forEach((action, idx) => {
var li = document.createElement("li"),
spanArrow = document.createElement("span"),
spanInstruction = document.createElement("span");
spanArrow.className = "arrow " + (action.direction || "") + action.action;
spanInstruction.innerHTML = section.actions[idx].instruction;
li.appendChild(spanArrow);
li.appendChild(spanInstruction);
nodeOL.appendChild(li);
});
});
routeInstructionsContainer.appendChild(nodeOL);
}
Number.prototype.toMMSS = function () {
return Math.floor(this / 60) + " minutes " + (this % 60) + " seconds.";
};
// //MY Location Function
function getCoordintes() {
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0,
};
function success(pos) {
var crd = pos.coords;
var lat = crd.latitude.toString();
var lng = crd.longitude.toString();
var coordinates = [lat, lng];
addAnswer(
Main,
"Your Latitude is <br><b>" + lat + " </b>Longitude<br><b>" + lng
);
getCity(coordinates);
return;
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
navigator.geolocation.getCurrentPosition(success, error, options);
}
// // Step 2: Get Country name
function getCity(coordinates) {
var xhr = new XMLHttpRequest();
var lat = coordinates[0];
var lng = coordinates[1];
xhr.open(
"GET",
"https://us1.locationiq.com/v1/reverse.php?key=pk.e61de8f8675accd3fd88866e1f92e31b&lat=" +
lat +
"&lon=" +
lng +
"&format=json",
true
);
xhr.send();
xhr.onreadystatechange = processRequest;
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var city = response.address.country;
addAnswer(Main, "Your City is <br> <b>" + city);
return;
}
}
}
// //Get origin and destination for map
async function getLocationDetails() {
$("#map__form").css("display", "none");
origin = document.getElementById("origin").value;
destination = document.getElementById("destination").value;
$.ajax({
url: "http://api.positionstack.com/v1/forward",
data: {
access_key: "83e725837df6ea6bafe0a9d495ad800f",
query: origin,
limit: 1,
},
}).done(function (data) {
originLat = data.data[0].latitude;
originLon = data.data[0].longitude;
console.log(originLat);
console.log(originLon);
});
$.ajax({
url: "http://api.positionstack.com/v1/forward",
data: {
access_key: "83e725837df6ea6bafe0a9d495ad800f",
query: destination,
limit: 1,
},
}).done(function (data) {
destinationLat = data.data[0].latitude;
destinationLon = data.data[0].longitude;
console.log(destinationLat);
console.log(destinationLon);
});
setTimeout(function () {
calculateRouteFromAtoB(
platform,
originLat,
originLon,
destinationLat,
destinationLon
);
}, 4000);
setTimeout(function () {
console.log(destinationLat);
console.log(originLat);
console.log(originLon);
console.log(destinationLon);
}, 2000);
setTimeout(function () {
document.getElementById('year').innerHTML = dur;
document.getElementById('year2').innerHTML = dis;
}, 10000);
}
</script>
</body>
</html>