source: tmcsimulator/trunk/webapps/GTEC/js/vdsLayer_tk1.js @ 556

Revision 556, 13.8 KB checked in by jdalbey, 6 years ago (diff)

Ver 0.1 of Graphic Traffic Events Creator.

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 initializeVDSlayer()
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        var clicked = false;
48        var first = [];
49        var asc = false;
50        var color_arr = [];
51        map.data.addListener('click', function(event) 
52        {
53            var event_arr = event.feature.getId().split(/[ ,]+/);
54            // var start = parseFloat(event[4]); // extract postmile field
55            if (clicked && event_arr[0] === first[0] && event_arr[1] === first[1])
56            {
57                // console.log('clicked ' + first + "/" + event_arr + event.feature);
58                var range = Math.abs(parseFloat(event_arr[2]) - parseFloat(first[2]));
59                var clicked_dots = [];
60                if (event_arr[2] < first[2])
61                {
62                    asc = false;
63                }
64                else 
65                {
66                    asc = true;
67                }
68                map.data.forEach(function (marker) 
69                {
70                    var marker_arr = marker.getId().split(/[ ,]+/);
71                    if (marker_arr[0] === event_arr[0] && marker_arr[1] === event_arr[1])
72                    {
73                        if (asc)
74                        {
75                            var dist = parseFloat(marker_arr[2]) - parseFloat(first[2]);
76                        }
77                        else 
78                        {
79                            var dist = parseFloat(parseFloat(first[2]) - (marker_arr[2]));
80                        }
81                        if (dist <= range && dist >= 0)
82                        {
83                            clicked_dots.push(marker);
84                        }
85                    }
86                });
87                color_arr.push(clicked_dots);
88                console.log(clicked_dots);
89                console.log(range);
90            }
91            else if (!clicked)
92            {
93                first = event_arr;
94            }
95            else 
96            {
97                console.log('wrong choice');
98            }
99            clicked = !clicked;
100
101        });
102    }
103    // callback when load GeoJson completes
104    // save each feature's Point as the original coordinates for later reference
105    function saveCoords(features)
106    {
107        // Iterate over all the features in the map
108        features.forEach(function(feature)
109        {
110            var pt = feature.getGeometry().get();
111            vds_coords[feature.getId()] = pt; // save the Point in a dictionary
112        });
113        // update the dot colors from the dynamic json data
114        updateVDSlayer();
115        // go adjust the marker coordinates so dots don't overlap
116        adjustCoords(calcDistanceFactor());
117    } 
118
119    // magic formula controls distance between dots proportionate to zoom factor
120    function calcDistanceFactor()
121    {
122        // 15 is maximum zoom, the point at which no adjustment is needed
123        return (.0005 * (15 - map.getZoom()));
124    }
125
126    // Adjust the coordinates of dots so they appear side-by-side
127    // The perpendicular vector for each dot has been provided,
128    // so we just need to multiply by a scaling factor (adjAmount)
129    // @param adjAmount amount by which to adjust coordinate
130    function adjustCoords(adjAmount)
131    {
132        // Adjust the NB points a slight amount
133        map.data.forEach(function(feature)
134        {
135            // get the name of the current feature
136            var name = feature.getId();
137            // lookup the original coordinates for this feature
138            var coords = vds_coords[name];
139
140            //retrieve the perpendicular vector (precomputed)
141            var perpx = feature.getProperty("perpx")
142            var perpy = feature.getProperty("perpy")
143                // Make adjustment and save it
144            var myLat = coords.lat() + perpy * adjAmount
145            var myLong = coords.lng() + perpx * adjAmount
146            feature.setGeometry(
147            {
148                lat: myLat,
149                lng: myLong
150            });
151        });
152    }
153
154    // update the color (as needed) for a given marker
155    function updateMarker(marker)
156    {
157        target = marker.id;
158        newColor = marker.properties.color;
159        // see if new color is different than current color
160        currentFeature = map.data.getFeatureById(target);
161        currentColor = currentFeature.getProperty("color");
162        // if a new color is desired then assign it to the feature's color property
163        if (currentColor != newColor)
164        {
165            currentFeature.setProperty("color", newColor);
166            // set zIndex for slowed traffic to a higher value so they overlap
167            currentFeature.setProperty("zIndex", colorZvalues[newColor]);
168        }
169    }
170
171    // Builds array to store the previous colors of the targetDots
172    /*function storePrev(marker, targetMarkers)
173    {
174        target = marker.id;
175        newColor = marker.properties.color;
176        // see if new color is different than current color
177        currentFeature = map.data.getFeatureById(target);
178        currentColor = currentFeature.getProperty("color");
179        // if a new color is desired then assign it to the feature's color property
180        if (currentColor != newColor)
181        {
182            targetMarkers.push({"id" : currentFeature.getId(),
183                "properties" : {"color" : currentColor}});
184        }
185    }*/
186
187    // Load the highways dynamic json file and update the map
188    function updateVDSlayer()
189    {
190        eventIndex = -1;
191        var parsed_JSON;
192        loadJSON(kVDSstatusFile, function(response)
193        {
194            // Parse JSON string into object
195            parsed_JSON = JSON.parse(response);
196            // Process each new marker - lookup in current map
197            parsed_JSON.features.forEach(updateMarker);
198        });
199    }
200
201    function getColorName(str){
202        if (str === "R\r" || str === "R")
203            return "red";
204        else if (str === "Y\r" || str === "Y")
205            return "yellow";
206        else if (str === "G\r" || str === "G")
207            return "lime";
208    }
209
210// Parses the traffic events file and builds an array of target dots for each line
211    /*function processVDS() {
212        var parsed_JSON;
213        loadJSON(kVDSstatusFile, function(response)
214        {
215            // Parse JSON string into object
216            parsed_JSON = JSON.parse(response);
217            // Process each new marker - lookup in current map
218            var parsed_features =  parsed_JSON.features;
219            var eventsFile = '';
220            var xmlhttp = new XMLHttpRequest();
221            xmlhttp.onreadystatechange = function(){
222                if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
223                    eventsFile = xmlhttp.responseText;
224                    var lines = eventsFile.toString().split("\n");
225                    for (var line = 1; line < lines.length; line++) {
226                        if (lines[line][0] !== '#') //ignores lines with #
227                        {
228                            var dots = [];
229                            var event = lines[line].split(/[ ,]+/);
230                            var start = parseFloat(event[4]); // extract postmile field
231                            var range = parseFloat(event[5]); // extract distance
232                            var newColor = getColorName(event[6]); // extract DotColor
233                            eventTimes.push(event[1]);
234                            parsed_features.forEach(function (marker) {
235                                var id_arr = marker.id.split(" ");
236                                if (id_arr[0] === event[2] && id_arr[1] === event[3]){
237                                    var dist = parseFloat(id_arr[2]) - start; //computes difference in postmiles
238                                    if (dist <= range && dist >= 0){ // adds all dots within computed range
239                                        dots.push({"marker": marker, "color": newColor});
240                                    }
241                                }
242                            });
243                            targetDots.push(dots);
244                        }
245                    }
246                }
247            };
248            xmlhttp.open("GET",trafficEventsFile,true); //read traffic events text file
249            xmlhttp.send();
250        });
251    }
252
253    // Increments the eventIndex from and updates all the targetDots on map
254    function updateForwards() {
255        eventIndex++;
256        // limit eventIndex to length of targetDots
257        if (eventIndex >= targetDots.length)
258        {
259            eventIndex = targetDots.length - 1;
260        }
261        // update all the target dots
262        if  (targetDots[eventIndex] !== undefined) {
263            targetDots[eventIndex].forEach(function(item){
264            item.marker.properties.color = item.color;
265            updateMarker(item.marker);
266            });
267        }
268    }
269
270    // Decrements the eventIndex and updates all the targetDots from diff_arr on map
271    function updateBackwards() {
272        //update each target dot in order to revert to previous color
273        if  (diff_arr[eventIndex] !== undefined) {
274            diff_arr[eventIndex].forEach(function(item){
275                updateMarker(item);
276            });
277        }
278        eventIndex--;
279        // restrict eventIndex to -1
280        if (eventIndex < -1)
281        {
282            eventIndex = -1;
283        }
284    }
285   
286    // Calls updateMarker for all targetDots after storing the previous marker in diff_arr
287    function buildDiff() {
288        for (var i = 0; i <= targetDots.length; i++)
289        {
290            if  (targetDots[i] !== undefined)
291            {
292                var targetMarkers = new Array();
293                targetDots[i].forEach(function(item){
294                    item.marker.properties.color = item.color;
295                    storePrev(item.marker, targetMarkers);
296                    updateMarker(item.marker);
297                });
298                diff_arr.push(targetMarkers);
299            }
300        }
301    }
302*/
303/*function initVDSbutton()
304{
305
306    var vdsBtnDiv = document.getElementById('vdsButton');
307    map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(vdsBtnDiv)
308    vdsBtnDiv.title = 'Click to toggle vds view';
309
310    // Setup the click event listeners to toggle icon display
311    vdsBtnDiv.addEventListener('click', function()
312    {
313        vds_showing = !vds_showing;
314        // reveal or hide all the dots
315        map.data.forEach(function(feature)
316        {
317            map.data.overrideStyle(feature,
318            {
319                visible: vds_showing
320            });
321        });
322        // Determine which button image to show
323        if (vds_showing)
324        {
325            pic = "images/btnDepressed_VDS.png"
326        }
327        else
328        {
329            pic = "images/btnReady_VDS.png"
330        }
331        document.getElementById('vdsBtnImg').src = pic;
332    });
333}*/
334
335// init beginning, forward and back buttons as well as time display on map
336function initControlButtons()
337{
338    var i = 0;
339    /*var time = document.getElementById('time');
340    map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(time)
341    var start = document.getElementById('start');
342    map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(start)
343    start.title = 'Click to see the first event';
344    var forward = document.getElementById('forward');
345    map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(forward)
346        var backward = document.getElementById('backward');
347        map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(backward)
348    forward.title = 'Click to see the next event';
349    forward.addEventListener('click', function() {
350        updateForwards();
351        backward.disabled = false;
352        if (i < eventTimes.length - 1) // get the next eventTime
353        {
354            ++i;
355            time.innerHTML = eventTimes[i];
356        }
357        if (eventIndex === targetDots.length - 1) // disable next button if last event reached
358        {
359            forward.disabled = true;
360        }
361    });
362        backward.addEventListener('click', function() {
363        updateBackwards();
364        forward.disabled = false;
365        if (i > 0)  // get the prev eventTime
366        {
367            --i;
368            time.innerHTML = eventTimes[i];
369        }
370        if (eventIndex < 0) // disable back button if at first event
371        {
372            backward.disabled = true;
373        }
374        });
375    start.addEventListener('click', function() {
376        updateVDSlayer(); // redraw markers on map from startup file
377        i = 0;
378        time.innerHTML = "00:00:00";
379    });*/
380}
381
Note: See TracBrowser for help on using the repository browser.