source: tmcsimulator/branches/realtime_VDS/cptms/js/vdsLayer.js @ 606

Revision 606, 7.5 KB checked in by jdalbey, 6 years ago (diff)

realtimeVDS fix code smells in vdsLayer.js

Line 
1    // Build a solid colored icon to use instead of the classic pin
2    function dotSymbol(color) 
3    {
4        var iconPath = iconVDSwhite;
5        if (color == 'red')
6        {
7           iconPath = iconVDSred;
8        }
9        else if (color == 'yellow')
10        {
11            iconPath = iconVDSyellow;
12        }
13        else if (color == 'lime')
14        {
15            iconPath = iconVDSgreen;
16        }
17        return {
18            url: iconPath, 
19            anchor: new google.maps.Point(6, 6)
20        };
21    }
22
23    // Load the map data from a json file and style all the points
24    function loadVDSlayer()
25    {
26        // Load the static map data and call saveCoords when done
27        map.data.loadGeoJson(kMapStartupFile, null, saveCoords)
28        // Style the map data by applying the desired properties to each feature (marker)
29        // The function will be called every time a feature's properties are updated.
30        map.data.setStyle(function(feature)
31        {
32            // Get the postmile id
33            var name = feature.getId();
34            // Get the desired color value
35            var ptColor = feature.getProperty("color");
36            var street = feature.getProperty("street");
37            // Build the marker
38            var iconSymbol = dotSymbol(ptColor);
39            // return the StyleOptions
40            return {
41                icon: iconSymbol,
42                title: name + " @" + street, // set rollover text
43                // set zIndex for slowed traffic to a higher value so they overlap
44                zIndex: colorZvalues[ptColor]
45            };
46        });
47    }
48    // callback when load GeoJson completes
49    // save each feature's Point as the original coordinates for later reference
50    function saveCoords(features)
51    {
52        // Iterate over all the features in the map
53        features.forEach(function(feature)
54        {
55            var pt = feature.getGeometry().get();
56            vds_coords[feature.getId()] = pt; // save the Point in a dictionary
57        });
58        // update the dot colors from the dynamic json data
59        updateVDSlayer();
60        // go adjust the marker coordinates so dots don't overlap
61        adjustCoords(calcDistanceFactor());
62    }
63
64    // magic formula controls distance between dots proportionate to zoom factor
65    function calcDistanceFactor()
66    {
67        // 15 is maximum zoom, the point at which no adjustment is needed
68        return (.0005 * (15 - map.getZoom()));
69    }
70
71    // Adjust the coordinates of dots so they appear side-by-side
72    // The perpendicular vector for each dot has been provided,
73    // so we just need to multiply by a scaling factor (adjAmount)
74    // @param adjAmount amount by which to adjust coordinate
75    function adjustCoords(adjAmount)
76    {
77        // Adjust the NB points a slight amount
78        map.data.forEach(function(feature)
79        {
80            // get the name of the current feature
81            var name = feature.getId();
82            // lookup the original coordinates for this feature
83            var coords = vds_coords[name];
84
85            //retrieve the perpendicular vector (precomputed)
86            var perpx = feature.getProperty("perpx")
87            var perpy = feature.getProperty("perpy")
88                // Make adjustment and save it
89            var myLat = coords.lat() + perpy * adjAmount
90            var myLong = coords.lng() + perpx * adjAmount
91            feature.setGeometry(
92            {
93                lat: myLat,
94                lng: myLong
95            });
96        });
97    }
98
99    // update the color (as needed) for a given marker
100    function updateMarker(marker)
101    {
102        target = marker.id;
103        newColor = marker.properties.color;
104        // see if new color is different than current color
105        currentFeature = map.data.getFeatureById(target);
106        currentColor = currentFeature.getProperty("color");
107        // if a new color is desired then assign it to the feature's color property
108        if (currentColor != newColor)
109        {
110            currentFeature.setProperty("color", newColor);
111            // set zIndex for slowed traffic to a higher value so they overlap
112            currentFeature.setProperty("zIndex", colorZvalues[newColor]);
113        }
114    }
115
116
117    // Load the highways dynamic json file and update the map
118    function updateVDSlayer()
119    {
120        var parsed_JSON;
121        loadJSON(kVDSstatusFile, function(response)
122        {
123            // Parse JSON string into object
124            parsed_JSON = JSON.parse(response);
125            // Process each new marker - lookup in current map
126            parsed_JSON.features.forEach(updateMarker);
127        });
128    }
129
130function initVDSbutton()
131{
132
133    var vdsBtnDiv = document.getElementById('vdsButton');
134    map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(vdsBtnDiv)
135    vdsBtnDiv.title = 'Click to toggle vds view';
136
137    // Setup the click event listeners to toggle icon display
138    vdsBtnDiv.addEventListener('click', function()
139    {
140        vds_showing = !vds_showing;
141        // reveal or hide all the dots
142        map.data.forEach(function(feature)
143        {
144            map.data.overrideStyle(feature,
145            {
146                visible: vds_showing
147            });
148        });
149        // Determine which button image to show
150        if (vds_showing)
151        {
152            pic = "images/btnDepressed_VDS.png"
153        }
154        else
155        {
156            pic = "images/btnReady_VDS.png"
157        }
158        document.getElementById('vdsBtnImg').src = pic;
159    });
160}
161
162//initialize live indicator icon
163function initLiveIcon(success) {
164    // if fetch is a success, display live img
165    var indicator = document.createElement('img');
166    if (success) 
167    {
168        //create new img tags for live and not-live indicators
169        indicator.src ="images/live.svg";
170        indicator.width = 50 ;
171        indicator.height= 40 ;
172    }
173    else
174    {
175        indicator.src ="images/offline.jpg";
176    }
177    if (map.controls[google.maps.ControlPosition.TOP_RIGHT].getLength() > 0)
178            map.controls[google.maps.ControlPosition.TOP_RIGHT].pop();
179    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(indicator);
180}
181
182//reads first line on last fetch file and checks if its less than 15 minutes old
183function checkLastFetch()
184{
185    var rawFile = new XMLHttpRequest();
186    rawFile.open("GET", lastFetchFile, true);
187    rawFile.onreadystatechange = function ()
188    {
189        if(rawFile.readyState === 4)
190        {
191            if(rawFile.status === 200 || rawFile.status == 0)
192            {
193                var text = rawFile.responseText;
194                // get last fetch time from file
195                var lastFetch = new Date(text);
196                // get current date time
197                var now = new Date();
198                // calculate time difference
199                var timeDiff = new Date(now - lastFetch);
200                var msec = now - lastFetch;
201                var days = Math.floor(msec / 1000 / 60 / (60 * 24));
202                msec -= days * 1000 * 60 * 60 * 24
203                var hh = Math.floor(msec / 1000 / 60 / 60);
204                msec -= hh * 1000 * 60 * 60;
205                var mm = Math.floor(msec / 1000 / 60);
206                msec -= mm * 1000 * 60;
207                var ss = Math.floor(msec / 1000);
208                msec -= ss * 1000;
209                // display icon if less than 15
210               if (days === 0 && hh === 0 && mm < liveThreshold)
211                    initLiveIcon(1)
212                else 
213                    initLiveIcon(0)
214                //console.log(days + " Days "+ hh + " Hours " + mm + " Minutes " + ss + " Seconds ");
215            }
216        }
217    }
218    rawFile.send(null);
219}
Note: See TracBrowser for help on using the repository browser.