PageRenderTime 95ms CodeModel.GetById 11ms app.highlight 71ms RepoModel.GetById 1ms 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

Large files files are truncated, but you can click here to view the full file

   1/**
   2 * Instance of OpenLayers map
   3 */
   4var map;
   5var proxy_script="/webportal/RemoteRequest?url=";
   6var tmp_response;
   7var popup;
   8var selectControl;
   9
  10var popupWidth = 435; //pixels
  11var popupHeight = 370; //pixels
  12
  13var requestCount = 0; // getFeatureInfo request count
  14var queries = new Object(); // current getFeatureInfo requests
  15var queries_valid_content = false;
  16var timestamp; // timestamp for getFeatureInfo requests
  17var X,Y; // getfeatureInfo Click point
  18
  19var clickEventHandler; // single clickhandler
  20var toolPanel; // container for OpenLayer controls
  21var pan; // OpenLayers.Control.Navigation
  22var zoom; // OpenLayers.Control.ZoomBox
  23var areaToolsButton// OpenLayers.Control.Button
  24//var selectableLayers = new Array();
  25/**
  26 * Associative array of all current active map layers except
  27 * for baselayers
  28 */
  29var mapLayers = new Object();
  30
  31/**
  32 * Associative array of all available base layers
  33 */
  34var baseLayers = new Object();
  35
  36/**
  37 * Key of the currently selected base layer in baseLayers
  38 */
  39var currentBaseLayer = null;
  40
  41var selectionLayers = new Array();
  42
  43var mapClickControl;
  44var polyControl = null;
  45var radiusControl = null;  //for deactivate after drawing
  46var boxControl = null;	//for deactivate after drawing
  47var areaSelectControl = null;
  48var filteringPolygon = null;	//temporary for destroy option after display
  49var alocPolygon = null;			//temporary for destroy option after display
  50var polygonLayer = null;
  51var boxLayer = null;
  52var radiusLayer = null;
  53var featureSelectLayer = null;
  54var featureSpeciesSelectLayer = null;
  55var areaSelectOn = false;
  56var layersLoading = 0;
  57var panoramioLoading = 0;
  58var layername; // current layer name
  59
  60var attempts = 0;
  61var libraryLoaded = false;
  62var checkLibraryLoadedTimeout = null;
  63var libraryCheckIntervalMs=100;
  64var secondsToWaitForLibrary=30;
  65var maxAttempts = (secondsToWaitForLibrary * 1000) / libraryCheckIntervalMs;
  66
  67var selecteFeature;
  68
  69// check if the Google Layer automatically got
  70// switched between normal and hybrid around zoom level 16
  71var autoBaseLayerSwitch = false;
  72// 0 = normal
  73// 1 = user-switch
  74// 2 = auto-switch 
  75var baseLayerSwitchStatus = 0;
  76var activeAreaPresent = false;
  77var shownPicture = false;
  78var shownPicturePopup = false;
  79var vectorLayer;
  80
  81
  82function stopCheckingLibraryLoaded() {
  83    clearInterval(checkLibraryLoadedTimeout);
  84}
  85
  86function registerLayer(layer) {
  87    layer.events.register('loadstart', this, loadStart);
  88    layer.events.register('loadend', this, loadEnd);
  89}
  90
  91function loadStart() {
  92    if (layersLoading == 0) {
  93        toggleLoadingImage("block");
  94    }
  95    layersLoading++;
  96}
  97
  98function loadEnd() {
  99    layersLoading--;
 100    if (layersLoading == 0) {
 101        toggleLoadingImage("none");
 102    }
 103//signal webportal
 104    
 105}
 106
 107function toggleLoadingImage(display) {
 108    var div = document.getElementById("loader");
 109    if (div != null) {
 110        if (display == "none") {
 111            jQuery("#loader").hide(2000);
 112        }
 113        else {
 114            setTimeout(function(){
 115                if (layersLoading > 0) {
 116                    div.style.display=display;
 117                }
 118            }, 2000);
 119        }
 120    }
 121}
 122
 123function checkLibraryLoaded() {
 124    if (typeof OpenLayers == 'undefined') {
 125        if ((attempts < maxAttempts) && (typeof OpenLayers == 'undefined')) {
 126            attempts++;
 127        }
 128        else if (attempts == maxAttempts) {
 129            // give up loading - too many attempts
 130            stopCheckingLibraryLoaded();
 131            alert(
 132                "Map not loaded after waiting " + secondsToWaitForLibrary + " seconds.  " +
 133                "Please wait a moment and then reload the page.  If this does not fix your " +
 134                "problem, please contact ALA for assistance"
 135                );
 136        }
 137    }
 138    else {
 139        // library loaded OK stop delay timer
 140        stopCheckingLibraryLoaded();
 141        libraryLoaded = true;
 142
 143        parent.updateSafeToLoadMap(libraryLoaded);
 144
 145        // ok now init the map...
 146        parent.onIframeMapFullyLoaded();
 147    }
 148
 149}
 150
 151var bLayer,bLayer2,bLayer3,bLayer4;
 152function loadBaseMap() {
 153    goToLocation(134, -25, 4);
 154    
 155// Google.v3 uses EPSG:900913 as projection, so we have to
 156// transform our coordinates
 157//    map.setCenter(
 158//        new OpenLayers.LonLat(134, -25).transform(
 159//            new OpenLayers.Projection("EPSG:4326"),
 160//            map.getProjectionObject()),
 161//        4);
 162
 163//    $(window).resize(function() {
 164//        setTimeout("map.pan(1,1);",500);
 165//    });
 166}
 167
 168function goToLocation(lon, lat, zoom) {
 169    // Google.v3 uses EPSG:900913 as projection, so we have to
 170    // transform our coordinates
 171    map.setCenter(
 172        new OpenLayers.LonLat(lon, lat).transform(
 173            new OpenLayers.Projection("EPSG:4326"),
 174            map.getProjectionObject()),
 175        zoom);
 176}
 177
 178function changeBaseLayer(type) {
 179    if (type == 'normal') {
 180        map.setBaseLayer(bLayer2);
 181    } else if (type == 'hybrid') {
 182        map.setBaseLayer(bLayer);
 183    } else if (type == 'minimal') {
 184        map.setBaseLayer(bLayer3);
 185    } else if (type == 'outline') {
 186        map.setBaseLayer(bLayer4);
 187    }
 188}
 189
 190function buildMap() {
 191    checkLibraryLoadedTimeout = setInterval('checkLibraryLoaded()', libraryCheckIntervalMs);
 192}
 193
 194function buildMapReal() {
 195
 196    // fix IE7 errors due to being in an iframe
 197    document.getElementById('mapdiv').style.width = '100%';
 198    document.getElementById('mapdiv').style.height = '100%';
 199
 200    // highlight for the scale and lonlat info
 201    $("div#mapinfo").hover( function(){$(this).css("opacity","0.9");}, function(){$(this).css("opacity","0.5");} );
 202    $("div#layervalues").hover( function(){$(this).css("opacity","0.9");}, function(){$(this).css("opacity","0.5");} );
 203
 204    // proxy.cgi script provided by OpenLayers written in Python, must be on the same domain
 205    OpenLayers.ProxyHost = proxy_script;
 206
 207
 208    // ---------- map setup --------------- //
 209
 210    var mapControls = [
 211    new OpenLayers.Control.PanZoomBar({
 212        div: document.getElementById('controlPanZoom')
 213    }),
 214    new OpenLayers.Control.LayerSwitcher(),
 215    new OpenLayers.Control.ScaleLine({
 216        div: document.getElementById('mapscale'),
 217        geodesic: true
 218    }),
 219
 220    new OpenLayers.Control.Attribution(),
 221    new OpenLayers.Control.MousePosition({
 222        div: document.getElementById('mapcoords'),
 223        prefix: '<b>Lon:</b> ',
 224        separator: ' <BR><b>Lat:</b> '
 225    }),
 226    new OpenLayers.Control.Navigation()
 227    ];
 228    var mapOptions = {
 229        projection: new OpenLayers.Projection("EPSG:900913"),
 230        displayProjection: new OpenLayers.Projection("EPSG:4326"),
 231        units: "m",
 232        numZoomLevels: 18,
 233        maxResolution: 156543.0339,
 234        maxExtent: new OpenLayers.Bounds(-20037508, -20037508,
 235            20037508, 20037508.34),
 236        controls: mapControls
 237    };
 238    map = new OpenLayers.Map('mapdiv', mapOptions);
 239
 240
 241    // make OL compute scale according to WMS spec
 242    OpenLayers.DOTS_PER_INCH = 25.4 / 0.28;
 243    // Stop the pink tiles appearing on error
 244    OpenLayers.Util.onImageLoadError = function() {
 245        this.style.display = "";
 246        this.src="img/blank.png";
 247    }
 248
 249    bLayer = new OpenLayers.Layer.Google("Google Hybrid",
 250    {
 251        type: google.maps.MapTypeId.HYBRID,
 252        wrapDateLine: false,
 253        'sphericalMercator': true
 254    });
 255    bLayer2 = new OpenLayers.Layer.Google("Google Streets",
 256    {
 257        wrapDateLine: false,
 258        'sphericalMercator': true
 259    });
 260    bLayer3 = new OpenLayers.Layer.OSM();
 261    
 262    bLayer4 = new OpenLayers.Layer.WMS("Outline",parent.jq('$geoserver_url')[0].innerHTML + "/gwc/service/wms/reflect",{
 263        layers:"ALA:world"
 264    },
 265
 266    {
 267        isBaseLayer: true,
 268        'wrapDateLine': true,
 269        projection: new OpenLayers.Projection("EPSG:900913"),
 270        'sphericalMercator': true
 271    }
 272    );
 273    map.addLayers([bLayer2,bLayer,bLayer3,bLayer4]);
 274    parent.bLayer = bLayer;
 275    parent.bLayer2 = bLayer2;
 276    parent.bLayer3 = bLayer3;
 277    parent.bLayer4 = bLayer4;
 278
 279    loadBaseMap();
 280    //loadPanoramio();
 281    // create a new event handler for single click query
 282    clickEventHandler = new OpenLayers.Handler.Click({
 283        'map': map
 284    }, {
 285        'click': function(e) {
 286        //envLayerInspection(e);
 287        }
 288    });
 289    clickEventHandler.activate();
 290    clickEventHandler.fallThrough = true;
 291        
 292    // cursor mods
 293    map.div.style.cursor="pointer";
 294    jQuery("#navtoolbar div.olControlZoomBoxItemInactive ").click(function(){
 295        map.div.style.cursor="crosshair";
 296        clickEventHandler.deactivate();
 297    });
 298    jQuery("#navtoolbar div.olControlNavigationItemActive ").click(function(){
 299        map.div.style.cursor="pointer";
 300        clickEventHandler.activate();
 301        setVectorLayersSelectable();
 302    });
 303
 304    map.events.register("moveend" , map, function (e) {
 305        parent.setExtent();
 306        if (shownPicture && !shownPicturePopup){
 307            removePanoramio(false);
 308            loadPanoramio(0,49);
 309        }
 310        Event.stop(e);
 311    });
 312
 313    map.events.register("zoomend" , map, function (e) {
 314        Event.stop(e);
 315
 316        //don't do change base layer if this is a 'print'
 317        if(parent.location.href.indexOf("?p=") < 0) {
 318            autoSwitchBaseMap();
 319        }
 320    });
 321
 322    registerSpeciesClick();
 323    toggleActiveHover();
 324}
 325
 326function autoSwitchBaseMap() {
 327    if (map.zoom > 15) {
 328        if (baseLayerSwitchStatus != 1) {
 329            baseLayerSwitchStatus = 2;
 330            changeBaseLayer('hybrid');
 331        }
 332    }
 333    else {
 334        if (baseLayerSwitchStatus == 2) {
 335            changeBaseLayer('normal');
 336            baseLayerSwitchStatus = 0;
 337        }
 338    }
 339}
 340
 341var query_
 342var query_layer
 343var query_size
 344var query_ui_forall = "";
 345function iterateSpeciesInfoQuery(curr) {
 346    var pos = 0;
 347    var curpos = curr;
 348    while(curpos >= query_size[pos]) {
 349        curpos -= query_size[pos];
 350        pos += 1;
 351    }
 352    var nextBtn = " &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ";
 353    try {
 354        if (curr+1 < query_count_total) {
 355            nextBtn = "<a style='float: right' href='javascript:iterateSpeciesInfoQuery("+(curr+1)+");'><img src='img/arrow_right.png' /></a>"; // next &rArr;
 356        }
 357    } catch (err) {}
 358    var prevBtn = " &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ";
 359    try {
 360        if (curr > 0) {
 361            prevBtn = "<a href='javascript:iterateSpeciesInfoQuery("+(curr-1)+");'><img src='img/arrow_left.png' /></a>"; // &lArr; previous
 362        }
 363    } catch (err) {}
 364
 365    var url = query_url[pos] + "&start=" + curpos;
 366    //alert(url);
 367    $.getJSON(proxy_script + URLEncode(url), function(data) {
 368        if (!query_layer[pos].bs) {
 369            var ulyr = query_[pos];
 370            var ulyr_occ_id = data.occurrences[0].id;
 371            var ulyr_occ_lng = data.occurrences[0].longitude;
 372            var ulyr_occ_lat = data.occurrences[0].latitude;
 373            var ulyr_meta = data.metadata;
 374
 375            var data = ulyr_meta.replace(/_n_/g,"<br />");
 376
 377            var heading = "<h2 class='z-label'>Occurrence information (" + (curr+1) + " of " + query_count_total + ")</h2>";
 378            if (query_count_total==1) {
 379                heading = "<h2>Occurrence information (1 occurrence)</h2>";
 380            }
 381
 382            var infohtml = "<div id='sppopup2'> " +
 383            heading + "Record id: " + ulyr_occ_id + "<br /> " + data + " <br /> <br />" +
 384            " 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/>" +
 385            //" <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/>" +
 386            "<div id=''>"+prevBtn+" &nbsp; &nbsp; &nbsp; &nbsp; "+nextBtn+"</div>";
 387
 388            setTimeout(function(){
 389                if (document.getElementById("sppopup") != null) {
 390                    document.getElementById("sppopup").innerHTML = infohtml;
 391                }
 392            }, 50);
 393        } else {
 394            displaySpeciesInfo(pos, data.occurrences[0], prevBtn, nextBtn, curr, query_count_total);
 395        }
 396    });
 397}
 398
 399function iteratePointsOfInterest(curr) {
 400    var pos = curr;
 401    if (pos < 0) {
 402    	pos = 0;
 403    }
 404    
 405    if (pos >= points_of_interest_total) {
 406    	pos = points_of_interest_total - 1;
 407    }
 408    
 409    var nextBtn = " &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ";
 410    try {
 411        if (curr+1 < points_of_interest_total) {
 412            nextBtn = "<a style='float: right' href='javascript:iteratePointsOfInterest("+(curr+1)+");'><img src='img/arrow_right.png' /></a>"; // next &rArr;
 413        }
 414    } catch (err) {}
 415    var prevBtn = " &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ";
 416    try {
 417        if (curr > 0) {
 418            prevBtn = "<a href='javascript:iteratePointsOfInterest("+(curr-1)+");'><img src='img/arrow_left.png' /></a>"; // &lArr; previous
 419        }
 420    } catch (err) {}
 421
 422    setTimeout(function() {
 423    	displayPointOfInterest(pos, points_of_interest[pos], prevBtn, nextBtn, curr, points_of_interest_total);
 424    });
 425}
 426
 427function displayPointOfInterest(pos, data, prevBtn, nextBtn, curr, total) {
 428    var poiInfo = data;
 429    
 430    var poiId = poiInfo.id;
 431    var objectId = poiInfo.object_id;
 432    var name = poiInfo.name;
 433    var type = poiInfo.type;
 434    var latitude = poiInfo.latitude;
 435    var longitude = poiInfo.longitude;
 436    var bearing = poiInfo.bearing;
 437    var userId = poiInfo.user_id;
 438    var focalLength = poiInfo.focal_length_millimetres;
 439
 440    var heading = "<h2>Point of interest (" + (curr+1) + " of " + total + ")</h2>";
 441    if (total==1) {
 442        heading = "<h2>Point of interest</h2>";
 443    }
 444
 445    var infohtml = "<div id='sppopup2'> " +
 446    heading +
 447    " ID: " + poiId + " <br />" +
 448    " Object ID: " + objectId + " <br />" +
 449    " Name: " + name + " <br />" +
 450    " Type: " + type + " <br />" +
 451    " Latitude: " + latitude + " <br />" +
 452    " Longitude: " + longitude + " <br />" +
 453    " Bearing: " + bearing + " <br />" +
 454    " User ID: " + userId + " <br />" +
 455    " Focal Length: " + focalLength + " <br />" +
 456    "<div id=''>"+prevBtn+" &nbsp; &nbsp; &nbsp; &nbsp; "+nextBtn+"</div>";
 457
 458    if (document.getElementById("sppopup") != null) {
 459        document.getElementById("sppopup").innerHTML = infohtml;
 460    }
 461}
 462
 463var defaultSelectFeatureStyle = null;
 464function addFeatureSelectionTool() {
 465    removeAreaSelection();
 466    areaSelectOn = true;
 467    mapClickControl = null;
 468
 469    OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
 470        defaultHandlerOptions: {
 471            'single': true,
 472            'double': false,
 473            'pixelTolerance': 0,
 474            'stopSingle': false,
 475            'stopDouble': false
 476        },
 477
 478        initialize: function(options) {
 479            this.handlerOptions = OpenLayers.Util.extend(
 480            {}, this.defaultHandlerOptions
 481                );
 482            OpenLayers.Control.prototype.initialize.apply(
 483                this, arguments
 484                );
 485            this.handler = new OpenLayers.Handler.Click(
 486                this, {
 487                    'click': pointSearch
 488                }, this.handlerOptions
 489                );
 490        }
 491    });
 492    mapClickControl = new OpenLayers.Control.Click();
 493    mapClickControl.fallThrough = true;
 494    map.addControl(mapClickControl);
 495    mapClickControl.activate();
 496}
 497
 498function pointSearch(e) {
 499    var lonlat = map.getLonLatFromViewPortPx(e.xy);
 500    parent.setSearchPoint(lonlat);
 501}
 502
 503function removePointSearch() {
 504    //remove the point search map click control
 505    mapClickControl.deactivate();
 506    map.removeControl(mapClickControl);
 507    mapClickControl = null;
 508    //reload the species click control
 509    registerSpeciesClick();
 510}
 511
 512var query_count_total;
 513var points_of_interest_total;
 514var points_of_interest;
 515function pointSpeciesSearch(e) {
 516	
 517    var lonlat = map.getLonLatFromViewPortPx(e.xy);
 518    var untransformedLon = lonlat.lon
 519    var untransformedLat = lonlat.lat
 520    
 521    lonlat.transform(map.projection, map.displayProjection);
 522
 523    var webportal_url = parent.jq('$webportal_url')[0].innerHTML;
 524
 525    //handles point click in mapComposer
 526    //parent.setSpeciesSearchPoint(lonlat);
 527
 528    query_count_total = 0;
 529    points_of_interest_total = 0
 530    query_ = new Array();
 531    query_layer = new Array();
 532    query_size = new Array();
 533    query_url = new Array();
 534    points_of_interest = new Array();
 535    var pos = 0;
 536
 537    for (var key in mapLayers) {
 538        if(mapLayers[key]) {
 539            if(mapLayers[key].id) {
 540
 541                if(map.getLayer(mapLayers[key].id)) {
 542                    var layer = mapLayers[key];
 543                    if(layer == null) {
 544                        continue;
 545                    }
 546                    
 547                    if (layer.pointsOfInterestWS != null) {
 548                    	var pointsOfInterestData = getPointsOfInterest(layer, lonlat.lat, lonlat.lon, 6)
 549                    	if (pointsOfInterestData.length == 0) {
 550                    		continue;
 551                    	} else {
 552                    		points_of_interest_total += pointsOfInterestData.length
 553                    		points_of_interest = points_of_interest.concat(pointsOfInterestData)
 554                    	}
 555                    } else {
 556                    	if (layer.url == null) {
 557                    		continue;
 558                    	}
 559                    	
 560	                    var query = null;
 561	                    var userquery = null;
 562	                    var p0 = layer.url.indexOf("CQL_FILTER=");
 563	                    var p1 = layer.url.indexOf("&", p0);
 564	                    if(p1 < 0) p1 = layer.url.indexOf(";", p0);
 565	                    if(p1 < 0) p1 = layer.url.length;
 566	                    if(p0 >= 0 && p1 >= 0 && layer.params != null) {
 567	                        if(layer.url.contains(webportal_url)) {
 568	                            userquery = layer.url.substring(p0 + 11,p1);
 569	                        } else {
 570	                            query = layer.url.substring(p0 + 11,p1);
 571	                        }
 572	                    }
 573	
 574	                    var size = 10;
 575	                    if(layer.params != null && layer.params.ENV != null) {
 576	                        var p2 = layer.params.ENV.indexOf("size:");
 577	                        p3 = layer.params.ENV.indexOf(";", p2);
 578	                        if(p3 < 0) p3 = layer.params.ENV.length;
 579	
 580	                        if(p2 >= 0 && p3 >= 0) {
 581	                            size = layer.params.ENV.substring(p2 + 5,p3)
 582	                        }
 583	                    }
 584	                    //console.log("map layer: " + layer);
 585	                    var data = null;
 586	                    if(query != null) data = getOccurrence(layer, query, lonlat.lat, lonlat.lon, 0, pos, size);
 587	                    if(userquery != null) data = getOccurrenceUploaded(layer, userquery, lonlat.lat, lonlat.lon, 0, pos, size);
 588	                    if(data != null) {
 589	                        query_count_total += query_size[pos];
 590	                        pos += 1;
 591	                    }
 592                    }
 593                }
 594            }
 595        }
 596    }
 597
 598    if (query_count_total == 0 && points_of_interest_total == 0) {
 599        return null;
 600    }
 601
 602    var lonlat = new OpenLayers.LonLat(lonlat.lon, lonlat.lat).transform(
 603        new OpenLayers.Projection("EPSG:4326"),
 604        map.getProjectionObject());
 605
 606    setupPopup(query_count_total, points_of_interest_total, lonlat);
 607    
 608    if (points_of_interest_total == 0 && query_count_total > 0) {
 609    	iterateSpeciesInfoQuery(0)
 610    }
 611    
 612    if (query_count_total == 0 && points_of_interest_total  > 0) {
 613    	iteratePointsOfInterest(0)
 614    }
 615
 616    var feature = popup;
 617    feature.popup = popup;
 618    popup.feature = feature;
 619    map.addPopup(popup, true);
 620}
 621
 622function registerSpeciesClick() {
 623
 624    OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
 625        defaultHandlerOptions: {
 626            'single': true,
 627            'double': false,
 628            'pixelTolerance': 0,
 629            'stopSingle': false,
 630            'stopDouble': false
 631        },
 632
 633        initialize: function(options) {
 634            this.handlerOptions = OpenLayers.Util.extend(
 635            {}, this.defaultHandlerOptions
 636                );
 637            OpenLayers.Control.prototype.initialize.apply(
 638                this, arguments
 639                );
 640            this.handler = new OpenLayers.Handler.Click(
 641                this, {
 642                    'click': pointSpeciesSearch
 643                }, this.handlerOptions
 644                );
 645        }
 646    });
 647    mapClickControl = new OpenLayers.Control.Click();
 648    mapClickControl.fallThrough = true;
 649    map.addControl(mapClickControl);
 650    mapClickControl.activate();
 651    ///////////////////
 652    //  setVectorLayersSelectable();
 653    var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
 654    layer_style.fillColor = "red";
 655    layer_style.strokeColor = "red";
 656
 657    featureSpeciesSelectLayer = new OpenLayers.Layer.Vector("Selected Species Layer", {
 658        style: layer_style
 659    });
 660    featureSpeciesSelectLayer.setVisibility(true);
 661    map.addLayer(featureSpeciesSelectLayer);
 662}
 663
 664function addRadiusDrawingTool() {
 665    removeAreaSelection();
 666    radiusOptions = {
 667        sides: 40
 668    };
 669
 670    var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
 671    layer_style.fillColor = "red";
 672    layer_style.strokeColor = "red";
 673
 674    radiusLayer = new OpenLayers.Layer.Vector("Point Radius Layer Layer", {
 675        style: layer_style,
 676        eventListeners: {
 677            "sketchmodified": function(event) {
 678                var verts = event.vertex.getVertices();
 679                var gll = new Array();
 680                if (verts.length > 0) {
 681                    for (var v=0; v<verts.length; v++) {
 682                        var pt = verts[v].transform(map.projection, map.displayProjection);
 683                        gll.push(new google.maps.LatLng(pt.y, pt.x));
 684                    }
 685                }
 686                var currarea = ((google.maps.geometry.spherical.computeArea(gll)/1000)/1000);
 687                var currradius = Math.sqrt(currarea/Math.PI);
 688                currradius = Math.round(currradius*Math.pow(10,2))/Math.pow(10,2);
 689                $('#currradius').html(currradius);
 690            }
 691        }
 692    });
 693    radiusLayer.setVisibility(true);
 694    map.addLayer(radiusLayer);
 695
 696    if(radiusControl != null){
 697        map.removeControl(radiusControl);
 698        radiusControl.destroy();
 699        radiusControl = null;
 700    }
 701    radiusControl = new OpenLayers.Control.DrawFeature(radiusLayer,OpenLayers.Handler.RegularPolygon,{
 702        'featureAdded':radiusAdded,
 703        handlerOptions:radiusOptions
 704    });
 705    map.addControl(radiusControl);
 706    radiusControl.activate();
 707    $('#currradius').html("0"); 
 708    $('#radiusDisplay').slideDown('slow');
 709}
 710
 711function addPolygonDrawingTool() {
 712    removeAreaSelection();
 713    ////adding polygon control and layer
 714    var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
 715    layer_style.fillColor = "red";
 716    layer_style.strokeColor = "red";	
 717
 718    polygonLayer = new OpenLayers.Layer.Vector("Polygon Layer", {
 719        style: layer_style
 720    });
 721    polygonLayer.setVisibility(true);
 722    map.addLayer(polygonLayer);
 723    if(polyControl != null){
 724        map.removeControl(polyControl);
 725        polyControl.destroy();
 726        polyControl = null;
 727    }
 728    polyControl = new OpenLayers.Control.DrawFeature(polygonLayer,OpenLayers.Handler.Polygon,{
 729        'featureAdded':polygonAdded
 730    });
 731    map.addControl(polyControl);
 732    polyControl.activate();	
 733//////
 734}
 735
 736function removeAreaSelection() {
 737    if(polygonLayer != null){
 738        polygonLayer.destroy();
 739        polygonLayer = null;
 740        polyControl.deactivate();
 741    }
 742    if(boxLayer != null) {
 743        boxLayer.destroy();
 744        boxLayer = null;
 745        boxControl.deactivate();        
 746    }
 747    if(radiusLayer != null){
 748        radiusLayer.destroy();
 749        radiusLayer = null;
 750        radiusControl.deactivate();
 751        $('#radiusDisplay').slideUp('slow');
 752    }
 753
 754    if(featureSelectLayer != null){
 755        featureSelectLayer.destroy();
 756        featureSelectLayer = null;
 757        areaSelectOn = false;
 758    }
 759
 760    /* refreshes all the vector layers -> this is because the vector features
 761     * can dissappear after selection so need to redraw
 762     */
 763    for(var i in selectionLayers) {
 764        var layer = selectionLayers[i];
 765        for(var j in layer.features) {
 766            layer.drawFeature(layer.features[j]);
 767        }
 768    }
 769
 770    if(mapClickControl != null) {
 771        mapClickControl.deactivate();
 772        map.removeControl(mapClickControl);
 773    }
 774}
 775
 776function addBoxDrawingTool() {
 777    removeAreaSelection();
 778    var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
 779    layer_style.fillColor = "red";
 780    layer_style.strokeColor = "red";	
 781
 782    boxLayer = new OpenLayers.Layer.Vector("Box Layer", {
 783        style : layer_style
 784    });
 785
 786    boxControl = new OpenLayers.Control.DrawFeature(boxLayer,OpenLayers.Handler.Box,{
 787        'featureAdded':regionAdded
 788    });
 789    map.addControl(boxControl);
 790
 791    boxControl.activate();	
 792}
 793
 794function featureSelected(feature) {
 795    parent.setLayerGeometry(feature.layer.name);
 796    areaSelectOn = false;    
 797    removeAreaSelection();
 798    setVectorLayersSelectable();
 799}
 800
 801function radiusAdded(feature) {
 802    parent.setPolygonGeometry(feature.geometry);
 803    removeAreaSelection();
 804    setVectorLayersSelectable();
 805}
 806
 807// This function passes the region geometry up to javascript in index.zul which can then send it to the server.
 808function regionAdded(feature) {    
 809    //converting bounds from pixel value to lonlat - annoying!
 810    var geoBounds = new OpenLayers.Bounds();
 811    geoBounds.extend(map.getLonLatFromPixel(new OpenLayers.Pixel(feature.geometry.left,feature.geometry.bottom)));
 812    geoBounds.extend(map.getLonLatFromPixel(new OpenLayers.Pixel(feature.geometry.right,feature.geometry.top)));
 813
 814    removeAreaSelection();
 815    setVectorLayersSelectable();
 816    parent.setRegionGeometry(geoBounds.toGeometry());
 817}
 818
 819// This function passes the geometry up to javascript in index.zul which can then send it to the server.
 820function polygonAdded(feature) {
 821    parent.setPolygonGeometry(feature.geometry);
 822    removeAreaSelection();
 823    setVectorLayersSelectable();
 824}
 825
 826function setVectorLayersSelectable() {
 827    try {
 828        var layersV = map.getLayersByClass('OpenLayers.Layer.Vector');
 829        if(selectControl != null){
 830            selectControl.deactivate();
 831            map.removeControl(selectControl);
 832            selectControl.destroy();
 833            selectControl = null;
 834        }
 835        selectControl = new OpenLayers.Control.SelectFeature(layersV);
 836        map.addControl(selectControl);
 837        selectControl.activate();
 838    } catch (err) {
 839
 840    }
 841}
 842
 843var currFeature;
 844var currFeatureCount; 
 845
 846function setupPopup(occurrenceCount, pointOfInterestCount, centerlonlat) {
 847	var msg = "<br /><br />";
 848	
 849	if (occurrenceCount > 0 && pointOfInterestCount == 0) {
 850	    if (occurrenceCount == 1) {
 851	        msg += occurrenceCount + " occurrence found in this location <br /> Retrieving data... ";
 852	    } else {
 853	    	msg += occurrenceCount + " occurrences found in this location <br /> Retrieving data... ";	    	
 854	    }		
 855	} else if (pointOfInterestCount > 0 && occurrenceCount == 0) {
 856	    if (pointOfInterestCount == 1) {
 857	        msg += pointOfInterestCount + " occurrence found in this location <br /> Retrieving data... ";
 858	    } else {
 859	    	msg += pointOfInterestCount + " points of interest found in this location <br /> Retrieving data... ";	
 860	    }
 861	} else {
 862	    if (occurrenceCount == 1) {
 863	        msg += occurrenceCount + " occurrence found in this location ";
 864	    } else {
 865	    	msg += occurrenceCount + " occurrences found in this location ";	
 866	    }
 867	    
 868	    msg += "<a href='javascript:iterateSpeciesInfoQuery(0);'><img src='img/arrow_right.png' /></a>";
 869	    msg += "<br />";
 870	    
 871	    msg += pointOfInterestCount + " points of interest found in this location ";
 872	    if (pointOfInterestCount == 1) {
 873	        msg += pointOfInterestCount + " points of interest found in this location ";
 874	    }
 875	    
 876	    msg += "<a href='javascript:iteratePointsOfInterest(0);'><img src='img/arrow_right.png' /></a>";
 877	}
 878    
 879    popup = new OpenLayers.Popup.FramedCloud("featurePopup",
 880        centerlonlat,
 881        new OpenLayers.Size(100,170),
 882        "<div id='sppopup'>" + msg + "</div>" //  style='width: 350px; height: 250px;'
 883        ,
 884        null, true, onPopupClose);
 885        popup.autoSize = true;
 886        popup.minSize = new OpenLayers.Size(350,250);
 887}
 888
 889function onPopupClose(evt) {
 890    try {
 891        map.removePopup(this.feature.popup);
 892        this.feature.popup.destroy();
 893        this.feature.popup = null;
 894
 895        selectControl.unselect(this.feature);
 896    } catch(err) {
 897    }
 898}
 899
 900function relocatePopup(lon, lat) {
 901    popup.lonlat = new OpenLayers.LonLat(lon, lat).transform(
 902        new OpenLayers.Projection("EPSG:4326"),
 903        map.getProjectionObject());
 904    popup.updatePosition(); 
 905}
 906
 907function displaySpeciesInfo(pos, data, prevBtn, nextBtn, curr, total) {
 908    var occinfo = data;
 909    var bie = parent.jq('$bie_url')[0].innerHTML;
 910    var biocache = query_layer[pos].ws;
 911    var rank = occinfo.taxonRank;
 912    var speciesname = occinfo.scientificName;
 913    var specieslsid = occinfo.taxonConceptID;
 914    species = (speciesname!=null)?speciesname:"";
 915    if (specieslsid != null) {
 916        species = '<a href="' + bie + '/species/'+specieslsid+'" target="_blank">'+species+'</a>';
 917    } else {
 918        species = species + ' (<i>Supplied as: "' + occinfo.scientificName + '"</i>) ';
 919    }
 920
 921    var family = occinfo.family;
 922    if (occinfo.family != null) {
 923        family = '<a href="' + bie + '/species/'+occinfo.family+'" target="_blank">'+family+'</a>';
 924    }
 925
 926    var kingdom = occinfo.kingdom;
 927    if (occinfo.kingdom != null) {
 928        kingdom = '<a href="' + bie + '/species/'+occinfo.kingdom+'" target="_blank">'+kingdom+'</a>';
 929    }
 930
 931    var occurrencedate = "";
 932    if(occinfo.year && occinfo.month) {
 933        occurrencedate = occinfo.month + "/" + occinfo.year;
 934    } else if (occinfo.year) {
 935        occurrencedate = occinfo.year
 936    }
 937    var uncertainty = occinfo.coordinateUncertaintyInMeters;
 938    var uncertaintyText = uncertainty + " metres";
 939    if(uncertainty == "" || uncertainty == undefined || uncertainty == null) {
 940        uncertaintyText = "<b>Not supplied </b>"; // setting to 10km
 941        uncertainty = 10000;
 942    }
 943    var heading = "<h2>Occurrence information (" + (curr+1) + " of " + total + ")</h2>";
 944    if (total==1) {
 945        heading = "<h2>Occurrence information (1 occurrence)</h2>";
 946    }
 947
 948    var fullQueryLink = "";
 949    if(total>1) fullQueryLink = "More detail:  <a href='" + query_ui_forall + "' target='_blank'>All records at this point</a>";
 950
 951    var checked = parent.isFlaggedRecord(query_layer[pos].name, occinfo.uuid);
 952    var checkstate = "";
 953    if(checked) checkstate="checked='" + checked + "'";
 954
 955    var infohtml = "<div id='sppopup2'> " +
 956    heading +
 957    " Scientific name: " + species + " <br />" +
 958    " Kingdom: " + kingdom + " <br />" +
 959    " Family: " + family + " <br />" +
 960    " Data provider: <a href='http://collections.ala.org.au/public/show/" + occinfo.dataProviderUid + "' target='_blank'>" + occinfo.dataProviderName + "</a> <br />" +
 961    " Longitude: "+occinfo.decimalLongitude + " , Latitude: " + occinfo.decimalLatitude + " (<a href='javascript:goToLocation("+occinfo.decimalLongitude+", "+occinfo.decimalLatitude+", 15);relocatePopup("+occinfo.decimalLongitude+", "+occinfo.decimalLatitude+");'>zoom to</a>) <br/>" +
 962    " Spatial uncertainty in metres: " + uncertaintyText + "<br />" +
 963    " Occurrence date: " + occurrencedate + " <br />" +
 964    "Full record: <a href='" + biocache + "/occurrences/" + occinfo.uuid + "' target='_blank'>View details</a> <br />" +
 965        fullQueryLink + " <br/>" +
 966    "<input type='checkbox' " + checkstate + " onClick='parent.flagRecord(\"" + query_layer[pos].name + "\",\"" + occinfo.uuid + "\",this.checked)' />Assign record to <i>ad hoc</i> group<br/>" +
 967    "<div id=''>"+prevBtn+" &nbsp; &nbsp; &nbsp; &nbsp; "+nextBtn+"</div>";
 968
 969    if (document.getElementById("sppopup") != null) {
 970        document.getElementById("sppopup").innerHTML = infohtml;
 971    }
 972}
 973
 974function addWKTFeatureToMap(featureWKT,name,hexColour,opacity) {
 975    var in_options = {
 976        'internalProjection': map.baseLayer.projection,
 977        'externalProjection': new OpenLayers.Projection("EPSG:4326")
 978    };
 979    var styleMap = new OpenLayers.StyleMap(OpenLayers.Util.applyDefaults(
 980    {
 981        fillColor: hexColour,
 982        fillOpacity: opacity,
 983        strokeOpacity: 1,
 984        strokeWidth: 2,
 985        strokeColor: hexColour
 986    },
 987    OpenLayers.Feature.Vector.style["new"]));
 988
 989    var layer_style = OpenLayers.Util.extend({},OpenLayers.Feature.Vector.style['default']);
 990    layer_style.fillColor = hexColour;
 991    layer_style.strokeColor = hexColour;
 992    layer_style.fillOpacity = opacity;
 993
 994    var wktLayer = new OpenLayers.Layer.Vector(name, {
 995        style : layer_style
 996    });
 997    map.addLayer(wktLayer);
 998    var geom = new OpenLayers.Geometry.fromWKT(featureWKT);
 999    geom = geom.transform(map.displayProjection, map.projection);
1000    wktLayer.addFeatures([new OpenLayers.Feature.Vector(geom)]);
1001
1002    wktLayer.isFixed = false;
1003    selectionLayers[selectionLayers.length] = wktLayer;
1004
1005    removePointSearch();
1006
1007    return wktLayer;
1008}
1009var myVector;
1010function addJsonFeatureToMap(feature, name, hexColour, radius, opacity, szUncertain) {
1011    var in_options = {
1012        'internalProjection': map.baseLayer.projection,
1013        'externalProjection': new OpenLayers.Projection("EPSG:4326")
1014    };
1015    
1016    var styleMap = new OpenLayers.StyleMap(OpenLayers.Util.applyDefaults(
1017    {
1018        fillColor: hexColour,
1019        fillOpacity: opacity,
1020        strokeOpacity: 1,
1021        strokeWidth: 2,
1022        strokeColor: hexColour
1023    },
1024    OpenLayers.Feature.Vector.style["new"]));
1025
1026    var layer_style = OpenLayers.Util.extend({},OpenLayers.Feature.Vector.style['default']);
1027    layer_style.fillColor = hexColour;
1028    layer_style.strokeColor = hexColour;
1029    layer_style.pointRadius = 0;
1030    layer_style.pointRadius = radius;
1031    layer_style.fillOpacity = opacity;
1032    layer_style.szUncertain = szUncertain;
1033    layer_style.fontWeight = "bold";
1034
1035    var geojson_format = new OpenLayers.Format.GeoJSON(in_options);
1036    var vector_layer = new OpenLayers.Layer.Vector(name,{
1037        styleMap: styleMap
1038    });
1039
1040    myVector = vector_layer;
1041
1042    vector_layer.style = layer_style;
1043    vector_layer.isFixed = false;
1044    features = geojson_format.read(feature);
1045
1046    fixAttributes(features, feature);
1047
1048    //apply uncertainty to features
1049    vector_layer.events.register("featureadded", vector_layer, featureadd);
1050    vector_layer.addFeatures(features);
1051    
1052    vector_layer.events.register("featureselected", vector_layer, selected);
1053
1054    window.setTimeout(function(){
1055        setVectorLayersSelectable();
1056    }, 2000);
1057        
1058    return vector_layer;
1059}
1060
1061function selected (evt) {
1062
1063    var feature = (evt.feature==null)?evt:evt.feature;
1064    var attrs = feature.attributes;
1065    currFeature = feature;
1066
1067    if (areaSelectOn) {
1068        currFeature = null;
1069        featureSelected(feature);
1070        return;
1071    }
1072    else {
1073        //test to see if its occurrence data
1074        if (attrs["oi"] != null) {
1075            popup = new OpenLayers.Popup.FramedCloud("featurePopup",
1076                feature.geometry.getBounds().getCenterLonLat(),
1077                new OpenLayers.Size(100,170),
1078                "<div id='sppopup'>Retrieving data... </div>" //  style='width: 350px; height: 250px;'
1079                ,
1080                null, true, onPopupClose);
1081
1082            //parent.showInfoOne();
1083            parent.setSpeciesSearchPoint(feature.geometry.getBounds().getCenterLonLat());
1084
1085        } else if (attrs["count"] != null) {
1086            setupPopup(attrs["count"], feature.geometry.getBounds().getCenterLonLat());
1087            showClusterInfo(0);
1088
1089
1090
1091        } else {
1092            var html = "<h2>Feature Details</h2>";
1093
1094            if (attrs.Feature_Name) {
1095                html += "Feature name: " + attrs.Feature_Name + "<br />";
1096                html += "Feature ID: " + attrs.Feature_ID + "<br />";
1097                html += "GID: " + attrs.gid + "<br /><br />";
1098
1099                if (attrs.Bounding_Box) {
1100                    html += "Bounding box: " + attrs.Bounding_Box + "<br />";
1101                    html += "Feature type: Polygon <br /><br />";
1102                }
1103
1104                if (attrs.Point) {
1105                    html += "Point: " + attrs.Point + "<br />";
1106                    html += "Feature type: Point <br /><br />";
1107                }
1108
1109                html += "Metadata: <a href='" + attrs.Layer_Metadata + "' target='_blank'>" + attrs.Layer_Metadata + "</a> <br />";
1110            } else {
1111                for (key in attrs) {
1112                    html += "<br>" +  key + " : "  + attrs[key];
1113                }
1114            }
1115
1116            popup = new OpenLayers.Popup.FramedCloud("featurePopup",
1117                feature.geometry.getBounds().getCenterLonLat(),
1118                new OpenLayers.Size(100,170),
1119                html
1120                ,
1121                null, true, onPopupClose);
1122
1123        }
1124        feature.popup = popup;
1125        popup.feature = feature;
1126        map.addPopup(popup, true);
1127    }
1128
1129}
1130
1131function featureadd(evt) {
1132    var max_map_bounds = new OpenLayers.Bounds(-180,-90, 180, 90);  // map.getMaxExtent();
1133    var feature = evt.feature;
1134    var fgeomt = feature.geometry.transform(map.projection,map.displayProjection);
1135    var isContains = max_map_bounds.contains(this.getDataExtent().left, this.getDataExtent().top); 
1136    /*
1137         * add a mirror point 360 to the west of the feature, so that it will be displayed
1138         * when the map's extent becomes < -180 as a result of the warpdateline function
1139         * of the base layer, this is only applicable for point
1140         */
1141    if(!feature.isMirror){
1142        if(!feature.onScreen()){
1143            if(!max_map_bounds.contains(this.getDataExtent().left, this.getDataExtent().top)){//feature.geometry.x > 0 &&
1144                var featureMirror = new OpenLayers.Feature.Vector(
1145                    new OpenLayers.Geometry.Point((fgeomt.x - max_map_bounds.getWidth()), fgeomt.y),
1146                    feature.attributes,
1147                    feature.style);
1148                featureMirror.isMirror = true;
1149                feature.isMirror = false;
1150                var fmgeomt = featureMirror.geometry.transform(map.projection,map.displayProjection);
1151                this.addFeatures([featureMirror]);
1152            }
1153        }
1154    }
1155    fgeomt = feature.geometry.transform(map.displayProjection,map.projection);
1156}
1157
1158function addJsonUrlToMap(url, name, hexColour, radius, opacity, szUncertain) {
1159   
1160    $.getJSON(proxy_script + url, function(feature) {
1161        addJsonFeatureToMap(feature, name, hexColour, radius, opacity, szUncertain);
1162
1163        var urlname = url + "::" + name;
1164        vector_layer.urlname = urlname;
1165        mapLayers[urlname] = vector_layer;
1166        registerLayer(mapLayers[urlname]);
1167        map.addLayer(mapLayers[urlname]);
1168
1169        if(map.signalLayerLoaded != undefined
1170            && vector_layer.urlname != undefined)
1171            map.signalLayerLoaded(vector_layer.urlname);
1172    });
1173}
1174
1175function appendJsonUrlToMap(url, original_url, name) {
1176    $.getJSON(proxy_script + url, function(feature) {
1177
1178        var urlname = original_url + "::" + name;
1179        vector_layer = mapLayers[urlname];
1180
1181        var in_options = {
1182            'internalProjection': map.baseLayer.projection,
1183            'externalProjection': new OpenLayers.Projection("EPSG:4326")
1184        };
1185
1186        var geojson_format = new OpenLayers.Format.GeoJSON(in_options);
1187        features = geojson_format.read(feature);
1188
1189        fixAttributes(features, feature)
1190    
1191        //apply uncertainty to features
1192        vector_layer.addFeatures(features);
1193
1194        if(map.signalLayerLoaded != undefined
1195            && vector_layer.urlname != undefined)
1196            map.signalLayerLoaded(url);
1197    });
1198}
1199
1200function removeFromSelectControl(lyrname) {
1201    if (selectControl==undefined || selectControl==null) {
1202        return;
1203    }
1204    var currentLayers = selectControl.layers;
1205    for (var li=0; li<currentLayers.length; li++) {
1206        if (currentLayers[li].name==lyrname) {
1207            currentLayers.splice(li,1);
1208            break;
1209        }
1210    }
1211
1212    if (lyrname=="Active Area") {
1213        activeAreaPresent = false;
1214        parent.displayArea(map.getExtent().toGeometry().getGeodesicArea(map.projection)/1000/1000);
1215        var verts = map.getExtent().toGeometry().clone().getVertices();
1216        var gll = new Array();
1217        if (verts.length > 0) {
1218            for (var v=0; v<verts.length; v++) {
1219                var pt = verts[v].transform(map.projection, map.displayProjection);
1220                gll.push(new google.maps.LatLng(pt.y, pt.x));
1221            }
1222        }
1223        parent.displayArea2((google.maps.geometry.spherical.computeArea(gll)/1000)/1000);
1224
1225    }
1226
1227    var isActive = selectControl.active;
1228    try{
1229        selectControl.unselectAll();
1230    }catch(err){}
1231    selectControl.deactivate();
1232    if(selectControl.layers) {
1233        selectControl.layer.destroy();
1234        selectControl.layers = null;
1235    }
1236    initSelectControlLayers(currentLayers);
1237    selectControl.handlers.feature.layer = selectControl.layer;
1238    if (isActive) {
1239        selectControl.activate();
1240    }
1241}
1242
1243function initSelectControlLayers(layers) {
1244    if(layers instanceof Array) {
1245        selectControl.layers = layers;
1246        selectControl.layer = new OpenLayers.Layer.Vector.RootContainer(
1247            selectControl.id + "_container", {
1248                layers: layers
1249            }
1250            );
1251    } else {
1252        selectControl.layer = layers;
1253    }
1254}
1255
1256function redrawWKTFeatures(featureWKT, name,hexColour,opacity) {
1257    var layers = map.getLayersByName(name);
1258    
1259    var layer_style = OpenLayers.Util.extend({},OpenLayers.Feature.Vector.style['default']);
1260    layer_style.fillColor = hexColour;
1261    layer_style.strokeColor = hexColour;
1262    layer_style.fillOpacity = opacity;
1263
1264    for (key in layers) {
1265
1266        if (layers[key] != undefined) {
1267
1268            var layer = map.getLayer(layers[key].id);
1269
1270            if (layer.name == name) {
1271
1272                layer.destroyFeatures();
1273                layer.style = layer_style;
1274                var geom = new OpenLayers.Geometry.fromWKT(featureWKT);
1275
1276                geom = geom.transform(map.displayProjection, map.projection);
1277                layer.addFeatures([new OpenLayers.Feature.Vector(geom)]);
1278                layer.isFixed = false;
1279                layer.addFeatures([new OpenLayers.Feature.Vector(geom)]);
1280            }
1281        }
1282    }
1283}
1284
1285function redrawFeatures(name, hexColour, opacity, radius, szUncertain) {
1286    var in_options = {
1287        'internalProjection': map.baseLayer.projection,
1288        'externalProjection': new OpenLayers.Projection("EPSG:4326")
1289    };
1290    var gjLayers = map.getLayersByName(name);
1291
1292    var layer_style = OpenLayers.Util.extend({},OpenLayers.Feature.Vector.style['default']);
1293    layer_style.fillColor = hexColour;
1294    layer_style.strokeColor = hexColour;
1295    layer_style.fillOpacity = opacity;
1296    layer_style.pointRadius = radius;
1297    layer_style.szUncertain = szUncertain;
1298    layer_style.fontWeight = "bold";
1299    
1300    for (key in gjLayers) {
1301        if (gjLayers[key] != undefined) {
1302            var layer = gjLayers[key];
1303            if (layer.name == name) {
1304                layer.style = layer_style;                
1305                layer.redraw(true);
1306            }
1307        }
1308    }
1309}
1310
1311function zoomBoundsGeoJSON(layerName) {
1312    //get the other geojson layers and force them to redraw
1313    var geoJsonLayers = map.getLayersByClass("OpenLayers.Layer.Vector");
1314    for (key in geoJsonLayers) {
1315        var layer = geoJsonLayers[key];
1316
1317        if (layer.name == layerName) {
1318            map.zoomToExtent(layer.getDataExtent());
1319        } 
1320    }
1321}
1322
1323function zoomBoundsLayer(layername) {
1324    var wmsLayers = map.getLayersByClass("OpenLayers.Layer.WMS");
1325    for (key in wmsLayers) {
1326
1327        if (map.layers[key] != undefined) {
1328
1329            var layer = map.getLayer(map.layers[key].id);
1330
1331            if (layer.name == layername){
1332                map.zoomToExtent(layer.getExtent());
1333            }
1334        }
1335    }
1336}
1337
1338function removeItFromTheList(layername) {
1339    var gjLayers = map.getLayersByName(layername);
1340    
1341    for (key in gjLayers) {        
1342        if (gjLayers[key] != undefined) {
1343            var layer = map.getLayer(gjLayers[key].id);
1344            if (layer.name == layername) {
1345                if(layer.removeFeatures != undefined) layer.removeFeatures();
1346                map.removeLayer(layer);
1347            }
1348        }
1349    }
1350}
1351
1352function removeDeselectedLayers(layerIds) {
1353    for (var key in mapLayers) {
1354        var found = false;
1355        var i = 0;
1356        while (! found && i < layerIds.length) {
1357            if (key == layerIds[i]) {
1358                found = true;
1359            }
1360            i++;
1361        }
1362
1363        if (! found) {
1364            map.removeLayer(mapLayers[key]);
1365            mapLayers[key] = null;
1366        }
1367    }
1368}
1369
1370function getCurrentFeatureInfo() {
1371    return jQuery('#featureinfocontent').html();
1372}
1373
1374function URLEncode (clearString) {
1375    var output = '';
1376    var x = 0;
1377    clearString = clearString.toString();
1378    var regex = /(^[a-zA-Z0-9_.]*)/;
1379    while (x < clearString.length) {
1380        var match = regex.exec(clearString.substr(x));
1381        if (match != null && match.length > 1 && match[1] != '') {
1382            output += match[1];
1383            x += match[1].length;
1384        } else {
1385            if (clearString[x] == ' ')
1386                output += '+';
1387            else {
1388                var charCode = clearString.charCodeAt(x);
1389                var hexVal = charCode.toString(16);
1390                output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
1391            }
1392            x++;
1393        }
1394    }
1395    return output;
1396}
1397
1398function fixAttributes(features, feature){
1399    //add feature (geojson string) properties to all features attributes
1400    //when first object (geometry) in features (geometry array) has no attributes
1401    //occurs when geojson type is GeometryCollection instead of Feature
1402    try{
1403        if(features.length > 0){
1404            var f = features[0];
1405            var i = 0;
1406            for(key in f.attributes) i++;
1407            if(i == 0){
1408                var json_format = new OpenLayers.Format.JSON();
1409                var json = json_format.read(feature);
1410                if(json.properties != undefined){
1411                    for(i=0;i<features.length;i++) {
1412                        features[i].attributes = json.properties;
1413                    }
1414                }
1415            }
1416            for (var j=0;j<features.length;j++) {
1417                features[j].isMirror = false; 
1418            }
1419        }
1420    }catch(err){}
1421}
1422
1423function loadKmlFile(name, kmlurl) {
1424    //Defiine your KML layer//
1425    var kmlLayer= new OpenLayers.Layer.Vector(name, {
1426        //Set your projection and strategies//
1427        projection: new OpenLayers.Projection("EPSG:4326"),
1428        strategies: [new OpenLayers.Strategy.Fixed()],
1429        //set the protocol with a url//
1430        protocol: new OpenLayers.Protocol.HTTP({
1431            //set the url to your variable//
1432            url: kmlurl,
1433            //format this layer as KML//
1434            format: new OpenLayers.Format.KML({
1435                //maxDepth is how deep it will follow network links//
1436                maxDepth: 1,
1437                //extract styles from the KML Layer//
1438                extractStyles: true,
1439                //extract attributes from the KML Layer//
1440                extractAttributes: true
1441            })
1442        })
1443    });
1444    return kmlLayer; 
1445
1446}
1447
1448var prevHoverData = null;
1449var prevHoverRequest = null;
1450
1451var prevNearestData = null;
1452var prevNearestRequest = null;
1453
1454function envLayerInspection(e) {
1455    try {
1456        infoHtml = envLayerHover(e, true);
1457        if(infoHtml != null) {
1458            var pt = map.getLonLatFromViewPortPx(new
1459                OpenLayers.Pixel(e.xy.x, e.xy.y) );
1460
1461            popup

Large files files are truncated, but you can click here to view the full file