-
Notifications
You must be signed in to change notification settings - Fork 5
/
map.js
82 lines (67 loc) · 1.67 KB
/
map.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
var config = require('./config');
var URL = config.url;
var markers = [];
var _map;
var isMapInitialized = false;
var isIntervalSetted = false;
function computeCenter(positions) {
if (positions.length == 0) {
return 0;
}
var latitude = 0;
var longitude = 0;
for (var i = 0; i < positions.length; i++) {
var position = positions[i];
latitude += position.lat;
longitude += position.lon;
}
latitude /= positions.length;
longitude /= positions.length;
return {lat: latitude, lng: longitude};
}
function initMap() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var positions = JSON.parse(xhttp.responseText);
var cntr = computeCenter(positions);
if (isMapInitialized === false) {
_map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: cntr
});
isMapInitialized = true;
} else {
_map.setCenter(cntr);
}
deleteMarkers();
for (var i = 0; i < positions.length; i++) {
var position = positions[i];
addMarker(position);
}
}
};
xhttp.open('GET', URL + '/locations');
xhttp.send();
if (isIntervalSetted === false) {
setInterval(initMap, 1000);
isIntervalSetted = true;
}
}
function clearMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
function deleteMarkers() {
clearMarkers();
markers = [];
}
function addMarker(pos) {
var marker = new google.maps.Marker({
position: {lat: pos.lat, lng: pos.lon},
map: _map
//title: pos.id
});
markers.push(marker);
}