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

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

2 single changes before major commit. 1. map-scripts.js: Bugfix, no longer referencing a var that does not exist. 2. classifier_scripts.js: Removing unused variable.

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