PageRenderTime 59ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/webportal/src/main/webapp/scripts/map3.js

http://alageospatialportal.googlecode.com/
JavaScript | 2383 lines | 1946 code | 304 blank | 133 comment | 370 complexity | c0b3dd5cb68dd23df2c67b218d8ca8ed MD5 | raw file
  1. /**
  2. * Instance of OpenLayers map
  3. */
  4. var map;
  5. var proxy_script="/webportal/RemoteRequest?url=";
  6. var tmp_response;
  7. var popup;
  8. var selectControl;
  9. var popupWidth = 435; //pixels
  10. var popupHeight = 370; //pixels
  11. var requestCount = 0; // getFeatureInfo request count
  12. var queries = new Object(); // current getFeatureInfo requests
  13. var queries_valid_content = false;
  14. var timestamp; // timestamp for getFeatureInfo requests
  15. var X,Y; // getfeatureInfo Click point
  16. var clickEventHandler; // single clickhandler
  17. var toolPanel; // container for OpenLayer controls
  18. var pan; // OpenLayers.Control.Navigation
  19. var zoom; // OpenLayers.Control.ZoomBox
  20. var areaToolsButton// OpenLayers.Control.Button
  21. //var selectableLayers = new Array();
  22. /**
  23. * Associative array of all current active map layers except
  24. * for baselayers
  25. */
  26. var mapLayers = new Object();
  27. /**
  28. * Associative array of all available base layers
  29. */
  30. var baseLayers = new Object();
  31. /**
  32. * Key of the currently selected base layer in baseLayers
  33. */
  34. var currentBaseLayer = null;
  35. var selectionLayers = new Array();
  36. var mapClickControl;
  37. var polyControl = null;
  38. var radiusControl = null; //for deactivate after drawing
  39. var boxControl = null; //for deactivate after drawing
  40. var areaSelectControl = null;
  41. var filteringPolygon = null; //temporary for destroy option after display
  42. var alocPolygon = null; //temporary for destroy option after display
  43. var polygonLayer = null;
  44. var boxLayer = null;
  45. var radiusLayer = null;
  46. var featureSelectLayer = null;
  47. var featureSpeciesSelectLayer = null;
  48. var areaSelectOn = false;
  49. var layersLoading = 0;
  50. var panoramioLoading = 0;
  51. var layername; // current layer name
  52. var attempts = 0;
  53. var libraryLoaded = false;
  54. var checkLibraryLoadedTimeout = null;
  55. var libraryCheckIntervalMs=100;
  56. var secondsToWaitForLibrary=30;
  57. var maxAttempts = (secondsToWaitForLibrary * 1000) / libraryCheckIntervalMs;
  58. var selecteFeature;
  59. // check if the Google Layer automatically got
  60. // switched between normal and hybrid around zoom level 16
  61. var autoBaseLayerSwitch = false;
  62. // 0 = normal
  63. // 1 = user-switch
  64. // 2 = auto-switch
  65. var baseLayerSwitchStatus = 0;
  66. var activeAreaPresent = false;
  67. var shownPicture = false;
  68. var shownPicturePopup = false;
  69. var vectorLayer;
  70. function stopCheckingLibraryLoaded() {
  71. clearInterval(checkLibraryLoadedTimeout);
  72. }
  73. function registerLayer(layer) {
  74. layer.events.register('loadstart', this, loadStart);
  75. layer.events.register('loadend', this, loadEnd);
  76. }
  77. function loadStart() {
  78. if (layersLoading == 0) {
  79. toggleLoadingImage("block");
  80. }
  81. layersLoading++;
  82. }
  83. function loadEnd() {
  84. layersLoading--;
  85. if (layersLoading == 0) {
  86. toggleLoadingImage("none");
  87. }
  88. //signal webportal
  89. }
  90. function toggleLoadingImage(display) {
  91. var div = document.getElementById("loader");
  92. if (div != null) {
  93. if (display == "none") {
  94. jQuery("#loader").hide(2000);
  95. }
  96. else {
  97. setTimeout(function(){
  98. if (layersLoading > 0) {
  99. div.style.display=display;
  100. }
  101. }, 2000);
  102. }
  103. }
  104. }
  105. function checkLibraryLoaded() {
  106. if (typeof OpenLayers == 'undefined') {
  107. if ((attempts < maxAttempts) && (typeof OpenLayers == 'undefined')) {
  108. attempts++;
  109. }
  110. else if (attempts == maxAttempts) {
  111. // give up loading - too many attempts
  112. stopCheckingLibraryLoaded();
  113. alert(
  114. "Map not loaded after waiting " + secondsToWaitForLibrary + " seconds. " +
  115. "Please wait a moment and then reload the page. If this does not fix your " +
  116. "problem, please contact ALA for assistance"
  117. );
  118. }
  119. }
  120. else {
  121. // library loaded OK stop delay timer
  122. stopCheckingLibraryLoaded();
  123. libraryLoaded = true;
  124. parent.updateSafeToLoadMap(libraryLoaded);
  125. // ok now init the map...
  126. parent.onIframeMapFullyLoaded();
  127. }
  128. }
  129. var bLayer,bLayer2,bLayer3,bLayer4;
  130. function loadBaseMap() {
  131. goToLocation(134, -25, 4);
  132. // Google.v3 uses EPSG:900913 as projection, so we have to
  133. // transform our coordinates
  134. // map.setCenter(
  135. // new OpenLayers.LonLat(134, -25).transform(
  136. // new OpenLayers.Projection("EPSG:4326"),
  137. // map.getProjectionObject()),
  138. // 4);
  139. // $(window).resize(function() {
  140. // setTimeout("map.pan(1,1);",500);
  141. // });
  142. }
  143. function goToLocation(lon, lat, zoom) {
  144. // Google.v3 uses EPSG:900913 as projection, so we have to
  145. // transform our coordinates
  146. map.setCenter(
  147. new OpenLayers.LonLat(lon, lat).transform(
  148. new OpenLayers.Projection("EPSG:4326"),
  149. map.getProjectionObject()),
  150. zoom);
  151. }
  152. function changeBaseLayer(type) {
  153. if (type == 'normal') {
  154. map.setBaseLayer(bLayer2);
  155. } else if (type == 'hybrid') {
  156. map.setBaseLayer(bLayer);
  157. } else if (type == 'minimal') {
  158. map.setBaseLayer(bLayer3);
  159. } else if (type == 'outline') {
  160. map.setBaseLayer(bLayer4);
  161. }
  162. }
  163. function buildMap() {
  164. checkLibraryLoadedTimeout = setInterval('checkLibraryLoaded()', libraryCheckIntervalMs);
  165. }
  166. function buildMapReal() {
  167. // fix IE7 errors due to being in an iframe
  168. document.getElementById('mapdiv').style.width = '100%';
  169. document.getElementById('mapdiv').style.height = '100%';
  170. // highlight for the scale and lonlat info
  171. $("div#mapinfo").hover( function(){$(this).css("opacity","0.9");}, function(){$(this).css("opacity","0.5");} );
  172. $("div#layervalues").hover( function(){$(this).css("opacity","0.9");}, function(){$(this).css("opacity","0.5");} );
  173. // proxy.cgi script provided by OpenLayers written in Python, must be on the same domain
  174. OpenLayers.ProxyHost = proxy_script;
  175. // ---------- map setup --------------- //
  176. var mapControls = [
  177. new OpenLayers.Control.PanZoomBar({
  178. div: document.getElementById('controlPanZoom')
  179. }),
  180. new OpenLayers.Control.LayerSwitcher(),
  181. new OpenLayers.Control.ScaleLine({
  182. div: document.getElementById('mapscale'),
  183. geodesic: true
  184. }),
  185. new OpenLayers.Control.Attribution(),
  186. new OpenLayers.Control.MousePosition({
  187. div: document.getElementById('mapcoords'),
  188. prefix: '<b>Lon:</b> ',
  189. separator: ' <BR><b>Lat:</b> '
  190. }),
  191. new OpenLayers.Control.Navigation()
  192. ];
  193. var mapOptions = {
  194. projection: new OpenLayers.Projection("EPSG:900913"),
  195. displayProjection: new OpenLayers.Projection("EPSG:4326"),
  196. units: "m",
  197. numZoomLevels: 18,
  198. maxResolution: 156543.0339,
  199. maxExtent: new OpenLayers.Bounds(-20037508, -20037508,
  200. 20037508, 20037508.34),
  201. controls: mapControls
  202. };
  203. map = new OpenLayers.Map('mapdiv', mapOptions);
  204. // make OL compute scale according to WMS spec
  205. OpenLayers.DOTS_PER_INCH = 25.4 / 0.28;
  206. // Stop the pink tiles appearing on error
  207. OpenLayers.Util.onImageLoadError = function() {
  208. this.style.display = "";
  209. this.src="img/blank.png";
  210. }
  211. bLayer = new OpenLayers.Layer.Google("Google Hybrid",
  212. {
  213. type: google.maps.MapTypeId.HYBRID,
  214. wrapDateLine: false,
  215. 'sphericalMercator': true
  216. });
  217. bLayer2 = new OpenLayers.Layer.Google("Google Streets",
  218. {
  219. wrapDateLine: false,
  220. 'sphericalMercator': true
  221. });
  222. bLayer3 = new OpenLayers.Layer.OSM();
  223. bLayer4 = new OpenLayers.Layer.WMS("Outline",parent.jq('$geoserver_url')[0].innerHTML + "/gwc/service/wms/reflect",{
  224. layers:"ALA:world"
  225. },
  226. {
  227. isBaseLayer: true,
  228. 'wrapDateLine': true,
  229. projection: new OpenLayers.Projection("EPSG:900913"),
  230. 'sphericalMercator': true
  231. }
  232. );
  233. map.addLayers([bLayer2,bLayer,bLayer3,bLayer4]);
  234. parent.bLayer = bLayer;
  235. parent.bLayer2 = bLayer2;
  236. parent.bLayer3 = bLayer3;
  237. parent.bLayer4 = bLayer4;
  238. loadBaseMap();
  239. //loadPanoramio();
  240. // create a new event handler for single click query
  241. clickEventHandler = new OpenLayers.Handler.Click({
  242. 'map': map
  243. }, {
  244. 'click': function(e) {
  245. //envLayerInspection(e);
  246. }
  247. });
  248. clickEventHandler.activate();
  249. clickEventHandler.fallThrough = true;
  250. // cursor mods
  251. map.div.style.cursor="pointer";
  252. jQuery("#navtoolbar div.olControlZoomBoxItemInactive ").click(function(){
  253. map.div.style.cursor="crosshair";
  254. clickEventHandler.deactivate();
  255. });
  256. jQuery("#navtoolbar div.olControlNavigationItemActive ").click(function(){
  257. map.div.style.cursor="pointer";
  258. clickEventHandler.activate();
  259. setVectorLayersSelectable();
  260. });
  261. map.events.register("moveend" , map, function (e) {
  262. parent.setExtent();
  263. if (shownPicture && !shownPicturePopup){
  264. removePanoramio(false);
  265. loadPanoramio(0,49);
  266. }
  267. Event.stop(e);
  268. });
  269. map.events.register("zoomend" , map, function (e) {
  270. Event.stop(e);
  271. //don't do change base layer if this is a 'print'
  272. if(parent.location.href.indexOf("?p=") < 0) {
  273. autoSwitchBaseMap();
  274. }
  275. });
  276. registerSpeciesClick();
  277. toggleActiveHover();
  278. }
  279. function autoSwitchBaseMap() {
  280. if (map.zoom > 15) {
  281. if (baseLayerSwitchStatus != 1) {
  282. baseLayerSwitchStatus = 2;
  283. changeBaseLayer('hybrid');
  284. }
  285. }
  286. else {
  287. if (baseLayerSwitchStatus == 2) {
  288. changeBaseLayer('normal');
  289. baseLayerSwitchStatus = 0;
  290. }
  291. }
  292. }
  293. var query_
  294. var query_layer
  295. var query_size
  296. var query_ui_forall = "";
  297. function iterateSpeciesInfoQuery(curr) {
  298. var pos = 0;
  299. var curpos = curr;
  300. while(curpos >= query_size[pos]) {
  301. curpos -= query_size[pos];
  302. pos += 1;
  303. }
  304. var nextBtn = " &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ";
  305. try {
  306. if (curr+1 < query_count_total) {
  307. nextBtn = "<a style='float: right' href='javascript:iterateSpeciesInfoQuery("+(curr+1)+");'><img src='img/arrow_right.png' /></a>"; // next &rArr;
  308. }
  309. } catch (err) {}
  310. var prevBtn = " &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ";
  311. try {
  312. if (curr > 0) {
  313. prevBtn = "<a href='javascript:iterateSpeciesInfoQuery("+(curr-1)+");'><img src='img/arrow_left.png' /></a>"; // &lArr; previous
  314. }
  315. } catch (err) {}
  316. var url = query_url[pos] + "&start=" + curpos;
  317. //alert(url);
  318. $.getJSON(proxy_script + URLEncode(url), function(data) {
  319. if (!query_layer[pos].bs) {
  320. var ulyr = query_[pos];
  321. var ulyr_occ_id = data.occurrences[0].id;
  322. var ulyr_occ_lng = data.occurrences[0].longitude;
  323. var ulyr_occ_lat = data.occurrences[0].latitude;
  324. var ulyr_meta = data.metadata;
  325. var data = ulyr_meta.replace(/_n_/g,"<br />");
  326. var heading = "<h2 class='z-label'>Occurrence information (" + (curr+1) + " of " + query_count_total + ")</h2>";
  327. if (query_count_total==1) {
  328. heading = "<h2>Occurrence information (1 occurrence)</h2>";
  329. }
  330. var infohtml = "<div id='sppopup2'> " +
  331. heading + "Record id: " + ulyr_occ_id + "<br /> " + data + " <br /> <br />" +
  332. " Longitude: "+ulyr_occ_lng + " , Latitude: " + ulyr_occ_lat + " (<a href='javascript:goToLocation("+ulyr_occ_lng+", "+ulyr_occ_lat+", 15);relocatePopup("+ulyr_occ_lng+", "+ulyr_occ_lat+");'>zoom to</a>) <br/>" +
  333. //" <input type='checkbox' checked='parent.isFlaggedRecord(\"" + ulyr + "\",\"" + ulyr_occ_id + "\")' onClick='parent.flagRecord(\"" + ulyr + "\",\"" + ulyr_occ_id + "\",this.checked)' />Assign record to <i>ad hoc</i> group<br/>" +
  334. "<div id=''>"+prevBtn+" &nbsp; &nbsp; &nbsp; &nbsp; "+nextBtn+"</div>";
  335. setTimeout(function(){
  336. if (document.getElementById("sppopup") != null) {
  337. document.getElementById("sppopup").innerHTML = infohtml;
  338. }
  339. }, 50);
  340. } else {
  341. displaySpeciesInfo(pos, data.occurrences[0], prevBtn, nextBtn, curr, query_count_total);
  342. }
  343. });
  344. }
  345. function iteratePointsOfInterest(curr) {
  346. var pos = curr;
  347. if (pos < 0) {
  348. pos = 0;
  349. }
  350. if (pos >= points_of_interest_total) {
  351. pos = points_of_interest_total - 1;
  352. }
  353. var nextBtn = " &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ";
  354. try {
  355. if (curr+1 < points_of_interest_total) {
  356. nextBtn = "<a style='float: right' href='javascript:iteratePointsOfInterest("+(curr+1)+");'><img src='img/arrow_right.png' /></a>"; // next &rArr;
  357. }
  358. } catch (err) {}
  359. var prevBtn = " &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ";
  360. try {
  361. if (curr > 0) {
  362. prevBtn = "<a href='javascript:iteratePointsOfInterest("+(curr-1)+");'><img src='img/arrow_left.png' /></a>"; // &lArr; previous
  363. }
  364. } catch (err) {}
  365. setTimeout(function() {
  366. displayPointOfInterest(pos, points_of_interest[pos], prevBtn, nextBtn, curr, points_of_interest_total);
  367. });
  368. }
  369. function displayPointOfInterest(pos, data, prevBtn, nextBtn, curr, total) {
  370. var poiInfo = data;
  371. var poiId = poiInfo.id;
  372. var objectId = poiInfo.object_id;
  373. var name = poiInfo.name;
  374. var type = poiInfo.type;
  375. var latitude = poiInfo.latitude;
  376. var longitude = poiInfo.longitude;
  377. var bearing = poiInfo.bearing;
  378. var userId = poiInfo.user_id;
  379. var focalLength = poiInfo.focal_length_millimetres;
  380. var heading = "<h2>Point of interest (" + (curr+1) + " of " + total + ")</h2>";
  381. if (total==1) {
  382. heading = "<h2>Point of interest</h2>";
  383. }
  384. var infohtml = "<div id='sppopup2'> " +
  385. heading +
  386. " ID: " + poiId + " <br />" +
  387. " Object ID: " + objectId + " <br />" +
  388. " Name: " + name + " <br />" +
  389. " Type: " + type + " <br />" +
  390. " Latitude: " + latitude + " <br />" +
  391. " Longitude: " + longitude + " <br />" +
  392. " Bearing: " + bearing + " <br />" +
  393. " User ID: " + userId + " <br />" +
  394. " Focal Length: " + focalLength + " <br />" +
  395. "<div id=''>"+prevBtn+" &nbsp; &nbsp; &nbsp; &nbsp; "+nextBtn+"</div>";
  396. if (document.getElementById("sppopup") != null) {
  397. document.getElementById("sppopup").innerHTML = infohtml;
  398. }
  399. }
  400. var defaultSelectFeatureStyle = null;
  401. function addFeatureSelectionTool() {
  402. removeAreaSelection();
  403. areaSelectOn = true;
  404. mapClickControl = null;
  405. OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
  406. defaultHandlerOptions: {
  407. 'single': true,
  408. 'double': false,
  409. 'pixelTolerance': 0,
  410. 'stopSingle': false,
  411. 'stopDouble': false
  412. },
  413. initialize: function(options) {
  414. this.handlerOptions = OpenLayers.Util.extend(
  415. {}, this.defaultHandlerOptions
  416. );
  417. OpenLayers.Control.prototype.initialize.apply(
  418. this, arguments
  419. );
  420. this.handler = new OpenLayers.Handler.Click(
  421. this, {
  422. 'click': pointSearch
  423. }, this.handlerOptions
  424. );
  425. }
  426. });
  427. mapClickControl = new OpenLayers.Control.Click();
  428. mapClickControl.fallThrough = true;
  429. map.addControl(mapClickControl);
  430. mapClickControl.activate();
  431. }
  432. function pointSearch(e) {
  433. var lonlat = map.getLonLatFromViewPortPx(e.xy);
  434. parent.setSearchPoint(lonlat);
  435. }
  436. function removePointSearch() {
  437. //remove the point search map click control
  438. mapClickControl.deactivate();
  439. map.removeControl(mapClickControl);
  440. mapClickControl = null;
  441. //reload the species click control
  442. registerSpeciesClick();
  443. }
  444. var query_count_total;
  445. var points_of_interest_total;
  446. var points_of_interest;
  447. function pointSpeciesSearch(e) {
  448. var lonlat = map.getLonLatFromViewPortPx(e.xy);
  449. var untransformedLon = lonlat.lon
  450. var untransformedLat = lonlat.lat
  451. lonlat.transform(map.projection, map.displayProjection);
  452. var webportal_url = parent.jq('$webportal_url')[0].innerHTML;
  453. //handles point click in mapComposer
  454. //parent.setSpeciesSearchPoint(lonlat);
  455. query_count_total = 0;
  456. points_of_interest_total = 0
  457. query_ = new Array();
  458. query_layer = new Array();
  459. query_size = new Array();
  460. query_url = new Array();
  461. points_of_interest = new Array();
  462. var pos = 0;
  463. for (var key in mapLayers) {
  464. if(mapLayers[key]) {
  465. if(mapLayers[key].id) {
  466. if(map.getLayer(mapLayers[key].id)) {
  467. var layer = mapLayers[key];
  468. if(layer == null) {
  469. continue;
  470. }
  471. if (layer.pointsOfInterestWS != null) {
  472. var pointsOfInterestData = getPointsOfInterest(layer, lonlat.lat, lonlat.lon, 6)
  473. if (pointsOfInterestData.length == 0) {
  474. continue;
  475. } else {
  476. points_of_interest_total += pointsOfInterestData.length
  477. points_of_interest = points_of_interest.concat(pointsOfInterestData)
  478. }
  479. } else {
  480. if (layer.url == null) {
  481. continue;
  482. }
  483. var query = null;
  484. var userquery = null;
  485. var p0 = layer.url.indexOf("CQL_FILTER=");
  486. var p1 = layer.url.indexOf("&", p0);
  487. if(p1 < 0) p1 = layer.url.indexOf(";", p0);
  488. if(p1 < 0) p1 = layer.url.length;
  489. if(p0 >= 0 && p1 >= 0 && layer.params != null) {
  490. if(layer.url.contains(webportal_url)) {
  491. userquery = layer.url.substring(p0 + 11,p1);
  492. } else {
  493. query = layer.url.substring(p0 + 11,p1);
  494. }
  495. }
  496. var size = 10;
  497. if(layer.params != null && layer.params.ENV != null) {
  498. var p2 = layer.params.ENV.indexOf("size:");
  499. p3 = layer.params.ENV.indexOf(";", p2);
  500. if(p3 < 0) p3 = layer.params.ENV.length;
  501. if(p2 >= 0 && p3 >= 0) {
  502. size = layer.params.ENV.substring(p2 + 5,p3)
  503. }
  504. }
  505. //console.log("map layer: " + layer);
  506. var data = null;
  507. if(query != null) data = getOccurrence(layer, query, lonlat.lat, lonlat.lon, 0, pos, size);
  508. if(userquery != null) data = getOccurrenceUploaded(layer, userquery, lonlat.lat, lonlat.lon, 0, pos, size);
  509. if(data != null) {
  510. query_count_total += query_size[pos];
  511. pos += 1;
  512. }
  513. }
  514. }
  515. }
  516. }
  517. }
  518. if (query_count_total == 0 && points_of_interest_total == 0) {
  519. return null;
  520. }
  521. var lonlat = new OpenLayers.LonLat(lonlat.lon, lonlat.lat).transform(
  522. new OpenLayers.Projection("EPSG:4326"),
  523. map.getProjectionObject());
  524. setupPopup(query_count_total, points_of_interest_total, lonlat);
  525. if (points_of_interest_total == 0 && query_count_total > 0) {
  526. iterateSpeciesInfoQuery(0)
  527. }
  528. if (query_count_total == 0 && points_of_interest_total > 0) {
  529. iteratePointsOfInterest(0)
  530. }
  531. var feature = popup;
  532. feature.popup = popup;
  533. popup.feature = feature;
  534. map.addPopup(popup, true);
  535. }
  536. function registerSpeciesClick() {
  537. OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
  538. defaultHandlerOptions: {
  539. 'single': true,
  540. 'double': false,
  541. 'pixelTolerance': 0,
  542. 'stopSingle': false,
  543. 'stopDouble': false
  544. },
  545. initialize: function(options) {
  546. this.handlerOptions = OpenLayers.Util.extend(
  547. {}, this.defaultHandlerOptions
  548. );
  549. OpenLayers.Control.prototype.initialize.apply(
  550. this, arguments
  551. );
  552. this.handler = new OpenLayers.Handler.Click(
  553. this, {
  554. 'click': pointSpeciesSearch
  555. }, this.handlerOptions
  556. );
  557. }
  558. });
  559. mapClickControl = new OpenLayers.Control.Click();
  560. mapClickControl.fallThrough = true;
  561. map.addControl(mapClickControl);
  562. mapClickControl.activate();
  563. ///////////////////
  564. // setVectorLayersSelectable();
  565. var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
  566. layer_style.fillColor = "red";
  567. layer_style.strokeColor = "red";
  568. featureSpeciesSelectLayer = new OpenLayers.Layer.Vector("Selected Species Layer", {
  569. style: layer_style
  570. });
  571. featureSpeciesSelectLayer.setVisibility(true);
  572. map.addLayer(featureSpeciesSelectLayer);
  573. }
  574. function addRadiusDrawingTool() {
  575. removeAreaSelection();
  576. radiusOptions = {
  577. sides: 40
  578. };
  579. var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
  580. layer_style.fillColor = "red";
  581. layer_style.strokeColor = "red";
  582. radiusLayer = new OpenLayers.Layer.Vector("Point Radius Layer Layer", {
  583. style: layer_style,
  584. eventListeners: {
  585. "sketchmodified": function(event) {
  586. var verts = event.vertex.getVertices();
  587. var gll = new Array();
  588. if (verts.length > 0) {
  589. for (var v=0; v<verts.length; v++) {
  590. var pt = verts[v].transform(map.projection, map.displayProjection);
  591. gll.push(new google.maps.LatLng(pt.y, pt.x));
  592. }
  593. }
  594. var currarea = ((google.maps.geometry.spherical.computeArea(gll)/1000)/1000);
  595. var currradius = Math.sqrt(currarea/Math.PI);
  596. currradius = Math.round(currradius*Math.pow(10,2))/Math.pow(10,2);
  597. $('#currradius').html(currradius);
  598. }
  599. }
  600. });
  601. radiusLayer.setVisibility(true);
  602. map.addLayer(radiusLayer);
  603. if(radiusControl != null){
  604. map.removeControl(radiusControl);
  605. radiusControl.destroy();
  606. radiusControl = null;
  607. }
  608. radiusControl = new OpenLayers.Control.DrawFeature(radiusLayer,OpenLayers.Handler.RegularPolygon,{
  609. 'featureAdded':radiusAdded,
  610. handlerOptions:radiusOptions
  611. });
  612. map.addControl(radiusControl);
  613. radiusControl.activate();
  614. $('#currradius').html("0");
  615. $('#radiusDisplay').slideDown('slow');
  616. }
  617. function addPolygonDrawingTool() {
  618. removeAreaSelection();
  619. ////adding polygon control and layer
  620. var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
  621. layer_style.fillColor = "red";
  622. layer_style.strokeColor = "red";
  623. polygonLayer = new OpenLayers.Layer.Vector("Polygon Layer", {
  624. style: layer_style
  625. });
  626. polygonLayer.setVisibility(true);
  627. map.addLayer(polygonLayer);
  628. if(polyControl != null){
  629. map.removeControl(polyControl);
  630. polyControl.destroy();
  631. polyControl = null;
  632. }
  633. polyControl = new OpenLayers.Control.DrawFeature(polygonLayer,OpenLayers.Handler.Polygon,{
  634. 'featureAdded':polygonAdded
  635. });
  636. map.addControl(polyControl);
  637. polyControl.activate();
  638. //////
  639. }
  640. function removeAreaSelection() {
  641. if(polygonLayer != null){
  642. polygonLayer.destroy();
  643. polygonLayer = null;
  644. polyControl.deactivate();
  645. }
  646. if(boxLayer != null) {
  647. boxLayer.destroy();
  648. boxLayer = null;
  649. boxControl.deactivate();
  650. }
  651. if(radiusLayer != null){
  652. radiusLayer.destroy();
  653. radiusLayer = null;
  654. radiusControl.deactivate();
  655. $('#radiusDisplay').slideUp('slow');
  656. }
  657. if(featureSelectLayer != null){
  658. featureSelectLayer.destroy();
  659. featureSelectLayer = null;
  660. areaSelectOn = false;
  661. }
  662. /* refreshes all the vector layers -> this is because the vector features
  663. * can dissappear after selection so need to redraw
  664. */
  665. for(var i in selectionLayers) {
  666. var layer = selectionLayers[i];
  667. for(var j in layer.features) {
  668. layer.drawFeature(layer.features[j]);
  669. }
  670. }
  671. if(mapClickControl != null) {
  672. mapClickControl.deactivate();
  673. map.removeControl(mapClickControl);
  674. }
  675. }
  676. function addBoxDrawingTool() {
  677. removeAreaSelection();
  678. var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
  679. layer_style.fillColor = "red";
  680. layer_style.strokeColor = "red";
  681. boxLayer = new OpenLayers.Layer.Vector("Box Layer", {
  682. style : layer_style
  683. });
  684. boxControl = new OpenLayers.Control.DrawFeature(boxLayer,OpenLayers.Handler.Box,{
  685. 'featureAdded':regionAdded
  686. });
  687. map.addControl(boxControl);
  688. boxControl.activate();
  689. }
  690. function featureSelected(feature) {
  691. parent.setLayerGeometry(feature.layer.name);
  692. areaSelectOn = false;
  693. removeAreaSelection();
  694. setVectorLayersSelectable();
  695. }
  696. function radiusAdded(feature) {
  697. parent.setPolygonGeometry(feature.geometry);
  698. removeAreaSelection();
  699. setVectorLayersSelectable();
  700. }
  701. // This function passes the region geometry up to javascript in index.zul which can then send it to the server.
  702. function regionAdded(feature) {
  703. //converting bounds from pixel value to lonlat - annoying!
  704. var geoBounds = new OpenLayers.Bounds();
  705. geoBounds.extend(map.getLonLatFromPixel(new OpenLayers.Pixel(feature.geometry.left,feature.geometry.bottom)));
  706. geoBounds.extend(map.getLonLatFromPixel(new OpenLayers.Pixel(feature.geometry.right,feature.geometry.top)));
  707. removeAreaSelection();
  708. setVectorLayersSelectable();
  709. parent.setRegionGeometry(geoBounds.toGeometry());
  710. }
  711. // This function passes the geometry up to javascript in index.zul which can then send it to the server.
  712. function polygonAdded(feature) {
  713. parent.setPolygonGeometry(feature.geometry);
  714. removeAreaSelection();
  715. setVectorLayersSelectable();
  716. }
  717. function setVectorLayersSelectable() {
  718. try {
  719. var layersV = map.getLayersByClass('OpenLayers.Layer.Vector');
  720. if(selectControl != null){
  721. selectControl.deactivate();
  722. map.removeControl(selectControl);
  723. selectControl.destroy();
  724. selectControl = null;
  725. }
  726. selectControl = new OpenLayers.Control.SelectFeature(layersV);
  727. map.addControl(selectControl);
  728. selectControl.activate();
  729. } catch (err) {
  730. }
  731. }
  732. var currFeature;
  733. var currFeatureCount;
  734. function setupPopup(occurrenceCount, pointOfInterestCount, centerlonlat) {
  735. var msg = "<br /><br />";
  736. if (occurrenceCount > 0 && pointOfInterestCount == 0) {
  737. if (occurrenceCount == 1) {
  738. msg += occurrenceCount + " occurrence found in this location <br /> Retrieving data... ";
  739. } else {
  740. msg += occurrenceCount + " occurrences found in this location <br /> Retrieving data... ";
  741. }
  742. } else if (pointOfInterestCount > 0 && occurrenceCount == 0) {
  743. if (pointOfInterestCount == 1) {
  744. msg += pointOfInterestCount + " occurrence found in this location <br /> Retrieving data... ";
  745. } else {
  746. msg += pointOfInterestCount + " points of interest found in this location <br /> Retrieving data... ";
  747. }
  748. } else {
  749. if (occurrenceCount == 1) {
  750. msg += occurrenceCount + " occurrence found in this location ";
  751. } else {
  752. msg += occurrenceCount + " occurrences found in this location ";
  753. }
  754. msg += "<a href='javascript:iterateSpeciesInfoQuery(0);'><img src='img/arrow_right.png' /></a>";
  755. msg += "<br />";
  756. msg += pointOfInterestCount + " points of interest found in this location ";
  757. if (pointOfInterestCount == 1) {
  758. msg += pointOfInterestCount + " points of interest found in this location ";
  759. }
  760. msg += "<a href='javascript:iteratePointsOfInterest(0);'><img src='img/arrow_right.png' /></a>";
  761. }
  762. popup = new OpenLayers.Popup.FramedCloud("featurePopup",
  763. centerlonlat,
  764. new OpenLayers.Size(100,170),
  765. "<div id='sppopup'>" + msg + "</div>" // style='width: 350px; height: 250px;'
  766. ,
  767. null, true, onPopupClose);
  768. popup.autoSize = true;
  769. popup.minSize = new OpenLayers.Size(350,250);
  770. }
  771. function onPopupClose(evt) {
  772. try {
  773. map.removePopup(this.feature.popup);
  774. this.feature.popup.destroy();
  775. this.feature.popup = null;
  776. selectControl.unselect(this.feature);
  777. } catch(err) {
  778. }
  779. }
  780. function relocatePopup(lon, lat) {
  781. popup.lonlat = new OpenLayers.LonLat(lon, lat).transform(
  782. new OpenLayers.Projection("EPSG:4326"),
  783. map.getProjectionObject());
  784. popup.updatePosition();
  785. }
  786. function displaySpeciesInfo(pos, data, prevBtn, nextBtn, curr, total) {
  787. var occinfo = data;
  788. var bie = parent.jq('$bie_url')[0].innerHTML;
  789. var biocache = query_layer[pos].ws;
  790. var rank = occinfo.taxonRank;
  791. var speciesname = occinfo.scientificName;
  792. var specieslsid = occinfo.taxonConceptID;
  793. species = (speciesname!=null)?speciesname:"";
  794. if (specieslsid != null) {
  795. species = '<a href="' + bie + '/species/'+specieslsid+'" target="_blank">'+species+'</a>';
  796. } else {
  797. species = species + ' (<i>Supplied as: "' + occinfo.scientificName + '"</i>) ';
  798. }
  799. var family = occinfo.family;
  800. if (occinfo.family != null) {
  801. family = '<a href="' + bie + '/species/'+occinfo.family+'" target="_blank">'+family+'</a>';
  802. }
  803. var kingdom = occinfo.kingdom;
  804. if (occinfo.kingdom != null) {
  805. kingdom = '<a href="' + bie + '/species/'+occinfo.kingdom+'" target="_blank">'+kingdom+'</a>';
  806. }
  807. var occurrencedate = "";
  808. if(occinfo.year && occinfo.month) {
  809. occurrencedate = occinfo.month + "/" + occinfo.year;
  810. } else if (occinfo.year) {
  811. occurrencedate = occinfo.year
  812. }
  813. var uncertainty = occinfo.coordinateUncertaintyInMeters;
  814. var uncertaintyText = uncertainty + " metres";
  815. if(uncertainty == "" || uncertainty == undefined || uncertainty == null) {
  816. uncertaintyText = "<b>Not supplied </b>"; // setting to 10km
  817. uncertainty = 10000;
  818. }
  819. var heading = "<h2>Occurrence information (" + (curr+1) + " of " + total + ")</h2>";
  820. if (total==1) {
  821. heading = "<h2>Occurrence information (1 occurrence)</h2>";
  822. }
  823. var fullQueryLink = "";
  824. if(total>1) fullQueryLink = "More detail: <a href='" + query_ui_forall + "' target='_blank'>All records at this point</a>";
  825. var checked = parent.isFlaggedRecord(query_layer[pos].name, occinfo.uuid);
  826. var checkstate = "";
  827. if(checked) checkstate="checked='" + checked + "'";
  828. var infohtml = "<div id='sppopup2'> " +
  829. heading +
  830. " Scientific name: " + species + " <br />" +
  831. " Kingdom: " + kingdom + " <br />" +
  832. " Family: " + family + " <br />" +
  833. " Data provider: <a href='http://collections.ala.org.au/public/show/" + occinfo.dataProviderUid + "' target='_blank'>" + occinfo.dataProviderName + "</a> <br />" +
  834. " Longitude: "+occinfo.decimalLongitude + " , Latitude: " + occinfo.decimalLatitude + " (<a href='javascript:goToLocation("+occinfo.decimalLongitude+", "+occinfo.decimalLatitude+", 15);relocatePopup("+occinfo.decimalLongitude+", "+occinfo.decimalLatitude+");'>zoom to</a>) <br/>" +
  835. " Spatial uncertainty in metres: " + uncertaintyText + "<br />" +
  836. " Occurrence date: " + occurrencedate + " <br />" +
  837. "Full record: <a href='" + biocache + "/occurrences/" + occinfo.uuid + "' target='_blank'>View details</a> <br />" +
  838. fullQueryLink + " <br/>" +
  839. "<input type='checkbox' " + checkstate + " onClick='parent.flagRecord(\"" + query_layer[pos].name + "\",\"" + occinfo.uuid + "\",this.checked)' />Assign record to <i>ad hoc</i> group<br/>" +
  840. "<div id=''>"+prevBtn+" &nbsp; &nbsp; &nbsp; &nbsp; "+nextBtn+"</div>";
  841. if (document.getElementById("sppopup") != null) {
  842. document.getElementById("sppopup").innerHTML = infohtml;
  843. }
  844. }
  845. function addWKTFeatureToMap(featureWKT,name,hexColour,opacity) {
  846. var in_options = {
  847. 'internalProjection': map.baseLayer.projection,
  848. 'externalProjection': new OpenLayers.Projection("EPSG:4326")
  849. };
  850. var styleMap = new OpenLayers.StyleMap(OpenLayers.Util.applyDefaults(
  851. {
  852. fillColor: hexColour,
  853. fillOpacity: opacity,
  854. strokeOpacity: 1,
  855. strokeWidth: 2,
  856. strokeColor: hexColour
  857. },
  858. OpenLayers.Feature.Vector.style["new"]));
  859. var layer_style = OpenLayers.Util.extend({},OpenLayers.Feature.Vector.style['default']);
  860. layer_style.fillColor = hexColour;
  861. layer_style.strokeColor = hexColour;
  862. layer_style.fillOpacity = opacity;
  863. var wktLayer = new OpenLayers.Layer.Vector(name, {
  864. style : layer_style
  865. });
  866. map.addLayer(wktLayer);
  867. var geom = new OpenLayers.Geometry.fromWKT(featureWKT);
  868. geom = geom.transform(map.displayProjection, map.projection);
  869. wktLayer.addFeatures([new OpenLayers.Feature.Vector(geom)]);
  870. wktLayer.isFixed = false;
  871. selectionLayers[selectionLayers.length] = wktLayer;
  872. removePointSearch();
  873. return wktLayer;
  874. }
  875. var myVector;
  876. function addJsonFeatureToMap(feature, name, hexColour, radius, opacity, szUncertain) {
  877. var in_options = {
  878. 'internalProjection': map.baseLayer.projection,
  879. 'externalProjection': new OpenLayers.Projection("EPSG:4326")
  880. };
  881. var styleMap = new OpenLayers.StyleMap(OpenLayers.Util.applyDefaults(
  882. {
  883. fillColor: hexColour,
  884. fillOpacity: opacity,
  885. strokeOpacity: 1,
  886. strokeWidth: 2,
  887. strokeColor: hexColour
  888. },
  889. OpenLayers.Feature.Vector.style["new"]));
  890. var layer_style = OpenLayers.Util.extend({},OpenLayers.Feature.Vector.style['default']);
  891. layer_style.fillColor = hexColour;
  892. layer_style.strokeColor = hexColour;
  893. layer_style.pointRadius = 0;
  894. layer_style.pointRadius = radius;
  895. layer_style.fillOpacity = opacity;
  896. layer_style.szUncertain = szUncertain;
  897. layer_style.fontWeight = "bold";
  898. var geojson_format = new OpenLayers.Format.GeoJSON(in_options);
  899. var vector_layer = new OpenLayers.Layer.Vector(name,{
  900. styleMap: styleMap
  901. });
  902. myVector = vector_layer;
  903. vector_layer.style = layer_style;
  904. vector_layer.isFixed = false;
  905. features = geojson_format.read(feature);
  906. fixAttributes(features, feature);
  907. //apply uncertainty to features
  908. vector_layer.events.register("featureadded", vector_layer, featureadd);
  909. vector_layer.addFeatures(features);
  910. vector_layer.events.register("featureselected", vector_layer, selected);
  911. window.setTimeout(function(){
  912. setVectorLayersSelectable();
  913. }, 2000);
  914. return vector_layer;
  915. }
  916. function selected (evt) {
  917. var feature = (evt.feature==null)?evt:evt.feature;
  918. var attrs = feature.attributes;
  919. currFeature = feature;
  920. if (areaSelectOn) {
  921. currFeature = null;
  922. featureSelected(feature);
  923. return;
  924. }
  925. else {
  926. //test to see if its occurrence data
  927. if (attrs["oi"] != null) {
  928. popup = new OpenLayers.Popup.FramedCloud("featurePopup",
  929. feature.geometry.getBounds().getCenterLonLat(),
  930. new OpenLayers.Size(100,170),
  931. "<div id='sppopup'>Retrieving data... </div>" // style='width: 350px; height: 250px;'
  932. ,
  933. null, true, onPopupClose);
  934. //parent.showInfoOne();
  935. parent.setSpeciesSearchPoint(feature.geometry.getBounds().getCenterLonLat());
  936. } else if (attrs["count"] != null) {
  937. setupPopup(attrs["count"], feature.geometry.getBounds().getCenterLonLat());
  938. showClusterInfo(0);
  939. } else {
  940. var html = "<h2>Feature Details</h2>";
  941. if (attrs.Feature_Name) {
  942. html += "Feature name: " + attrs.Feature_Name + "<br />";
  943. html += "Feature ID: " + attrs.Feature_ID + "<br />";
  944. html += "GID: " + attrs.gid + "<br /><br />";
  945. if (attrs.Bounding_Box) {
  946. html += "Bounding box: " + attrs.Bounding_Box + "<br />";
  947. html += "Feature type: Polygon <br /><br />";
  948. }
  949. if (attrs.Point) {
  950. html += "Point: " + attrs.Point + "<br />";
  951. html += "Feature type: Point <br /><br />";
  952. }
  953. html += "Metadata: <a href='" + attrs.Layer_Metadata + "' target='_blank'>" + attrs.Layer_Metadata + "</a> <br />";
  954. } else {
  955. for (key in attrs) {
  956. html += "<br>" + key + " : " + attrs[key];
  957. }
  958. }
  959. popup = new OpenLayers.Popup.FramedCloud("featurePopup",
  960. feature.geometry.getBounds().getCenterLonLat(),
  961. new OpenLayers.Size(100,170),
  962. html
  963. ,
  964. null, true, onPopupClose);
  965. }
  966. feature.popup = popup;
  967. popup.feature = feature;
  968. map.addPopup(popup, true);
  969. }
  970. }
  971. function featureadd(evt) {
  972. var max_map_bounds = new OpenLayers.Bounds(-180,-90, 180, 90); // map.getMaxExtent();
  973. var feature = evt.feature;
  974. var fgeomt = feature.geometry.transform(map.projection,map.displayProjection);
  975. var isContains = max_map_bounds.contains(this.getDataExtent().left, this.getDataExtent().top);
  976. /*
  977. * add a mirror point 360 to the west of the feature, so that it will be displayed
  978. * when the map's extent becomes < -180 as a result of the warpdateline function
  979. * of the base layer, this is only applicable for point
  980. */
  981. if(!feature.isMirror){
  982. if(!feature.onScreen()){
  983. if(!max_map_bounds.contains(this.getDataExtent().left, this.getDataExtent().top)){//feature.geometry.x > 0 &&
  984. var featureMirror = new OpenLayers.Feature.Vector(
  985. new OpenLayers.Geometry.Point((fgeomt.x - max_map_bounds.getWidth()), fgeomt.y),
  986. feature.attributes,
  987. feature.style);
  988. featureMirror.isMirror = true;
  989. feature.isMirror = false;
  990. var fmgeomt = featureMirror.geometry.transform(map.projection,map.displayProjection);
  991. this.addFeatures([featureMirror]);
  992. }
  993. }
  994. }
  995. fgeomt = feature.geometry.transform(map.displayProjection,map.projection);
  996. }
  997. function addJsonUrlToMap(url, name, hexColour, radius, opacity, szUncertain) {
  998. $.getJSON(proxy_script + url, function(feature) {
  999. addJsonFeatureToMap(feature, name, hexColour, radius, opacity, szUncertain);
  1000. var urlname = url + "::" + name;
  1001. vector_layer.urlname = urlname;
  1002. mapLayers[urlname] = vector_layer;
  1003. registerLayer(mapLayers[urlname]);
  1004. map.addLayer(mapLayers[urlname]);
  1005. if(map.signalLayerLoaded != undefined
  1006. && vector_layer.urlname != undefined)
  1007. map.signalLayerLoaded(vector_layer.urlname);
  1008. });
  1009. }
  1010. function appendJsonUrlToMap(url, original_url, name) {
  1011. $.getJSON(proxy_script + url, function(feature) {
  1012. var urlname = original_url + "::" + name;
  1013. vector_layer = mapLayers[urlname];
  1014. var in_options = {
  1015. 'internalProjection': map.baseLayer.projection,
  1016. 'externalProjection': new OpenLayers.Projection("EPSG:4326")
  1017. };
  1018. var geojson_format = new OpenLayers.Format.GeoJSON(in_options);
  1019. features = geojson_format.read(feature);
  1020. fixAttributes(features, feature)
  1021. //apply uncertainty to features
  1022. vector_layer.addFeatures(features);
  1023. if(map.signalLayerLoaded != undefined
  1024. && vector_layer.urlname != undefined)
  1025. map.signalLayerLoaded(url);
  1026. });
  1027. }
  1028. function removeFromSelectControl(lyrname) {
  1029. if (selectControl==undefined || selectControl==null) {
  1030. return;
  1031. }
  1032. var currentLayers = selectControl.layers;
  1033. for (var li=0; li<currentLayers.length; li++) {
  1034. if (currentLayers[li].name==lyrname) {
  1035. currentLayers.splice(li,1);
  1036. break;
  1037. }
  1038. }
  1039. if (lyrname=="Active Area") {
  1040. activeAreaPresent = false;
  1041. parent.displayArea(map.getExtent().toGeometry().getGeodesicArea(map.projection)/1000/1000);
  1042. var verts = map.getExtent().toGeometry().clone().getVertices();
  1043. var gll = new Array();
  1044. if (verts.length > 0) {
  1045. for (var v=0; v<verts.length; v++) {
  1046. var pt = verts[v].transform(map.projection, map.displayProjection);
  1047. gll.push(new google.maps.LatLng(pt.y, pt.x));
  1048. }
  1049. }
  1050. parent.displayArea2((google.maps.geometry.spherical.computeArea(gll)/1000)/1000);
  1051. }
  1052. var isActive = selectControl.active;
  1053. try{
  1054. selectControl.unselectAll();
  1055. }catch(err){}
  1056. selectControl.deactivate();
  1057. if(selectControl.layers) {
  1058. selectControl.layer.destroy();
  1059. selectControl.layers = null;
  1060. }
  1061. initSelectControlLayers(currentLayers);
  1062. selectControl.handlers.feature.layer = selectControl.layer;
  1063. if (isActive) {
  1064. selectControl.activate();
  1065. }
  1066. }
  1067. function initSelectControlLayers(layers) {
  1068. if(layers instanceof Array) {
  1069. selectControl.layers = layers;
  1070. selectControl.layer = new OpenLayers.Layer.Vector.RootContainer(
  1071. selectControl.id + "_container", {
  1072. layers: layers
  1073. }
  1074. );
  1075. } else {
  1076. selectControl.layer = layers;
  1077. }
  1078. }
  1079. function redrawWKTFeatures(featureWKT, name,hexColour,opacity) {
  1080. var layers = map.getLayersByName(name);
  1081. var layer_style = OpenLayers.Util.extend({},OpenLayers.Feature.Vector.style['default']);
  1082. layer_style.fillColor = hexColour;
  1083. layer_style.strokeColor = hexColour;
  1084. layer_style.fillOpacity = opacity;
  1085. for (key in layers) {
  1086. if (layers[key] != undefined) {
  1087. var layer = map.getLayer(layers[key].id);
  1088. if (layer.name == name) {
  1089. layer.destroyFeatures();
  1090. layer.style = layer_style;
  1091. var geom = new OpenLayers.Geometry.fromWKT(featureWKT);
  1092. geom = geom.transform(map.displayProjection, map.projection);
  1093. layer.addFeatures([new OpenLayers.Feature.Vector(geom)]);
  1094. layer.isFixed = false;
  1095. layer.addFeatures([new OpenLayers.Feature.Vector(geom)]);
  1096. }
  1097. }
  1098. }
  1099. }
  1100. function redrawFeatures(name, hexColour, opacity, radius, szUncertain) {
  1101. var in_options = {
  1102. 'internalProjection': map.baseLayer.projection,
  1103. 'externalProjection': new OpenLayers.Projection("EPSG:4326")
  1104. };
  1105. var gjLayers = map.getLayersByName(name);
  1106. var layer_style = OpenLayers.Util.extend({},OpenLayers.Feature.Vector.style['default']);
  1107. layer_style.fillColor = hexColour;
  1108. layer_style.strokeColor = hexColour;
  1109. layer_style.fillOpacity = opacity;
  1110. layer_style.pointRadius = radius;
  1111. layer_style.szUncertain = szUncertain;
  1112. layer_style.fontWeight = "bold";
  1113. for (key in gjLayers) {
  1114. if (gjLayers[key] != undefined) {
  1115. var layer = gjLayers[key];
  1116. if (layer.name == name) {
  1117. layer.style = layer_style;
  1118. layer.redraw(true);
  1119. }
  1120. }
  1121. }
  1122. }
  1123. function zoomBoundsGeoJSON(layerName) {
  1124. //get the other geojson layers and force them to redraw
  1125. var geoJsonLayers = map.getLayersByClass("OpenLayers.Layer.Vector");
  1126. for (key in geoJsonLayers) {
  1127. var layer = geoJsonLayers[key];
  1128. if (layer.name == layerName) {
  1129. map.zoomToExtent(layer.getDataExtent());
  1130. }
  1131. }
  1132. }
  1133. function zoomBoundsLayer(layername) {
  1134. var wmsLayers = map.getLayersByClass("OpenLayers.Layer.WMS");
  1135. for (key in wmsLayers) {
  1136. if (map.layers[key] != undefined) {
  1137. var layer = map.getLayer(map.layers[key].id);
  1138. if (layer.name == layername){
  1139. map.zoomToExtent(layer.getExtent());
  1140. }
  1141. }
  1142. }
  1143. }
  1144. function removeItFromTheList(layername) {
  1145. var gjLayers = map.getLayersByName(layername);
  1146. for (key in gjLayers) {
  1147. if (gjLayers[key] != undefined) {
  1148. var layer = map.getLayer(gjLayers[key].id);
  1149. if (layer.name == layername) {
  1150. if(layer.removeFeatures != undefined) layer.removeFeatures();
  1151. map.removeLayer(layer);
  1152. }
  1153. }
  1154. }
  1155. }
  1156. function removeDeselectedLayers(layerIds) {
  1157. for (var key in mapLayers) {
  1158. var found = false;
  1159. var i = 0;
  1160. while (! found && i < layerIds.length) {
  1161. if (key == layerIds[i]) {
  1162. found = true;
  1163. }
  1164. i++;
  1165. }
  1166. if (! found) {
  1167. map.removeLayer(mapLayers[key]);
  1168. mapLayers[key] = null;
  1169. }
  1170. }
  1171. }
  1172. function getCurrentFeatureInfo() {
  1173. return jQuery('#featureinfocontent').html();
  1174. }
  1175. function URLEncode (clearString) {
  1176. var output = '';
  1177. var x = 0;
  1178. clearString = clearString.toString();
  1179. var regex = /(^[a-zA-Z0-9_.]*)/;
  1180. while (x < clearString.length) {
  1181. var match = regex.exec(clearString.substr(x));
  1182. if (match != null && match.length > 1 && match[1] != '') {
  1183. output += match[1];
  1184. x += match[1].length;
  1185. } else {
  1186. if (clearString[x] == ' ')
  1187. output += '+';
  1188. else {
  1189. var charCode = clearString.charCodeAt(x);
  1190. var hexVal = charCode.toString(16);
  1191. output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
  1192. }
  1193. x++;
  1194. }
  1195. }
  1196. return output;
  1197. }
  1198. function fixAttributes(features, feature){
  1199. //add feature (geojson string) properties to all features attributes
  1200. //when first object (geometry) in features (geometry array) has no attributes
  1201. //occurs when geojson type is GeometryCollection instead of Feature
  1202. try{
  1203. if(features.length > 0){
  1204. var f = features[0];
  1205. var i = 0;
  1206. for(key in f.attributes) i++;
  1207. if(i == 0){
  1208. var json_format = new OpenLayers.Format.JSON();
  1209. var json = json_format.read(feature);
  1210. if(json.properties != undefined){
  1211. for(i=0;i<features.length;i++) {
  1212. features[i].attributes = json.properties;
  1213. }
  1214. }
  1215. }
  1216. for (var j=0;j<features.length;j++) {
  1217. features[j].isMirror = false;
  1218. }
  1219. }
  1220. }catch(err){}
  1221. }
  1222. function loadKmlFile(name, kmlurl) {
  1223. //Defiine your KML layer//
  1224. var kmlLayer= new OpenLayers.Layer.Vector(name, {
  1225. //Set your projection and strategies//
  1226. projection: new OpenLayers.Projection("EPSG:4326"),
  1227. strategies: [new OpenLayers.Strategy.Fixed()],
  1228. //set the protocol with a url//
  1229. protocol: new OpenLayers.Protocol.HTTP({
  1230. //set the url to your variable//
  1231. url: kmlurl,
  1232. //format this layer as KML//
  1233. format: new OpenLayers.Format.KML({
  1234. //maxDepth is how deep it will follow network links//
  1235. maxDepth: 1,
  1236. //extract styles from the KML Layer//
  1237. extractStyles: true,
  1238. //extract attributes from the KML Layer//
  1239. extractAttributes: true
  1240. })
  1241. })
  1242. });
  1243. return kmlLayer;
  1244. }
  1245. var prevHoverData = null;
  1246. var prevHoverRequest = null;
  1247. var prevNearestData = null;
  1248. var prevNearestRequest = null;
  1249. function envLayerInspection(e) {
  1250. try {
  1251. infoHtml = envLayerHover(e, true);
  1252. if(infoHtml != null) {
  1253. var pt = map.getLonLatFromViewPortPx(new
  1254. OpenLayers.Pixel(e.xy.x, e.xy.y) );
  1255. popup = new OpenLayers.Popup.FramedCloud("featurePopup",
  1256. pt,
  1257. new OpenLayers.Size(20,20),
  1258. "<div id='sppopup' style='width: 350px; height: 50px;'>" + "Loading..." + "</div>"
  1259. ,
  1260. null, true, onPopupClose);
  1261. var feature = popup;
  1262. feature.popup = popup;
  1263. popup.feature = feature;
  1264. map.addPopup(popup, true);
  1265. pt = pt.transform(map.projection, map.displayProjection);
  1266. infoHtml = "<div id='sppopup2'>"
  1267. + "<table><tr><td colspan='5'><b>Point "
  1268. + pt.lon.toPrecision(8)
  1269. + ", "
  1270. + pt.lat.toPrecision(8)
  1271. + "</b></td></tr>"
  1272. + infoHtml
  1273. + "</table>"
  1274. + "</div>";
  1275. if (document.getElementById("sppopup") != null) {
  1276. document.getElementById("sppopup").innerHTML = infoHtml;
  1277. }
  1278. }
  1279. }catch(err){
  1280. }
  1281. }
  1282. var last_hover_pos = null;
  1283. var last_hover_data = null;
  1284. function envLayerHover(e,displayFull) {
  1285. //This variable will contain the body text to be displayed in the popup.
  1286. var body = "";
  1287. var pt = map.getLonLatFromViewPortPx(new OpenLayers.Pixel(e.xy.x, e.xy.y) );
  1288. pt = pt.transform(map.projection, map.displayProjection);
  1289. var this_pos = pt.lat + "," + pt.lon;
  1290. if(this_pos == last_hover_pos) {
  1291. return last_hover_data;
  1292. }
  1293. last_hover_pos = this_pos;
  1294. try {
  1295. var layers = map.getLayersByClass("OpenLayers.Layer.WMS");
  1296. //find first valid layer, if any
  1297. var names = "";
  1298. for(var i=layers.length-1;i>=0;i--) {
  1299. var layer = layers[i];
  1300. var p0 = layer.url.indexOf("geoserver");
  1301. var p1 = layer.url.indexOf("ALA:");
  1302. var p2 = layer.url.indexOf("&",p1+1);
  1303. if(p0 < 0 || p1 < 0 || p1 < 0) {
  1304. continue;
  1305. }
  1306. if(p2 < 0) p2 = layer.url.length;
  1307. if(names.length > 0) {
  1308. names = names + ",";
  1309. }
  1310. names = names + layer.url.substring(p1+4,p2);
  1311. }
  1312. if (names.length == 0) {
  1313. return "";
  1314. }
  1315. var data = getLayerValue(names, pt.lat, pt.lon);
  1316. if(data != null && data.length > 0) {
  1317. for(i=0;i<data.length;i++) {
  1318. if (displayFull) {
  1319. body = body + "<tr><td>" + data[i].layername + "</td><td><b>" + data[i].value + "</b></td></tr>";
  1320. } else {
  1321. body += '<div class="lvalue" title="' + data[i].layername + ': ' + data[i].value + '">';
  1322. body += '<div class="lname">' + data[i].layername + '</div>';
  1323. body += '<div class="lval">' + data[i].value + '</div>';
  1324. body += '</div>';
  1325. }
  1326. }
  1327. last_hover_data = body;
  1328. return body;
  1329. }
  1330. }catch(err){
  1331. //console.error("an error has occurred!");
  1332. }
  1333. return null;
  1334. }
  1335. var markers = null;
  1336. var markers_icon = null;
  1337. var last_nearest_pos = null;
  1338. var last_nearest_data = null;
  1339. function envLayerNearest(e) {
  1340. //This variable will contain the body text to be displayed in the popup.
  1341. var body = "";
  1342. var pt = map.getLonLatFromViewPortPx(new OpenLayers.Pixel(e.xy.x, e.xy.y) );
  1343. pt = pt.transform(map.projection, map.displayProjection);
  1344. var this_pos = pt.lat + "," + pt.lon;
  1345. if(this_pos == last_nearest_pos) {
  1346. return last_nearest_data;
  1347. }
  1348. last_nearest_pos = this_pos;
  1349. try {
  1350. var url = parent.jq('$layers_url')[0].innerHTML + "/objects/cl915/" + pt.lat + "/" + pt.lon + "?limit=5";
  1351. var ret = "";
  1352. var time = new Date().getTime();
  1353. $.ajax({
  1354. url: proxy_script + URLEncode(url),
  1355. dataType: "json",
  1356. success: function(data){
  1357. ret = data;
  1358. },
  1359. async: false
  1360. });
  1361. if(ret != null && ret.length > 0) {
  1362. body = body + "<tr><td width='200px'><b>Feature</td><td width='85px'><b>Location</b></td><td width='55px'><b>Distance (km)</b></td><td width='50px'><b>Heading (deg)</b></td></tr>"
  1363. if(markers == null) {
  1364. initMarkersLayer();
  1365. }
  1366. for(i=0;i<ret.length;i++) {
  1367. var coords = ret[i].geometry.replace("POINT(","").replace(")","").split(" ");
  1368. var lng = coords[0] * 1.0;
  1369. var lat = coords[1] * 1.0;
  1370. var style = ""
  1371. if(i%2 == 1) {
  1372. style = "class='md_grey-bg'"
  1373. }
  1374. body = body + "<tr " + style + "><td>" + ret[i].name
  1375. + "</td><td>" + lng + ",<br>" + lat
  1376. + "</td><td>" + (Math.round(ret[i].distance/100)/10)
  1377. + "</td><td>" + (Math.round(ret[i].degrees*10)/10) + "</td></tr>";
  1378. //markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(lng,lat).transform(map.displayProjection, map.projection),markers_icon.clone()));
  1379. var c = new OpenLayers.LonLat(lng,lat).transform(map.displayProjection, map.projection)
  1380. var point = new OpenLayers.Geometry.Point(c.lon, c.lat);
  1381. var pointFeature = new OpenLayers.Feature.Vector(point);
  1382. pointFeature.attributes = {
  1383. name: ret[i].name
  1384. };
  1385. try {
  1386. markers.addFeatures([pointFeature]);
  1387. } catch (err) {
  1388. //Catch IE9 error. pointFeature is still mapping.
  1389. }
  1390. }
  1391. last_nearest_data = body;
  1392. return body;
  1393. }
  1394. }catch(err){
  1395. }
  1396. return null;
  1397. }
  1398. function mapPoints(json) {
  1399. if(markers == null) {
  1400. initMarkersLayer();
  1401. }
  1402. var ret = jQuery.parseJSON(json);
  1403. var body = "";
  1404. if(ret != undefined && ret.length > 0) {
  1405. for(i=0;i<ret.length;i++) {
  1406. var coords = ret[i].geometry.replace("POINT(","").replace(")","").split(" ");
  1407. var lng = coords[0] * 1.0;
  1408. var lat = coords[1] * 1.0;
  1409. var style = ""
  1410. if(i%2 == 1) {
  1411. style = "class='md_grey-bg'"
  1412. }
  1413. body = body + "<tr " + style + "><td>" + ret[i].name
  1414. + "</td><td>" + lng + ",<br>" + lat
  1415. + "</td></tr>";
  1416. //markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(lng,lat).transform(map.displayProjection, map.projection),markers_icon.clone()));
  1417. var c = new OpenLayers.LonLat(lng,lat).transform(map.displayProjection, map.projection)
  1418. var point = new OpenLayers.Geometry.Point(c.lon, c.lat);
  1419. var pointFeature = new OpenLayers.Feature.Vector(point);
  1420. pointFeature.attributes = {
  1421. name: ret[i].name
  1422. };
  1423. try {
  1424. markers.addFeatures([pointFeature]);
  1425. } catch (err) {
  1426. //Catch IE9 error. pointFeature is still mapping.
  1427. }
  1428. }
  1429. setTimeout(function(){ //fix for some browsers
  1430. parent.jq('$featuretool')[0].style.display=""
  1431. parent.document.getElementById('featureOutput').innerHTML = "<table>" + body + "</table>";
  1432. },200)
  1433. }
  1434. }
  1435. function initMarkersLayer() {
  1436. var renderer = OpenLayers.Util.getParameters(window.location.href).renderer;
  1437. renderer = (renderer) ? [renderer] : OpenLayers.Layer.Vector.prototype.renderers;
  1438. markers = new OpenLayers.Layer.Vector("Nearest Localities", {
  1439. styleMap: new OpenLayers.StyleMap({
  1440. 'default':{
  1441. strokeColor: "#FFFF00",
  1442. strokeOpacity: 1,
  1443. strokeWidth: 2,
  1444. fillColor: "#FF0000",
  1445. fillOpacity: 1,
  1446. pointRadius: 6,
  1447. pointerEvents: "visiblePainted",
  1448. label : "${name}",
  1449. fontColor: "black",
  1450. fontSize: "12px",
  1451. fontFamily: "Courier New, monospace",
  1452. fontWeight: "bold",
  1453. labelAlign: "left",
  1454. labelXOffset: "5",
  1455. labelYOffset: "0"
  1456. }
  1457. }),
  1458. renderers: renderer
  1459. });
  1460. map.addLayer(markers);
  1461. }
  1462. var hovercontrol = null;
  1463. var hovercontrolprevpos = null;
  1464. function initHover() {
  1465. hovercontrol = new OpenLayers.Handler.Hover({
  1466. 'map': map
  1467. }, {
  1468. 'pause': function(e) {
  1469. var pt = map.getLonLatFromViewPortPx(new
  1470. OpenLayers.Pixel(e.xy.x, e.xy.y) );
  1471. pt = pt.transform(map.projection, map.displayProjection);
  1472. var this_pos = pt.lat + "," + pt.lon;
  1473. if(this_pos == hovercontrolprevpos) {
  1474. return;
  1475. }
  1476. hovercontrolprevpos = this_pos;
  1477. var displayFull = false;
  1478. if ($("#lvalues").hasClass("layervaluesMax")) {
  1479. displayFull = true;
  1480. }
  1481. var output = parent.document.getElementById('hoverOutput');
  1482. var data = envLayerHover(e,displayFull);
  1483. if(data != null) {
  1484. if (displayFull) {
  1485. output.innerHTML = "<table><tr><td colspan='5'><b>Point " + pt.lon.toPrecision(8) + ", " + pt.lat.toPrecision(8) + "</b></td></tr>" + data + "</table>";
  1486. //$('#hoverOutput').html("<table><tr><td colspan='5'><b>Point " + pt.lon.toPrecision(8) + ", " + pt.lat.toPrecision(8) + "</b></td></tr>" + data + "</table>");
  1487. } else {
  1488. $('div#lvalues').html(data);
  1489. }
  1490. } else {
  1491. output.innerHTML = "No values to display";
  1492. }
  1493. },
  1494. 'delay': 200
  1495. });
  1496. hovercontrol.fallThrough = true;
  1497. hovercontrol.activate();
  1498. }
  1499. function toggleActiveHover() {
  1500. if(hovercontrol != null) {
  1501. hovercontrol.deactivate();
  1502. hovercontrol = null;
  1503. document.getElementById("hoverTool").style.backgroundImage = "url('img/overview_replacement_off.gif')";
  1504. setTimeout(function() { //for IE9
  1505. parent.jq('$hovertool')[0].style.display="none"
  1506. }, 100)
  1507. } else {
  1508. initHover();
  1509. parent.document.getElementById('hoverOutput').innerHTML = "Hover cursor over map to view layer values";
  1510. document.getElementById("hoverTool").style.backgroundImage = "url('img/overview_replacement.gif')";
  1511. // setTimeout(function() { //for IE9
  1512. // parent.jq('$hovertool')[0].style.display=""
  1513. // }, 100)
  1514. }
  1515. }
  1516. var nearestcontrol = null;
  1517. var nearestcontrolprevpos = null;
  1518. function initNearest() {
  1519. nearestcontrol = new OpenLayers.Handler.Click({
  1520. 'map': map
  1521. }, {
  1522. 'click': function(e) {
  1523. var pt = map.getLonLatFromViewPortPx(new
  1524. OpenLayers.Pixel(e.xy.x, e.xy.y) );
  1525. pt = pt.transform(map.projection, map.displayProjection);
  1526. var this_pos = pt.lat + "," + pt.lon;
  1527. if(this_pos == nearestcontrolprevpos) {
  1528. return;
  1529. }
  1530. nearestcontrolprevpos = this_pos;
  1531. setTimeout(function(){ //fix for some browsers
  1532. parent.document.getElementById('nearestOutput').innerHTML = "<table><tr><td colspan='5'><b>Point " + pt.lon.toPrecision(8) + ", " + pt.lat.toPrecision(8) + "</b></td></tr><tr><td>&nbsp;</td></tr><tr><td>Retrieving...</td></tr></table>"
  1533. },100)
  1534. setTimeout(function(){
  1535. var data = envLayerNearest(e);
  1536. if(data != null) {
  1537. setTimeout(function(){ //fix for some browsers
  1538. parent.document.getElementById('nearestOutput').innerHTML = "<table><tr><td colspan='5'><b>Point " + pt.lon.toPrecision(8) + ", " + pt.lat.toPrecision(8) + "</b></td></tr>" + data + "</table>";
  1539. },200)
  1540. } else {
  1541. setTimeout(function(){ //fix for some browsers
  1542. parent.document.getElementById('nearestOutput').innerHTML = "No values to display";
  1543. },200)
  1544. }
  1545. }, 2);
  1546. }
  1547. });
  1548. nearestcontrol.fallThrough = true;
  1549. nearestcontrol.activate();
  1550. }
  1551. function toggleActiveNearest() {
  1552. if(nearestcontrol != null) {
  1553. nearestcontrol.deactivate();
  1554. nearestcontrol = null;
  1555. setTimeout(function() {
  1556. parent.jq('$nearesttool')[0].style.display="none"
  1557. }, 100)
  1558. } else {
  1559. initNearest();
  1560. parent.document.getElementById('nearestOutput').innerHTML = "Click on the map for the nearest localities.";
  1561. setTimeout(function() {
  1562. parent.jq('$nearesttool')[0].style.display=""
  1563. }, 100)
  1564. }
  1565. }
  1566. function toggleActiveFeatures() {
  1567. if(nearestcontrol != null) {
  1568. nearestcontrol.deactivate();
  1569. nearestcontrol = null;
  1570. setTimeout(function() {
  1571. parent.jq('$featuretool')[0].style.display="none"
  1572. }, 100)
  1573. } else {
  1574. initNearest();
  1575. parent.document.getElementById('featureOutput').innerHTML = "";
  1576. setTimeout(function() {
  1577. parent.jq('$featuretool')[0].style.display=""
  1578. }, 100)
  1579. }
  1580. }
  1581. //Function to enable and disable the clickEventHandler
  1582. function toggleClickHandler(state){
  1583. if (state == false){
  1584. clickEventHandler.deactivate();
  1585. }
  1586. else{
  1587. clickEventHandler.activate();
  1588. }
  1589. }
  1590. //string extensions - put back in here - didn't seem to work when I added this code to index.js
  1591. if(typeof(String.prototype.capitalize) === "undefined"){
  1592. String.prototype.capitalize = function() {
  1593. return this.charAt(0).toUpperCase() + this.slice(1);
  1594. }
  1595. }
  1596. if(typeof(String.prototype.trim) === "undefined"){
  1597. String.prototype.trim = function()
  1598. {
  1599. return String(this).replace(/^\s+|\s+$/g, '');
  1600. };
  1601. }
  1602. //backwards-compatible console logging
  1603. if (window['loadFirebugConsole']) {
  1604. window.loadFirebugConsole();
  1605. } else {
  1606. if (!window['console']) {
  1607. window.console = {};
  1608. window.console.info = function(msg){
  1609. return;
  1610. }
  1611. window.console.log = function(msg){
  1612. return;
  1613. }
  1614. window.console.warn = function(msg){
  1615. alert("Console warning: " + msg);
  1616. }
  1617. window.console.error = function(msg){
  1618. alert("Console error: " + msg);
  1619. }
  1620. }
  1621. }
  1622. function getLayerValue(layer, lat, lon) {
  1623. var url = parent.jq('$layers_url')[0].innerHTML + "/intersect/" + layer + "/" + lat + "/" + lon;
  1624. var ret = "";
  1625. $.ajax({
  1626. url: proxy_script + URLEncode(url),
  1627. dataType: "json",
  1628. success: function(data){
  1629. ret = data;
  1630. },
  1631. async: false
  1632. });
  1633. return ret;
  1634. }
  1635. function getPointsOfInterest(layer, lat, lon, dotradius) {
  1636. dotradius = dotradius*1 + 3
  1637. var px = map.getViewPortPxFromLonLat(new OpenLayers.LonLat(lon,lat).transform(
  1638. new OpenLayers.Projection("EPSG:4326"),map.getProjectionObject()));
  1639. var lonlat = map.getLonLatFromViewPortPx(new OpenLayers.Pixel(px.x + dotradius, px.y + dotradius)).transform(
  1640. map.getProjectionObject(), new OpenLayers.Projection("EPSG:4326"));
  1641. var lonSize = Math.abs(lon - lonlat.lon);
  1642. var latSize = Math.abs(lat - lonlat.lat);
  1643. var minLon = lon-lonSize;
  1644. var maxLon = lon+lonSize;
  1645. var minLat = lat-latSize;
  1646. var maxLat = lat+latSize;
  1647. var bbox = "POLYGON((" + minLon + "%20" + minLat + "," + minLon + "%20" + maxLat + "," + maxLon + "%20" + maxLat + "," + maxLon + "%20" + minLat + "," + minLon + "%20" + minLat + "))";
  1648. var url = layer.pointsOfInterestWS + "?wkt=" + bbox
  1649. var ret = null;
  1650. $.ajax({
  1651. type: "GET",
  1652. url: proxy_script + URLEncode(url),
  1653. dataType: "json",
  1654. success: function(data){
  1655. ret = data;
  1656. },
  1657. async: false
  1658. });
  1659. if (ret != null) {
  1660. return ret;
  1661. } else {
  1662. return null;
  1663. }
  1664. }
  1665. function getOccurrence(layer, query, lat, lon, start, pos, dotradius) {
  1666. dotradius = dotradius*1 + 3
  1667. var px = map.getViewPortPxFromLonLat(new OpenLayers.LonLat(lon,lat).transform(
  1668. new OpenLayers.Projection("EPSG:4326"),map.getProjectionObject()));
  1669. var lonlat = map.getLonLatFromViewPortPx(new OpenLayers.Pixel(px.x + dotradius, px.y + dotradius)).transform(
  1670. map.getProjectionObject(), new OpenLayers.Projection("EPSG:4326"));
  1671. var lonSize = Math.abs(lon - lonlat.lon);
  1672. var latSize = Math.abs(lat - lonlat.lat);
  1673. //console.log(layer);
  1674. var url = layer.bs + "/occurrences/search?q=" + query
  1675. + "&fq=longitude:[" + (lon-lonSize) + "%20TO%20" + (lon+lonSize) + "]"
  1676. + "&fq=latitude:[" + (lat-latSize) + "%20TO%20" + (lat+latSize) + "]"
  1677. + "&pageSize=1&facet=false";
  1678. var url_ui = layer.ws + "/occurrences/search?q=" + query
  1679. + "&fq=longitude:[" + (lon-lonSize) + "%20TO%20" + (lon+lonSize) + "]"
  1680. + "&fq=latitude:[" + (lat-latSize) + "%20TO%20" + (lat+latSize) + "]";
  1681. var ret = null;
  1682. $.ajax({
  1683. url: proxy_script + URLEncode(url + "&start=" + start),
  1684. dataType: "json",
  1685. success: function(data){
  1686. ret = data;
  1687. },
  1688. async: false
  1689. });
  1690. query_size[pos] = 0;
  1691. if(ret != null) {
  1692. query_layer[pos] = layer;
  1693. query_size[pos] = ret.totalRecords;
  1694. query_[pos] = query;
  1695. query_url[pos] = url;
  1696. query_ui_forall = url_ui;
  1697. return ret.occurrences[0];
  1698. } else {
  1699. return null;
  1700. }
  1701. }
  1702. function getOccurrenceUploaded(layer, query, lat, lon, start, pos, dotradius) {
  1703. dotradius = dotradius*1 + 3
  1704. var px = map.getViewPortPxFromLonLat(new OpenLayers.LonLat(lon,lat).transform(
  1705. new OpenLayers.Projection("EPSG:4326"),map.getProjectionObject()));
  1706. var lonlat = map.getLonLatFromViewPortPx(new OpenLayers.Pixel(px.x + dotradius, px.y + dotradius)).transform(
  1707. map.getProjectionObject(), new OpenLayers.Projection("EPSG:4326"));
  1708. var lonSize = Math.abs(lon - lonlat.lon);
  1709. var latSize = Math.abs(lat - lonlat.lat);
  1710. var url = parent.jq('$webportal_url')[0].innerHTML + "/ws/occurrences?q=" + query
  1711. + "&box=" + (lon-lonSize) + "," + (lat-latSize) + "," + (lon+lonSize) + "," + (lat+latSize);
  1712. var ret = null;
  1713. $.ajax({
  1714. url: proxy_script + URLEncode(url + "&start=" + start),
  1715. dataType: "json",
  1716. success: function(data){
  1717. ret = data;
  1718. },
  1719. async: false
  1720. });
  1721. query_size[pos] = 0;
  1722. if(ret != null) {
  1723. query_layer[pos] = layer;
  1724. query_size[pos] = ret.totalRecords;
  1725. query_[pos] = query;
  1726. query_url[pos] = url;
  1727. return ret.occurrences[0];
  1728. } else {
  1729. return null;
  1730. }
  1731. }
  1732. function checkIfLoadPanoramio() {
  1733. if (!shownPicture){
  1734. panoramioLoadingImage("block");
  1735. loadPanoramio(0,49);
  1736. }
  1737. else {
  1738. removePanoramio(true);
  1739. }
  1740. $('#addPanoramio').toggleClass('imagesOff').toggleClass('imagesOn');
  1741. }
  1742. function loadPanoramio(pictureIndexFrom,pictureIndexTo) {
  1743. panoramioLoading++;
  1744. //document.getElementById("addPanoramio").style.backgroundImage = "url('img/panoramio-marker.png')";
  1745. var popup21, selectControl, selectedFeature;
  1746. var panoramio_style;
  1747. //Obtain Bbox coords
  1748. var proj = new OpenLayers.Projection("EPSG:4326");
  1749. var ext = map.getExtent().transform(map.getProjectionObject(), proj);
  1750. var minx = ext.left;
  1751. var miny = ext.bottom;
  1752. var maxx = ext.right;
  1753. var maxy = ext.top;
  1754. url = "http://www.panoramio.com/map/get_panoramas.php";
  1755. var parameters = {
  1756. order:'public',
  1757. set:'full',
  1758. from:pictureIndexFrom,
  1759. to:pictureIndexTo,
  1760. minx: minx,
  1761. miny: miny,
  1762. maxx: maxx,
  1763. maxy: maxy,
  1764. size:'thumbnail',
  1765. mapfilter: true
  1766. };
  1767. OpenLayers.loadURL(url, parameters, this, showPhotos);
  1768. function showPhotos(response) {
  1769. var json = new OpenLayers.Format.JSON();
  1770. var panoramio = json.read(response.responseText);
  1771. var features = new Array(panoramio.photos.length);
  1772. for (var i = 0; i < panoramio.photos.length; i++)
  1773. {
  1774. var upload_date = panoramio.photos[i].upload_date;
  1775. var owner_name = panoramio.photos[i].owner_name;
  1776. var photo_id = panoramio.photos[i].photo_id;
  1777. var longitude =panoramio.photos[i].longitude;
  1778. var latitude = panoramio.photos[i].latitude;
  1779. var pheight = panoramio.photos[i].height;
  1780. var pwidth = panoramio.photos[i].width;
  1781. var photo_title = panoramio.photos[i].photo_title;
  1782. var owner_url = panoramio.photos[i].owner_url;
  1783. var owner_id = panoramio.photos[i].owner_id;
  1784. var photo_file_url = panoramio.photos[i].photo_file_url;
  1785. var photo_url = panoramio.photos[i].photo_url;
  1786. var fpoint = new OpenLayers.Geometry.Point(longitude,latitude);
  1787. fpoint.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));
  1788. var attributes = {
  1789. 'upload_date' : upload_date,
  1790. 'owner_name':owner_name,
  1791. 'photo_id':photo_id,
  1792. 'longitude':longitude,
  1793. 'latitude':latitude,
  1794. 'pheight':pheight,
  1795. 'pwidth':pwidth,
  1796. 'pheight':pheight,
  1797. 'photo_title':photo_title,
  1798. 'owner_url':owner_url,
  1799. 'owner_id':owner_id,
  1800. 'photo_file_url':photo_file_url,
  1801. 'photo_url':photo_url
  1802. }
  1803. features[i] = new OpenLayers.Feature.Vector(fpoint,attributes);
  1804. }//Outside for loop
  1805. panoramio_style = new OpenLayers.StyleMap(OpenLayers.Util.applyDefaults({
  1806. pointRadius: 15,
  1807. fillColor: "red",
  1808. fillOpacity: 1,
  1809. strokeColor: "black",
  1810. externalGraphic: "${photo_file_url}",
  1811. select: {
  1812. fillColor: "red",
  1813. pointRadius: 20,
  1814. strokeColor: "yellow",
  1815. strokeWidth: 3
  1816. }
  1817. //externalGraphic: "img/panoramio-marker.png"
  1818. }, OpenLayers.Feature.Vector.style["default"]));
  1819. vectorLayer = new OpenLayers.Layer.Vector("Panoramio Photos", {
  1820. styleMap: panoramio_style
  1821. });
  1822. registerPanoramio(vectorLayer);
  1823. vectorLayer.addFeatures(features);
  1824. this.map.addLayer(vectorLayer);
  1825. selectControl = new OpenLayers.Control.SelectFeature(vectorLayer, {
  1826. onSelect: onFeatureSelect,
  1827. onUnselect: onFeatureUnselect
  1828. });
  1829. this.map.addControl(selectControl);
  1830. selectControl.activate();
  1831. shownPicture = true;
  1832. }//End showPhotos
  1833. function onFeatureSelect(feature) {
  1834. selectedFeature = feature;
  1835. // HTML PopUp
  1836. var html = "<a href='http://www.panoramio.com/' target='_blank'><img src='img/panoramio_logo_small.gif' /></a><br />";
  1837. html += "<a href='"+feature.attributes.photo_url + "' target='_blank'>";
  1838. html += "<img src ='http://mw2.google.com/mw-panoramio/photos/small/"+feature.attributes.photo_id + ".jpg' border = '3' alt ='"+feature.attributes.photo_title +"' />";
  1839. html += "</a><br />";
  1840. html += "<a href='"+feature.attributes.photo_url + "' target='_blank'><strong>"+feature.attributes.photo_title +"</strong></a><br />";
  1841. html += "by <a href='"+feature.attributes.owner_url + "' target='_blank'>"+feature.attributes.owner_name +"</a><br />";
  1842. //var html = "<h2>"+feature.attributes.photo_title +"</h2> <p>" +" <a href='photo/"+feature.attributes.photo_id+"'><Img src ='http://mw2.google.com/mw-panoramio/photos/small/"+feature.attributes.photo_id + ".jpg ' border = '3' alt ='' /></a>";
  1843. popup = new OpenLayers.Popup.FramedCloud("featurePopup",
  1844. feature.geometry.getBounds().getCenterLonLat(),
  1845. new OpenLayers.Size(400,400),
  1846. "<div id='sppopup'>" + "Loading..." + "</div>" // style='width: 350px; height: 50px;'
  1847. ,
  1848. null, true, closePopup);
  1849. popup.autoSize = true;
  1850. if (feature.attributes.pwidth > feature.attributes.pheight) {
  1851. popup.minSize = new OpenLayers.Size(300,250);
  1852. } else if (feature.attributes.pwidth < feature.attributes.pheight) {
  1853. popup.minSize = new OpenLayers.Size(300,375);
  1854. } else {
  1855. popup.minSize = new OpenLayers.Size(315,375);
  1856. }
  1857. var feat = popup;
  1858. feat.popup = popup;
  1859. popup.feature = feat;
  1860. map.addPopup(popup, true);
  1861. infoHtml = "<div id='sppopup2'>"
  1862. + html
  1863. + "</div>";
  1864. if (document.getElementById("sppopup") != null) {
  1865. document.getElementById("sppopup").innerHTML = infoHtml;
  1866. }
  1867. //popup2.setSize(500, 500);
  1868. // setTimeout(function(){
  1869. // console.log("setting and updating pop up size");
  1870. // //popup.setSize(500, 500);
  1871. // popup.updateSize();
  1872. // }, 5000);
  1873. shownPicturePopup = true;
  1874. }
  1875. function closePopup(evt) {
  1876. shownPicturePopup = false;
  1877. //onPopupClose(evt);
  1878. try {
  1879. map.removePopup(this.feature.popup);
  1880. this.feature.popup.destroy();
  1881. this.feature.popup = null;
  1882. selectControl.unselect(this.feature);
  1883. } catch(err) {
  1884. }
  1885. }
  1886. function onFeatureUnselect(feature) {
  1887. //this.map.removePopup(feature.popup);
  1888. //feature.popup.destroy();
  1889. //feature.popup = null;
  1890. closePopup();
  1891. }
  1892. }
  1893. function removePanoramio(clearPopups) {
  1894. if (clearPopups) {
  1895. if (this.map.popups[0]!=null) {
  1896. this.map.removePopup(this.map.popups[0]);
  1897. }
  1898. }
  1899. this.map.removeLayer(vectorLayer);
  1900. shownPicture = false;
  1901. shownPicturePopup = false;
  1902. panoramioLoading = 0;
  1903. }
  1904. function registerPanoramio(vectorLayer) {
  1905. vectorLayer.events.register('beforefeaturesadded', this, panoramioloadStart);
  1906. vectorLayer.events.register('featuresadded', this, panoramioloadEnd);
  1907. //vectorLayer.events.on({"loadstart":panoramioloadStart,"loadend":panoramioloadStart});
  1908. }
  1909. function panoramioloadStart() {
  1910. if (panoramioLoading > 0) {
  1911. panoramioLoadingImage("block");
  1912. }
  1913. }
  1914. function panoramioloadEnd() {
  1915. panoramioLoading--;
  1916. if (panoramioLoading == 0) {
  1917. panoramioLoadingImage("none");
  1918. }
  1919. }
  1920. function panoramioLoadingImage(display) {
  1921. var div = document.getElementById("loader");
  1922. if (div != null) {
  1923. if (display == "none") {
  1924. //jQuery("#panoramioLoader").hide(2000);
  1925. jQuery("#loader").hide(2000);
  1926. }
  1927. else {
  1928. if (panoramioLoading > 0) {
  1929. div.style.display=display;
  1930. }
  1931. }
  1932. }
  1933. }
  1934. //animateStart("Eucalyptus",2000,1760,2012,30,0)"
  1935. function animateStop(layername) {
  1936. var layers = map.getLayersByName(layername);
  1937. if (layers.length == 0) return;
  1938. var layer = layers[0];
  1939. layer.animate = "stop";
  1940. }
  1941. /**
  1942. * Start the animation.
  1943. *
  1944. * @param layername layer to animate
  1945. * @param animateDenom 0=month, 1=year
  1946. * @param interval time interval between loading layers
  1947. * @param start startYear or startMonth
  1948. * @param end endYear or startMonth
  1949. * @param step gaps between layers - e.g. 1 year, 5 year
  1950. */
  1951. function animateStart(layername, animateDenom, interval, start, end, step) {
  1952. var layers = map.getLayersByName(layername);
  1953. if (layers.length == 0) {
  1954. cleanupAnimationLayers(layername);
  1955. return;
  1956. }
  1957. var layer = layers[0];
  1958. if(layer.url_orig == undefined) {
  1959. cleanupAnimationLayers(layername);
  1960. layer.url_orig = layer.url;
  1961. layer.animate = "playing"
  1962. }
  1963. console.log("step:" + step);
  1964. console.log("start:" + start);
  1965. console.log("end:" + end);
  1966. //create layers
  1967. var newlayers = [];
  1968. if(animateDenom != 0){
  1969. newlayers = getYearLayers(layer,start, end, step);
  1970. } else {
  1971. newlayers = getMonthLayers(layer,start, end);
  1972. }
  1973. map.addLayers(newlayers);
  1974. layer.animated_layers = newlayers;
  1975. animateLayered(layername, animateDenom, interval, start, end, step, 0);
  1976. }
  1977. function getYearLayers(layer,startYear,endYear, step){
  1978. var newlayers = [];
  1979. var page = 0;
  1980. while (page * step + startYear <= endYear) {
  1981. newlayers[page] = layer.clone();
  1982. newlayers[page].setName(layer.name + "__animation__" + page);
  1983. newlayers[page].url = layer.url_orig + "&fq=year:[" + (1 * startYear + step * (page)) + " TO " + (1*startYear + step*(page+1)) + "]";
  1984. console.log("Adding layer URL: " + newlayers[page].url);
  1985. page = page + 1;
  1986. }
  1987. return newlayers;
  1988. }
  1989. function getMonthLayers(layer,startYear,endYear){
  1990. var newlayers = [];
  1991. var page = 0;
  1992. while (page <= 11) {
  1993. var currentMonth = page + 1;
  1994. newlayers[page] = layer.clone();
  1995. newlayers[page].setName(layer.name + "__animation__" + page);
  1996. var currentMonthAsString = currentMonth<10 ? "0" + currentMonth : ""+currentMonth;
  1997. newlayers[page].url = layer.url_orig + "&fq=month:" + currentMonthAsString+"&fq=year:[" + startYear + " TO " + endYear + "]";
  1998. console.log("Adding layer URL: " + newlayers[page].url);
  1999. page = page + 1
  2000. }
  2001. return newlayers;
  2002. }
  2003. function animateLayered(layername, animateDenom, interval, start, end, step, page) {
  2004. var layers = map.getLayersByName(layername);
  2005. if (layers.length == 0) {
  2006. cleanupAnimationLayers(layername);
  2007. return;
  2008. }
  2009. var layer = layers[0];
  2010. var status = parent.document.getElementById('animationStatus');
  2011. if(page >= layer.animated_layers.length) {
  2012. page = 0;
  2013. //end animation when at the end
  2014. cleanupAnimationLayers(layername);
  2015. if(status) status.innerHTML = "stopped";
  2016. return;
  2017. }
  2018. if(layer.animate == "stop" ||
  2019. layer.animated_layers[page].url.indexOf(layer.url) < 0) {
  2020. layer.url = layer.url_orig;
  2021. layer.url_orig = undefined;
  2022. layer.display(true);
  2023. cleanupAnimationLayers(layername);
  2024. if(status) status.innerHTML = "stopped";
  2025. } else {
  2026. layer.display(false);
  2027. for(i=0;i<page;i++) {
  2028. // layer.animated_layers[i].setOpacity(((i+1)/(2*page)));
  2029. // layer.animated_layers[i].display(true);
  2030. layer.animated_layers[i].display(false);
  2031. }
  2032. //layer.animated_layers[page].setOpacity(layer.opacity);
  2033. layer.animated_layers[page].display(true);
  2034. for(i=page+1;i<layer.animated_layers.length;i++) {
  2035. layer.animated_layers[i].display(false);
  2036. }
  2037. if (status) {
  2038. if(animateDenom == "1"){
  2039. status.innerHTML = "" + (1*start + step*(page)) + " to " + (1*start + step*(page+1));
  2040. } else {
  2041. switch(page)
  2042. {
  2043. case 0: status.innerHTML = "January"; break;
  2044. case 1: status.innerHTML = "February"; break;
  2045. case 2: status.innerHTML = "March"; break;
  2046. case 3: status.innerHTML = "April"; break;
  2047. case 4: status.innerHTML = "May"; break;
  2048. case 5: status.innerHTML = "June"; break;
  2049. case 6: status.innerHTML = "July"; break;
  2050. case 7: status.innerHTML = "August"; break;
  2051. case 8: status.innerHTML = "September"; break;
  2052. case 9: status.innerHTML = "October"; break;
  2053. case 10: status.innerHTML = "November"; break;
  2054. case 11: status.innerHTML = "December"; break;
  2055. }
  2056. }
  2057. }
  2058. var callback = "animateLayered('" + layername+ "'," + animateDenom + ", " + interval + ", " + start + ", " + end + ", " + step + ", " + (page + 1) + ")";
  2059. console.log("Setting callback to: " + callback);
  2060. setTimeout(callback, interval);
  2061. }
  2062. }
  2063. function stopAllAnimations() {
  2064. for (i=0;i<map.layers.length;i++) {
  2065. if (map.layers[i].animate == 'playing') {
  2066. animateStop(map.layers[i].name);
  2067. i = 0;
  2068. }
  2069. }
  2070. }
  2071. function cleanupAnimationLayers(layername) {
  2072. for (i=0;i<map.layers.length;i++) {
  2073. if (map.layers[i].name.indexOf(layername + "__animation__") == 0) {
  2074. map.removeLayer(map.layers[i]);
  2075. i = 0;
  2076. }
  2077. }
  2078. map.getLayersByName(layername)[0].display(true);
  2079. }