source: tmcsimulator/trunk/webapps/visualizer/js/vdsLayer.js @ 528

Revision 528, 10.5 KB checked in by jdalbey, 6 years ago (diff)

Visualizer - add Back button functionality

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    function storePrev(marker, targetMarkers) 
117    {
118        target = marker.id;
119        newColor = marker.properties.color;
120        // see if new color is different than current color
121        currentFeature = map.data.getFeatureById(target);
122        currentColor = currentFeature.getProperty("color");
123        // if a new color is desired then assign it to the feature's color property
124        if (currentColor != newColor)
125        {
126            targetMarkers.push({"id" : currentFeature.getId(),
127                "properties" : {"color" : currentColor}});
128        }
129    }
130
131    // Load the highways dynamic json file and update the map
132    function updateVDSlayer()
133    {
134        index = -1;
135        var parsed_JSON;
136        loadJSON(kVDSstatusFile, function(response)
137        {
138            // Parse JSON string into object
139            parsed_JSON = JSON.parse(response);
140            // Process each new marker - lookup in current map
141            parsed_JSON.features.forEach(updateMarker);
142        });
143    }
144
145    function getColorName(str){
146        if (str === "R\r" || str === "R")
147            return "red";
148        else if (str === "Y\r" || str === "Y")
149            return "yellow";
150        else if (str === "G\r" || str === "G")
151            return "lime";
152    }
153
154    function processVDS() {
155        var parsed_JSON;
156        loadJSON(kVDSstatusFile, function(response)
157        { 
158            // Parse JSON string into object
159            parsed_JSON = JSON.parse(response);
160            // Process each new marker - lookup in current map
161            var array =  parsed_JSON.features;
162            var txt = '';
163            var xmlhttp = new XMLHttpRequest();
164            xmlhttp.onreadystatechange = function(){
165                if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
166                    txt = xmlhttp.responseText;
167                    var lines = txt.toString().split("\n");
168                    for (var line = 1; line < lines.length; line++) {
169                        filters[line-1] = [];
170                        var event = lines[line].split(/[ ,]+/);
171                        var start = parseFloat(event[4]); // 7.73
172                        var range = parseFloat(event[5]); // 0.5
173                        var newColor = getColorName(event[6]); // "R"
174                        times.push(event[1]);
175                        array.forEach(function (marker) {
176                            var id_arr = marker.id.split(" ");
177                            if (id_arr[0] === event[2] && id_arr[1] === event[3]){
178                                var dist = parseFloat(id_arr[2]) - start; //difference of postmiles
179                                if (dist <= range && dist >= 0){
180                                    filters[line-1].push({"marker": marker, "color": newColor});
181                                }
182                            }
183                        });
184                    }
185                }
186            };
187            xmlhttp.open("GET",trafficEventsFile,true); //read traffic events text file
188            xmlhttp.send();
189        });
190    }
191     
192    // updates color for each marker based on color in filters array
193    function updateVDS(forwards) { 
194                if (forwards) {
195            index++;
196            if (index >= filters.length) 
197            {
198                index = filters.length - 1;
199            }
200            if  (filters[index] !== undefined) {
201                filters[index].forEach(function(item){
202                    item.marker.properties.color = item.color;
203                    updateMarker(item.marker);
204                });
205            }
206        }
207                else {
208            if  (diff_arr[index] !== undefined) {
209                diff_arr[index].forEach(function(item){
210                    updateMarker(item);
211                });
212            }
213            index--; 
214            if (index < -1)
215            {
216                index = -1;
217            }
218        }
219    }
220
221    function buildDiff() 
222    {
223        for (var i = 0; i <= filters.length; i++)
224        {
225            if  (filters[i] !== undefined)
226            {
227                var targetMarkers = new Array();
228                filters[i].forEach(function(item){
229                    item.marker.properties.color = item.color;
230                    storePrev(item.marker, targetMarkers);
231                    updateMarker(item.marker);
232                });
233                diff_arr.push(targetMarkers);
234            }
235        }
236    }
237
238function initVDSbutton()
239{
240
241    var vdsBtnDiv = document.getElementById('vdsButton');
242    map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(vdsBtnDiv)
243    vdsBtnDiv.title = 'Click to toggle vds view';
244
245    // Setup the click event listeners to toggle icon display
246    vdsBtnDiv.addEventListener('click', function()
247    {
248        vds_showing = !vds_showing;
249        // reveal or hide all the dots
250        map.data.forEach(function(feature)
251        {
252            map.data.overrideStyle(feature,
253            {
254                visible: vds_showing
255            });
256        });
257        // Determine which button image to show
258        if (vds_showing)
259        {
260            pic = "images/btnDepressed_VDS.png"
261        }
262        else
263        {
264            pic = "images/btnReady_VDS.png"
265        }
266        document.getElementById('vdsBtnImg').src = pic;
267    });
268}
269
270// init beginning and next buttons as well as time display on map
271function initForwardbutton()
272{
273    var i = 0;
274    var time = document.getElementById('time');
275    map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(time)
276    var start = document.getElementById('start');
277    map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(start)
278    start.title = 'Click to see the first event';
279    var forward = document.getElementById('forward');
280    map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(forward)
281        var backward = document.getElementById('backward');
282        map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(backward)
283    forward.title = 'Click to see the next event';
284    //console.log(diff_arr);
285    forward.addEventListener('click', function() {
286        updateVDS(1);
287        if (i < times.length - 1)
288        {
289            ++i;
290            time.innerHTML = times[i];
291        }
292    });
293        backward.addEventListener('click', function() {
294        updateVDS(0);
295        if (i > 0)
296        {
297            --i;
298            time.innerHTML = times[i];
299        }
300        });
301    start.addEventListener('click', function() {
302        updateVDSlayer();
303        i = 0;
304        time.innerHTML = "00:00:00";
305    });
306}
307
Note: See TracBrowser for help on using the repository browser.