source: main/trunk/greenstone3/web/interfaces/default/js/map-scripts.js@ 33129

Last change on this file since 33129 was 33129, checked in by wy59, 5 years ago

With a hierarchical classifier, when the node is expanded to reveal the document underneath it, the markers for the doc are now also red (instead of blue as in previous commit). This way it works more like in the sense of the ImagesGPS collection, though that didn't have hierarchical classifiers.

  • Property svn:executable set to *
File size: 28.0 KB
Line 
1//var newLat, newLng = 0;
2var _docList = new Array();
3_docList.ids = new Array();
4_docList.getDocByIndex = function(index)
5{
6 return _docList[_docList.ids[index]];
7};
8
9var _map;
10var _intervalHandle;
11var _baseURL = document.URL.substring(0, document.URL.indexOf("?") + 1);
12var _retrievedClassifiers = new Array();
13var _preventLoopingSingleMarker = false;
14var _searchRunning = false;
15var _nearbyDocs = new Array();
16var _scrollThroughDefault = true;
17
18function initializeMapScripts()
19{
20 modifyFunctions();
21 setUpMap();
22
23 var jsonNodeDiv = $("#jsonNodes");
24 if(jsonNodeDiv.length)
25 {
26 //console.log("@@@ JSON node div html: " + jsonNodeDiv.html());
27 var jsonNodes = eval(jsonNodeDiv.html());
28
29 if(jsonNodes && jsonNodes.length > 0)
30 {
31 for(var i = 0; i < jsonNodes.length; i++)
32 {
33 _docList[jsonNodes[i].nodeID] = jsonNodes[i];
34 _docList.ids.push(jsonNodes[i].nodeID);
35 createMarkers(jsonNodes[i], true);
36 }
37 updateMap();
38 }
39 else
40 {
41 //hiding the map
42 //$("#map_canvas").css({visibility:"hidden", height:"0px"});
43 $("#map_canvas").css({visibility:"hidden"}); // if you comment this out, add a log message saying "suppressing hiding map"
44 }
45 }
46
47 _docList.loopIndex = 0;
48
49 if(_docList.ids.length > 1)
50 {
51 var startStopCheckbox = $("<input>", {"type": "checkbox", "checked": _scrollThroughDefault, "id": "scrollCheckbox"});
52 startStopCheckbox.click(function()
53 {
54 // http://stackoverflow.com/questions/901712/how-to-check-if-a-checkbox-is-checked-in-jquery
55 // http://stackoverflow.com/questions/5270689/attrchecked-checked-does-not-work
56
57 if($('#scrollCheckbox').is(':checked')) // OR: if(document.getElementById('scrollCheckbox').checked)
58 {
59 if(_intervalHandle == null)
60 {
61 _intervalHandle = setInterval(loopThroughMarkers, 2000);
62 }
63 }
64 else
65 {
66 clearInterval(_intervalHandle);
67 _intervalHandle = null;
68 }
69 });
70
71 var label = $("<span>Scroll through places</span>");
72 var container = $("<div>", {"class": "ui-widget-header ui-corner-all", "style": "clear:right; float:right; padding:0px 5px 3px 0px;"});
73 container.append(startStopCheckbox);
74 container.append(label);
75
76 $(container).insertAfter("#map_canvas");
77
78 if (_scrollThroughDefault) {
79 _intervalHandle = setInterval(loopThroughMarkers, 2000);
80 }
81
82 }
83}
84
85function setUpMap()
86{
87 //alert("@@@@in map-scripts::setUpMap()");
88
89 var myOptions =
90 {
91 zoom: 2,
92 center: new google.maps.LatLng(0, 0),
93 mapTypeId: google.maps.MapTypeId.HYBRID
94 };
95 var $map_canvas = $("#map_canvas");
96
97 if ($map_canvas.length > 0) {
98 _map = new google.maps.Map($map_canvas[0], myOptions);
99 google.maps.event.addListener(_map, 'bounds_changed', performSearchForMarkers);
100 }
101}
102
103function performSearchForMarkers()
104{
105 if(_searchRunning)
106 {
107 return;
108 }
109
110
111
112 _searchRunning = true;
113
114 var bounds = _map.getBounds();
115
116 var neLat = bounds.getNorthEast().lat();
117 var neLng = bounds.getNorthEast().lng();
118 var swLat = bounds.getSouthWest().lat();
119 var swLng = bounds.getSouthWest().lng();
120
121 var latDistance = neLat - swLat;
122 var lngDistance = neLng - swLng;
123
124 //Check which increment to use for latitude (i.e. 0.001, 0.01, 0.1 or 1 degree increments)
125 var latDelta;
126 var latPrecision;
127 for(var i = 3; i >= 0; i--)
128 {
129 latDelta = (1 / Math.pow(10, i));
130 if((latDistance / latDelta) <= 5 || latDelta == 1)
131 {
132 latPrecision = i;
133 break;
134 }
135 }
136
137 //Check which increment to use for longitude (i.e. 0.001, 0.01, 0.1 or 1 degree increments)
138 var lngDelta;
139 for(var i = 3; i >= 0; i--)
140 {
141 lngDelta = (1 / Math.pow(10, i));
142 if((lngDistance / lngDelta) <= 5 || lngDelta == 1)
143 {
144 lngPrecision = i;
145 break;
146 }
147 }
148
149 if(latDelta == 0.1){latDelta = 1; latPrecision = 0; }
150 if(lngDelta == 0.1){lngDelta = 1; lngPrecision = 0; }
151
152 /*
153 var query = "";
154 for(var i = 0; i <= Math.floor(latDistance / latDelta) + 1; i++)
155 {
156 for(var j = 0; j <= Math.floor(lngDistance / lngDelta) + 1; j++)
157 {
158 //Some necessary variables
159 var newLat = neLat - (latDelta * i);
160 var newLatString = "" + newLat;
161 var newLatTrunc;
162 if(newLat < 0){newLatTrunc = Math.ceil(newLat);}
163 else{newLatTrunc = Math.floor(newLat);}
164
165 var newLng = neLng - (lngDelta * j);
166 var newLngString = "" + newLng;
167 var newLngTrunc;
168 if(newLng < 0){newLngTrunc = Math.ceil(newLng);}
169 else{newLngTrunc = Math.floor(newLng);}
170
171 //Construct query
172 query += "(";
173 query += "LA:" + coordToAbsDirected(newLatTrunc, "lat");
174 if(latDelta != 1)
175 {
176 query += "+AND+";
177 query += "LA:" + newLatString.substring(newLatString.indexOf(".") + 1, newLatString.indexOf(".") + latPrecision + 1);
178 }
179 query += "+AND+";
180 query += "LN:" + coordToAbsDirected(newLngTrunc, "lng");
181 if(lngDelta != 1)
182 {
183 query += "+AND+";
184 query += "LN:" + newLngString.substring(newLngString.indexOf(".") + 1, newLngString.indexOf(".") + lngPrecision + 1);
185 }
186 query += ")";
187
188 if(i != (Math.floor(latDistance / latDelta) + 1) || j != (Math.floor(lngDistance / lngDelta) + 1)){ query += "+OR+"; }
189 }
190 }
191 */
192 var query = "";
193 var iMax = Math.floor(latDistance / latDelta) + 1;
194 var jMax = Math.floor(lngDistance / lngDelta) + 1;;
195 for(var i = 0; i <= iMax; i++) //for(var i = 0; i <= Math.floor(latDistance / latDelta) + 1; i++)
196 {
197 for(var j = 0; j <= jMax; j++) //for(var j = 0; j <= Math.floor(lngDistance / lngDelta) + 1; j++)
198 {
199 //Some necessary variables
200 var newLat = neLat - (latDelta * i);
201 var newLatString = "" + newLat;
202 var newLatTrunc;
203 if(newLat < 0){newLatTrunc = Math.ceil(newLat);}
204 else{newLatTrunc = Math.floor(newLat);}
205
206 var newLng = neLng - (lngDelta * j);
207 var newLngString = "" + newLng;
208 var newLngTrunc;
209 if(newLng < 0){newLngTrunc = Math.ceil(newLng);}
210 else{newLngTrunc = Math.floor(newLng);}
211
212 //Construct query
213 query += "(";
214 query += "CS:\"" + coordToAbsDirected(newLatTrunc, "lat");
215 //query += "CS:\"" + coordToAbsDirected(newLatTrunc, "lat") + "\" \"" + coordToAbsDirected(newLngTrunc, "lng") + "\""; //query += "LA:" + coordToAbsDirected(newLatTrunc, "lat");
216 if(latDelta != 1)
217 {
218 query += newLatString.substring(newLatString.indexOf(".") + 1, newLatString.indexOf(".") + latPrecision + 1);
219 }
220 query += " ";
221 //query += "+AND+";
222
223 //query += "LN:" + coordToAbsDirected(newLngTrunc, "lng");
224 query += coordToAbsDirected(newLngTrunc, "lng");
225 if(lngDelta != 1)
226 {
227 query += newLngString.substring(newLngString.indexOf(".") + 1, newLngString.indexOf(".") + lngPrecision + 1);
228 }
229 query += "\"";
230 query += ")";
231
232 //if(i != (Math.floor(latDistance / latDelta) + 1) || j != (Math.floor(lngDistance / lngDelta) + 1)){ query += "+OR+"; }
233 if(i != iMax || j != jMax){ query += "+OR+"; }
234 }
235 }
236
237 // This works, why not from the double loop above?
238 //query = "(CS:\"" + coordToAbsDirected(newLatTrunc, "lat") + " " + coordToAbsDirected(newLngTrunc, "lng") + "\")";
239 //alert("@@@@in map-scripts::performSearchForMarkers() - query: " + query);
240
241 //var url = gs.xsltParams.library_name + "?a=q&s=RawQuery&rt=rd&c=" + gs.cgiParams.c + "&s1.rawquery=" + query + "&excerptid=jsonNodes";
242 var url = gs.xsltParams.library_name;
243 var data = "a=q&s=RawQuery&rt=rd&c=" + gs.cgiParams.c + "&s1.rawquery=" + query + "&excerptid=jsonNodes";
244 $.ajax({type:"POST", url:url, data:data})
245 .success(function(responseText)
246 {
247 //console.log("*** responseText (first 250) = " + responseText.substring(0,256));
248
249 if(responseText.search("id=\"jsonNodes") != -1)
250 {
251 var startIndex = responseText.indexOf(">");
252 var endIndex = responseText.indexOf("</");
253
254 //console.log("@@@@ performSearch, got response: " + responseText);
255
256 var jsonNodes = eval(responseText.substring(startIndex+1, endIndex));
257 if(jsonNodes && jsonNodes.length > 0)
258 {
259 for(var i = 0; i < jsonNodes.length; i++)
260 {
261 var doc = jsonNodes[i];
262
263 var found = false;
264 for(var j = 0; j < _docList.ids.length; j++){if(doc.nodeID == _docList.ids[j]){found = true; break;}}
265
266 if(!found)
267 {
268 _docList[doc.nodeID] = doc;
269 _docList.ids.push(doc.nodeID);
270
271 createMarkers(doc, false);
272 }
273 }
274 }
275 }
276 else
277 {
278 console.log("No JSON information received");
279 }
280
281 _searchRunning = false;
282 }).fail(function(responseText, textStatus, errorThrown) // fail() has replaced error(), http://api.jquery.com/jquery.ajax/
283 {
284 console.log("In map-scripts.performSearchForMarkers(): Got an error in ajax call");
285 _searchRunning = false;
286 });
287}
288
289function coordToAbsDirected(coord, type)
290{
291 var value = "" + coord;
292 if(coord < 0)
293 {
294 value = value.substring(1);
295 if(type == "lat")
296 {
297 value += "S";
298 }
299 else
300 {
301 value += "W";
302 }
303 }
304 else
305 {
306 if(type == "lat")
307 {
308 value += "N";
309 }
310 else
311 {
312 value += "E";
313 }
314 }
315
316 return value;
317}
318
319function updateMap()
320{
321 var markersOnMap = 0;
322 var bounds = new google.maps.LatLngBounds();
323 for(var i = 0; i < _docList.ids.length; i++)
324 {
325 var doc = _docList.getDocByIndex(i);
326 if(doc.parentCL && doc.parentCL.style.display == "none")
327 {
328 doc.marker.setVisible(false);
329 continue;
330 }
331 else
332 {
333 doc.marker.setVisible(true);
334 markersOnMap++;
335 }
336
337
338 if(doc.coords) {
339 for(var x = 0; x < doc.coords.length; x++) {
340 var coord = doc.coords[x];
341 var coordInfo = getLatLngForCoord(doc.coords[x]);
342 bounds.extend(new google.maps.LatLng(coordInfo.lat, coordInfo.lng));
343 }
344 }
345 else {
346 bounds.extend(new google.maps.LatLng(doc.lat, doc.lng));
347 }
348 }
349
350 if(markersOnMap > 1)
351 {
352 _map.fitBounds(bounds);
353 } else if (markersOnMap == 1) {
354 // sometimes a single point bounds are too small for the map to display, so use center and zoom instead of fitbounds.
355 _map.setCenter(bounds.getCenter());
356 _map.setZoom(18); // arbitrary value that looked nice for my example
357 }
358}
359
360function getLatLngForCoord(coord) {
361
362 // https://stackoverflow.com/questions/2559318/how-to-check-for-an-undefined-or-null-variable-in-javascript
363 if(!coord) {
364 // some_variable is either null, undefined, 0, NaN, false, or an empty string
365 console.log("@@@@ In map-scripts::getLatLngForCoord(): no or invalid coord info");
366 return null;
367 }
368
369 // coord is of the form: "37S77 157E53"
370 // lat will be 37S77, lng 157E53.
371 var indexOfSpace = coord.indexOf(" ");
372 if(indexOfSpace === -1) {
373 console.log("@@@@ In map-scripts::getLatLngForCoord(): bad format for coord " + coord);
374 return null;
375 }
376 var latitude = coord.substring(0, indexOfSpace);
377 var longitude = coord.substring(indexOfSpace+1);
378 return {lat: latitude, lng: longitude}; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
379}
380
381function loopThroughMarkers()
382{
383 if(_docList.ids.length == 0)
384 {
385 return;
386 }
387
388 var visibleMarkers = new Array();
389 for(var i = 0; i < _docList.ids.length; i++)
390 {
391 var doc = _docList.getDocByIndex(i);
392 if(doc.marker.getVisible())
393 {
394 visibleMarkers.push(doc);
395 }
396 }
397
398 if(visibleMarkers.length < 2)
399 {
400 clearAllInfoBoxes();
401 return;
402 }
403
404 clearAllInfoBoxes();
405
406 var elem = null;
407 while(!elem)
408 {
409 if(_docList.loopIndex >= visibleMarkers.length)
410 {
411 _docList.loopIndex = 0;
412 }
413
414 var doc = visibleMarkers[_docList.loopIndex];
415 var elem = gs.jqGet("div" + doc.nodeID);
416 if(elem.length)
417 {
418 elem.css("background", "#BBFFBB");
419 setTimeout(function(){elem.css("background", "");}, 2000);
420 }
421 _docList.loopIndex++;
422 }
423 doc.marker.markerInfo.open(_map, doc.marker);
424}
425
426function attachClickHandler(marker, nodeID)
427{
428 google.maps.event.addListener(marker, 'click', function()
429 {
430 document.location.href = gs.xsltParams.library_name + "?a=d&ed=1&c=" + gs.cgiParams.c + "&d=" + nodeID + "&dt=hierarchy&p.a=b&p.sa=&p.s=ClassifierBrowse";
431
432 });
433
434 if (("docEdit" in gs.cgiParams) && (gs.cgiParams['docEdit'])) {
435 google.maps.event.addListener(marker, 'mouseup', function()
436 {
437 var lat = marker.getPosition().lat();
438 var lng = marker.getPosition().lng();
439 var collection = gs.cgiParams.c;
440 var site_name = gs.xsltParams.site_name;
441
442 if (nodeID == "") {
443 nodeID = gs.cgiParams.d;
444 }
445 console.log("GPS Click handler in collection:" + collection + " in site: " + site_name + " for Doc: " + nodeID + "(" + lat + "," + lng + ")");
446
447 var callbackFunction = function(){console.log("Completed saving metadata changes. You must rebuild the collection for the changes to take effect.");};
448
449 // set 5th parameter, metapos (metadata position) or 7th param prevMetaValue (previous metadata value) to non-null if you want metamode=override to work
450 // if neither of these 2 are set, then metamode is changed to 'accumulate' instead.
451 gs.functions.setArchivesMetadata(collection, site_name, nodeID, "Latitude", null, lat, null, "override", function(){callbackFunction();});
452 gs.functions.setArchivesMetadata(collection, site_name, nodeID, "Longitude", null, lng, null, "override", function(){callbackFunction();});
453 gs.functions.setArchivesMetadata(collection, site_name, nodeID, "Coordinate", null, lat + " " + lng, null, "override", function(){callbackFunction();});
454 console.log("NodeID: " + nodeID);
455 console.log("GPS Click handler in collection:" + collection + " in site: " + site_name + " for Doc: " + nodeID + "(" + lat + "," + lng + ")");
456 });
457 }
458}
459
460function focusDocument(id)
461{
462 var doc = _docList[id];
463 if(doc)
464 {
465 clearInterval(_intervalHandle);
466 _intervalHandle = null;
467 if(doc.coords) {
468 for(var x = 0; x < doc.coords.length; x++) {
469 var coord = doc.coords[x];
470 var coordInfo = getLatLngForCoord(doc.coords[x]);
471 _map.panTo(new google.maps.LatLng(coordInfo.lat, coordInfo.lng));
472 }
473 } else {
474 _map.panTo(new google.maps.LatLng(doc.lat, doc.lng));
475 }
476 clearAllInfoBoxes();
477 doc.marker.markerInfo.open(_map, doc.marker);
478 var scrollCheckbox = $("#scrollCheckbox");
479 if(scrollCheckbox.checked)
480 {
481 scrollCheckbox.checked = false;
482 }
483 }
484}
485
486function clearAllInfoBoxes()
487{
488 for(var i = 0; i < _docList.ids.length; i++)
489 {
490 var doc = _docList.getDocByIndex(i);
491 doc.marker.markerInfo.close();
492 }
493}
494
495function createMarkers(doc, mainMarker) {
496 if(doc.coords) {
497 for(var x = 0; x < doc.coords.length; x++) {
498 var coord = doc.coords[x];
499 var coordInfo = getLatLngForCoord(doc.coords[x]);
500 pos = new google.maps.LatLng(coordInfo.lat,coordInfo.lng);
501 createMarker(doc, pos, mainMarker);
502 }
503 } else {
504 pos = new google.maps.LatLng(doc.lat,doc.lng);
505 createMarker(doc, pos, mainMarker);
506 }
507}
508
509
510// Param mainMarker: if set to true, marker is red. If false, marker is blue
511function createMarker(doc, pos, mainMarker)
512{
513 var docEdit = (("docEdit" in gs.cgiParams) && (gs.cgiParams['docEdit']));
514 //var draggable_val = (docEdit) ? true : false;
515
516 // When user logs out, the very first page they're returned to has logout set
517 // If the user logged out when leaving docEdit on, then the very first page has docEdit=1 AND logout.
518 // In that case, don't allow editing. Subsequent pages in logged out mode have neither logout nor docEdit=1 set.
519 var loggedOutVar = ("logout" in gs.cgiParams);
520
521 // Don't allow dragging if either 1. docEdit not on OR 2. logout is in the cgiParams
522 var draggable_val = (!docEdit || loggedOutVar) ? false : true;
523
524 var marker
525 if(mainMarker)
526 {
527 marker = new google.maps.Marker
528 ({
529 position: pos,
530 title:doc.title,
531 map:_map,
532 draggable: draggable_val
533 });
534 }
535 else
536 {
537 marker = new google.maps.Marker
538 ({
539 position: pos,
540 title:doc.title,
541 map:_map,
542 icon:"interfaces/" + gs.xsltParams.interface_name + "/images/bluemarker.png",
543 draggable: draggable_val
544 });
545 }
546
547 var docElement = gs.jqGet("div" + doc.nodeID);
548 var parent;
549 if(docElement)
550 {
551 parent = docElement.parentNode;
552 }
553
554 while(parent && parent.nodeName != "BODY")
555 {
556 if($(parent).attr("id") && $(parent).attr("id").search("divCL") != -1)
557 {
558 doc.parentCL = parent;
559 break;
560 }
561
562 parent = parent.parentNode;
563 }
564
565 var info = new google.maps.InfoWindow({content:doc.title});
566 marker.markerInfo = info;
567 doc.marker = marker;
568 attachClickHandler(marker, doc.nodeID);
569
570 ////////////////////////////////////////////////////// TEST
571
572 newLat = marker.getPosition().lat();
573 newLng = marker.getPosition().lng();
574 //console.log("Latitude " + newLat);
575 //console.log("Longitude " + newLng);
576 //NewLatLng(newLat, newLng);
577
578// // Define the LatLng coordinates for the polygon's path.
579// var triangleCoords = [
580// {lat: 18.774, lng: -80.190},
581// {lat: 18.466, lng: -64.600},
582// {lat: 32.321, lng: -64.757},
583// {lat: 32.300, lng: -80.190},
584// {lat: 28.300, lng: -90.190}
585// ];
586//
587// // Construct the polygon.
588// var bermudaTriangle = new google.maps.Polygon({
589// paths: triangleCoords,
590// strokeColor: '#FF0000',
591// strokeOpacity: 0.8,
592// strokeWeight: 2,
593// fillColor: '#FF0000',
594// fillOpacity: 0.35
595// });
596// bermudaTriangle.setMap(map);
597}
598
599function NewLatLng(lat, lng)
600{
601 console.log("Latitude " + lat);
602 console.log("Longitude " + lng);
603}
604
605function getSubClassifier(sectionID)
606{
607 var url = gs.xsltParams.library_name + "?a=b&rt=s&s=ClassifierBrowse&c=" + gs.cgiParams.c + "&cl=" + sectionID + "&excerptid=jsonNodes";
608 $.ajax(url)
609 .success(function(responseText)
610 {
611 var startIndex = responseText.indexOf(">");
612 var endIndex = responseText.indexOf("</");
613
614 var jsonNodes = eval(responseText.substring(startIndex+1, endIndex));
615 if(jsonNodes && jsonNodes.length > 0)
616 {
617 for(var i = 0; i < jsonNodes.length; i++)
618 {
619 var doc = jsonNodes[i];
620 _docList[doc.nodeID] = doc;
621 _docList.ids.push(doc.nodeID);
622
623 createMarkers(doc, true);
624 }
625
626 $("#map_canvas").css({"visibility": "visible", "height": ""});
627 }
628
629 updateMap();
630 })
631 .error(function()
632 {
633 console.log("Error getting subclassifiers");
634 return;
635 });
636}
637
638function performDistanceSearchWithCoordinates(id, coord, degrees)
639{
640 var coordInfo = getLatLngForCoord(coord);
641 if(!coordInfo) {
642 console.log("@@@ ERROR in map-scripts::performDistanceSearchWithCoordinates: coordInfo is null");
643 }
644 performDistanceSearch(id, coordInfo.lat, coordInfo.lng, degrees);
645}
646
647function performDistanceSearch(id, lat, lng, degrees)
648{
649 if(parseFloat(lat) > 180 || parseFloat(lat) < -180 || parseFloat(lng) > 180 || parseFloat(lat) < -180)
650 {
651 console.log("Latitude or longitude incorrectly formatted");
652 return;
653 }
654
655 if(lat.indexOf(".") == -1 || lng.indexOf(".") == -1 || (lat.indexOf(".") + 3) >= lat.length || (lng.indexOf(".") + 3) >= lng.length)
656 {
657 console.log("Latitude or longitude does not have the required precision for a distance search");
658 return;
659 }
660
661 var query = "";
662 for(var i = 0; i < degrees * 2; i++)
663 {
664 for (var j = 0; j < degrees * 2; j++)
665 {
666 var latDelta = (i - degrees) * 0.01;
667 var lngDelta = (j - degrees) * 0.01;
668
669 query += "(" + getDistanceQueryString(lat, latDelta, 2, "LA", ["N","S"]);
670 query += "+AND+";
671 query += getDistanceQueryString(lng, lngDelta, 2, "LN", ["E","W"]) + ")";
672
673 if(i != ((degrees * 2) - 1) || j != ((degrees * 2) - 1)){ query += "+OR+"; }
674 }
675 }
676
677 var inlineTemplate = '\
678 <xsl:template match="/" priority="5">\
679 <table id="nearbyDocs">\
680 <tr>\
681 <th><a href="javascript:sortByDistance();">Distance</a></th><th><a href="javascript:sortAlphabetically();">Document</a></th>\
682 </tr>\
683 <xsl:apply-templates select="//documentNode"/>\
684 </table>\
685 </xsl:template>\
686 \
687 <xsl:template match="documentNode" priority="5">\
688 <xsl:if test="@nodeID !=\''+id+'\'">\
689 <tr>\
690 <td>___<gsf:metadata name="Latitude"/>______<gsf:metadata name="Longitude"/>___</td>\
691 <td><gsf:link title="'+gs.text.doc.nearby_doc_tooltip+'" type="document"><gsf:metadata name="Title"/></gsf:link></td>\
692 </tr>\
693 </xsl:if>\
694 </xsl:template>';
695
696 var url = gs.xsltParams.library_name + "?a=q&s=RawQuery&rt=rd&c=" + gs.cgiParams.c + "&s1.rawquery=" + query + "&excerptid=nearbyDocs&ilt=" + inlineTemplate.replace(/ /, "%20");
697 $.ajax(url)
698 .success(function(response)
699 {
700 response = response.replace(/<img src="[^"]*map_marker.png"[^>]*>/g, "");
701
702 var nearbyDocsArray = new Array();
703
704 var lats = new Array();
705 var lngs = new Array();
706 var matches = response.match(/___(-?[0-9\.]*)___/g);
707 for(var i = 0; i < matches.length; i += 2)
708 {
709 var matchLatFloat = parseFloat(matches[i].replace("___", ""));
710 var matchLngFloat = parseFloat(matches[i+1].replace("___", ""));
711
712 lats.push(matchLatFloat);
713 lngs.push(matchLngFloat);
714 var distance = Math.sqrt(Math.pow(matchLatFloat - parseFloat(lat), 2) + Math.pow(matchLngFloat - parseFloat(lng), 2)) * (40000.0/360.0);
715 var distanceString = "" + distance;
716 distanceString = distanceString.substring(0, 6);
717 response = response.replace(matches[i] + matches[i+1], distanceString);
718 }
719
720 var index = 0;
721 var i = 0;
722 while(true)
723 {
724 var distanceStart = response.indexOf("<td>", index);
725 if(distanceStart == -1)
726 {
727 break;
728 }
729 var distanceEnd = response.indexOf("</td>", distanceStart);
730
731 var docLinkStart = response.indexOf("<td>", distanceEnd);
732 var docLinkEnd = response.indexOf("</td>", docLinkStart);
733
734 var dist = response.substring(distanceStart + 4, distanceEnd);
735 var docLink = response.substring(docLinkStart + 4, docLinkEnd);
736
737 _nearbyDocs.push({title:docLink, distance:dist, lat:lats[i], lng:lngs[i++]});
738
739 index = docLinkEnd;
740 }
741
742 sortByDistance(lat,lng);
743
744 var toggle = $("#nearbyDocumentsToggle");
745 toggle.attr("src", gs.imageURLs.collapse);
746 gs.functions.makeToggle(toggle, $("#nearbyDocuments"));
747 });
748}
749
750var map_centering_timeout = null;
751function recenterMapF(lat, lng)
752{
753 return function() {
754 _map.setCenter(new google.maps.LatLng(lat, lng));
755 }
756}
757function recenterMap(lat, lng)
758{
759
760 _map.setCenter(new google.maps.LatLng(lat, lng));
761
762}
763function sortByDistance(base_lat,base_lng)
764{
765 var sortedTable = '<table id="nearbyDocs" onmouseleave="clearTimeout(map_centering_timeout); recenterMap('+base_lat+','+base_lng+');"><tr><th><a href="javascript:;">Distance</a></th><th><a href="javascript:sortAlphabetically('+base_lat+', '+base_lng+');">Document</a></th></tr>';
766 _nearbyDocs.sort(function(a, b){return (a.distance - b.distance);});
767 for(var i = 0; i < _nearbyDocs.length; i++)
768 {
769
770 sortedTable += "<tr><td>" + prettifyDistance(_nearbyDocs[i].distance) + '</td><td onmouseover="clearTimeout(map_centering_timeout); map_centering_timeout = setTimeout(recenterMapF(' + _nearbyDocs[i].lat + ',' + _nearbyDocs[i].lng + '), 900)" >' + _nearbyDocs[i].title + "</td></tr>";
771 }
772 sortedTable += "</table>";
773
774 $("#nearbyDocuments").html(sortedTable);
775}
776function prettifyDistance(distance) {
777
778 var new_distance;
779 if (distance < 1) {
780 new_distance = (distance * 1000);
781 // Round to nearest whole number - don't need to show points of metres..
782 new_distance = Math.round(new_distance);
783 new_distance += " m";
784 }
785 else {
786 new_distance = distance +" km";
787
788 }
789 return new_distance;
790}
791
792
793
794function sortAlphabetically(base_lat, base_lng)
795{
796 var sortedTable = '<table id="nearbyDocs" onmouseleave="clearTimeout(map_centering_timeout); recenterMap('+base_lat+','+base_lng+');"><tr><th><a href="javascript:sortByDistance('+base_lat+', '+base_lng+');">Distance</a></th><th><a href="javascript:;">Document</a></th></tr>';
797 _nearbyDocs.sort(function(a, b)
798 {
799 var firstTitleStartIndex = a.title.indexOf(">");
800 var firstTitleEndIndex = a.title.indexOf("<", firstTitleStartIndex);
801 var firstTitle = a.title.substring(firstTitleStartIndex + 1, firstTitleEndIndex);
802 var secondTitleStartIndex = b.title.indexOf(">");
803 var secondTitleEndIndex = b.title.indexOf("<", secondTitleStartIndex);
804 var secondTitle = b.title.substring(secondTitleStartIndex + 1, secondTitleEndIndex);
805 return ((firstTitle.toLowerCase() == secondTitle.toLowerCase()) ? 0 : ((firstTitle.toLowerCase() > secondTitle.toLowerCase()) ? 1 : -1));
806 });
807 for(var i = 0; i < _nearbyDocs.length; i++)
808 {
809 sortedTable += "<tr><td>" + _nearbyDocs[i].distance + '</td><td onmouseover="clearTimeout(map_centering_timeout); map_centering_timeout = setTimeout(recenterMapF(' + _nearbyDocs[i].lat + ',' + _nearbyDocs[i].lng + '), 900)">' + _nearbyDocs[i].title + "</td></tr>";
810 }
811 sortedTable += "</table>";
812
813 $("#nearbyDocuments").html(sortedTable);
814}
815
816function getDistanceQueryString(currentCoord, delta, precision, indexName, dirs)
817{
818 var query = "";
819 var coordFloat = parseFloat(currentCoord);
820
821 var newCoord = "" + (coordFloat + delta);
822 var beforeDec = newCoord.substring(0, newCoord.indexOf("."));
823
824 var dir = dirs[0];
825 if(coordFloat < 0)
826 {
827 dir = dirs[1];
828 beforeDec = beforeDec.substring(1);
829 }
830 beforeDec += dir;
831
832 var afterDec = newCoord.substring(newCoord.indexOf(".") + 1, newCoord.indexOf(".") + (precision) + 1);
833
834 return indexName + ":" + beforeDec + "+AND+" + indexName + ":" + afterDec;
835}
836
837function modifyFunctions()
838{
839 // This function "overrides" toggleSection in both classifier_scripts.js and document_scripts.js
840 // However, classifier_scripts.js::toggleSection() only took one parameter, sectionID, whereas
841 // document_scripts.js::toggleSection() took 3 params (sectionID, callback, tocDisabled).
842 // So to be compatible with both, need map-scripts::toggleSection() here to support all 3 in that order.
843 toggleSection = function(sectionID, callback, tocDisabled)
844 {
845 _basicToggleSection(sectionID, callback, tocDisabled);
846
847 var section = gs.jqGet("div" + sectionID);
848 var sectionToggle = gs.jqGet("toggle" + sectionID);
849
850 if(sectionToggle == undefined)
851 {
852 return;
853 }
854
855 // Test if 'section' exists.
856 // ==> Because we're using jQuery to do this we need to test the length of the object returned
857 // http://stackoverflow.com/questions/920236/how-can-i-detect-if-a-selector-returns-null
858 if(section.length !== 0)
859 {
860 if(isExpanded(sectionID))
861 {
862 section.css("display", "none");
863 sectionToggle.attr("src", gs.imageURLs.expand);
864
865 if(openClassifiers[sectionID].length !== 0) //if(openClassifiers[sectionID] != undefined)
866 {
867 delete openClassifiers[sectionID];
868 }
869 }
870 else
871 {
872 section.css("display", "block");
873 sectionToggle.attr("src", gs.imageURLs.collapse);
874 openClassifiers[sectionID] = true;
875 }
876 updateOpenClassifiers();
877 updateMap();
878 }
879 else
880 {
881 httpRequest(sectionID);
882 }
883
884 }
885
886 httpRequest = function(sectionID)
887 {
888 if(!inProgress[sectionID])
889 {
890 inProgress[sectionID] = true;
891
892 var sectionToggle = gs.jqGet("toggle" + sectionID);
893 sectionToggle.attr("src", gs.imageURLs.loading);
894
895 var url = gs.xsltParams.library_name + "/collection/" + gs.cgiParams.c + "/browse/" + sectionID.replace(/\./g, "/") + "?excerptid=div" + sectionID;
896
897 if(gs.cgiParams.berrybasket == "on")
898 {
899 url = url + "&berrybasket=on";
900 }
901
902 if(url.indexOf("#") != -1)
903 {
904 url = url.substring(0, url.indexOf("#"));
905 }
906
907 $.ajax(url)
908 .success(function(responseText)
909 {
910 var newDiv = $("<div>");
911 var sibling = gs.jqGet("title" + sectionID);
912 sibling.after(newDiv);
913
914 newDiv.html(responseText);
915 sectionToggle.attr("src", gs.imageURLs.collapse);
916 openClassifiers[sectionID] = true;
917
918 if(gs.cgiParams.berrybasket == "on")
919 {
920 checkout();
921 }
922 /*else if(gs.cgiParams.documentbasket == "on") // TODO: copied from classifier_scripts.js - should this else block be included here (and happen when mapEnabled) or not?
923 {
924 dmcheckout();
925 }*/
926 updateOpenClassifiers();
927 getSubClassifier(sectionID);
928 })
929 .error(function()
930 {
931 sectionToggle.attr("src", gs.imageURLs.expand);
932 })
933 .complete(function()
934 {
935 inProgress[sectionID] = false;
936 busy = false;
937 });
938 }
939 }
940}
Note: See TracBrowser for help on using the repository browser.