Project

General

Profile

Download (35.9 KB) Statistics
| Branch: | Tag: | Revision:
1
//see also https://github.com/geetarista/jquery-plugin-template/blob/master/jquery.plugin-template.js
2

    
3
/**
4
 * Expected dom structure:
5
 *  '<div class="ahah-content" rel="'.$cdm_proxy_url.'"><span class="loading">Loading ....</span></div>';
6
 */
7
(function($, document, window, undefined) {
8

    
9
    $.fn.cdm_openlayers_map = function(mapserverBaseUrl, mapserverVersion, options) {
10

    
11
      var opts = $.extend({},$.fn.cdm_openlayers_map.defaults, options);
12

    
13
      // sanitize invalid opts.boundingBox
14
      if(opts.boundingBox &&  !( typeof opts.boundingBox  == 'string' && opts.boundingBox .length > 6)) {
15
        opts.boundingBox = null;
16
      }
17

    
18
      return this.each(function(){
19
          this.cdmOpenlayersMap = new CdmOpenLayers.Map($(this), mapserverBaseUrl, mapserverVersion, opts);
20
          this.cdmOpenlayersMap.create();
21
      }); // END each
22

    
23
    }; // END cdm_openlayers_map
24

    
25
})(jQuery, document, window, undefined);
26

    
27
(function($){
28
  $.fn.cdm_openlayers_map.defaults = {  // set up default options
29
    legendPosition:  null,      // 1,2,3,4,5,6 = display a legend in the corner specified by the number
30
    distributionOpacity: 0.75,
31
    legendOpacity: 0.75,
32
    // These are bounds in the epsg_4326 projection in degree
33
    boundingBox: null,
34
    aspectRatio: 2, // w/h
35
    showLayerSwitcher: false,
36
    baseLayerNames: ["mapproxy_vmap0"],
37
    defaultBaseLayerName: 'mapproxy_vmap0',
38
    maxZoom: 4,
39
    minZoom: 0,
40
    debug: true,
41
    /**
42
     * allows the map to display parts of the layers which are outside
43
     * the maxExtent if the aspect ratio of the map and of the baselayer
44
     * are not equal
45
     */
46
    displayOutsideMaxExtent: false,
47
    //  customWMSBaseLayerData: {
48
    //  name: "Euro+Med",
49
    //  url: "http://edit.africamuseum.be/geoserver/topp/wms",
50
    //  params: {layers: "topp:em_tiny_jan2003", format:"image/png", tiled: true},
51
    //  projection: "EPSG:7777777",
52
    //  maxExtent: "-1600072.75, -1800000, 5600000, 5850093",
53
    //  units: 'm'
54
    //  }
55
    customWMSBaseLayerData: {
56
        name: null,
57
        url: null,
58
        params: null,
59
        projection: null,
60
        proj4js_def: null,
61
        max_extent: null,
62
        units: null
63
    },
64
    wmsOverlayLayerData: {
65
      name: null,
66
      url: null,
67
      params: null
68
    },
69
    /**
70
     * when true the map is made resizable by adding the jQueryUI widget resizable
71
     * to the map container. This feature requires that the jQueryUI is loaded
72
     */
73
    resizable: false
74
  };
75
})(jQuery);
76

    
77
/**************************************************************************
78
 *                          CdmOpenLayers
79
 **************************************************************************/
80
(function() {
81

    
82
    /**
83
     * The CdmOpenLayers namespace definition
84
     */
85
    window.CdmOpenLayers  = (function () {
86

    
87
        // EPSG:3857 from http://spatialreference.org/ref/sr-org/6864/proj4/
88
        // OpenStreetMap etc
89
        Proj4js.defs["EPSG:3857"] = '+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +a=6378137 +b=6378137 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs';
90

    
91
        var projections = {
92
                epsg_4326: new OpenLayers.Projection("EPSG:4326"),
93
                epsg_900913: new OpenLayers.Projection("EPSG:900913"),
94
                epsg_3857:  new OpenLayers.Projection("EPSG:3857")
95
        };
96
        var mapExtends = {
97
                epsg_4326: new OpenLayers.Bounds(-180, -90, 180, 90),
98
                epsg_900913: new OpenLayers.Bounds(-180, -90, 180, 90),
99
                epsg_3857: new OpenLayers.Bounds(-180, -90, 180, 90)
100
        };
101
        // transform epsg_900913 to units meter
102
        mapExtends.epsg_900913.transform(projections.epsg_4326, projections.epsg_900913);
103
        mapExtends.epsg_3857.transform(projections.epsg_4326, projections.epsg_3857);
104

    
105
        // make public by returning an object
106
        return {
107
            projections: projections,
108
            mapExtends: mapExtends,
109
            getMap: function (){},
110
            getLayerByName: function(layerName){} // initially empty function, will be populated by openlayers_layers.js
111
        };
112

    
113
    })(); // end of namespace definition for CdmOpenLayers
114

    
115
    /**
116
     * The CdmOpenLayers.Map constructor
117
     * @param mapElement
118
     * @param mapserverBaseUrl
119
     * @param mapserverVersion
120
     * @param opts
121
     * @returns
122
     */
123
    window.CdmOpenLayers.Map = function(mapElement, mapserverBaseUrl, mapserverVersion, opts){
124

    
125
      var mapServicePath = '/edit_wp5';
126

    
127
      // firebug console stub (avoids errors if firebug is not active)
128
      if(typeof console === "undefined") {
129
          console = { log: function() { } };
130
      }
131

    
132
      // sanitize given options
133
      try {
134
          opts.customWMSBaseLayerData.max_extent = OpenLayers.Bounds.fromString(opts.customWMSBaseLayerData.max_extent);
135
      } catch(e){
136
          opts.customWMSBaseLayerData.max_extent = null;
137
      }
138

    
139

    
140
      var legendImgSrc = null;
141

    
142
      var map = null;
143

    
144
      var infoElement = null;
145

    
146
      var baseLayers = [];
147

    
148
      var defaultBaseLayer = null;
149

    
150
      /**
151
       * Default bounding box for map viewport in the projection of the base layer.
152
       * as defined by the user, can be null.
153
       *
154
       * These are bounds in the epsg_4326 projection, and will be transformed to the baselayer projection.
155
       *
156
       * @type string
157
       */
158
      var defaultBaseLayerBoundingBox = "-180,-90,180,90";
159

    
160
      /**
161
       * bounding box for map viewport as defined by the user, can be null.
162
       *
163
       * These are bounds in the projection of the base layer.
164
       *
165
       * @type string
166
       */
167
      var boundingBox = null;
168

    
169
      /**
170
       * Bounds for the view port calculated from the data layer responses.
171
       * These are either calculated by the minimum bounding box which
172
       * encloses the data in the data layers, or it is equal to the
173
       * boundingBox as defined by the user.
174
       *
175
       * These are bounds in the projection of the base layer.
176
       *
177
       * @see boundingBox
178
       *
179
       * @type OpenLayers.Bounds
180
       */
181
      var dataBounds = null;
182

    
183
      /**
184
       * Final value for the view port, calculated from the other bounds.
185
       *
186
       * These are bounds in the projection of the base layer.
187
       *
188
       * @type OpenLayers.Bounds
189
       */
190
      var zoomToBounds = null;
191

    
192
      var zoomToClosestLevel = true;
193

    
194
      var LAYER_DATA_CNT = 0;
195

    
196
      /* this is usually the <div id="openlayers"> element */
197
      var mapContainerElement = mapElement.parent();
198

    
199
      var defaultControls = [
200
         new OpenLayers.Control.PanZoom(),
201
         new OpenLayers.Control.Navigation(
202
           {
203
             zoomWheelEnabled: false,
204
             handleRightClicks:true,
205
             zoomBoxKeyMask: OpenLayers.Handler.MOD_CTRL
206
           }
207
         )
208
      ];
209

    
210

    
211
      var layerByNameMap = {
212
              tdwg1: 'topp:tdwg_level_1',
213
              tdwg2: 'topp:tdwg_level_2',
214
              tdwg3: 'topp:tdwg_level_3',
215
              tdwg4: 'topp:tdwg_level_4'
216
      };
217

    
218
      if(opts.resizable == true) {
219
        // resizable requires jQueryUI to  be loaded!!!
220
        mapContainerElement.resizable({
221
          resize: function( event, ui ) {
222
            map.updateSize();
223
            //   this.printInfo();
224
          }
225
        });
226
      }
227

    
228
        /**
229
         *
230
         */
231
        this.create = function(){ // public function
232

    
233
          // set the height of the container element
234
          adjustHeight();
235

    
236
          // register for resize events to be able to adjust the map aspect ratio and legend position
237
          jQuery( window ).resize(function() {
238
            adjustHeight();
239
            adjustLegendAsElementPosition();
240
          });
241

    
242
          createBaseLayers(opts.baseLayerNames, opts.defaultBaseLayerName, opts.customWMSBaseLayerData);
243

    
244
          initMap();
245

    
246
          // now it is
247
          if(opts.boundingBox){
248
            boundingBox = OpenLayers.Bounds.fromString(opts.boundingBox);
249
            boundingBox.transform(CdmOpenLayers.projections.epsg_4326, map.getProjectionObject());
250
          }
251

    
252
          // -- Distribution Layer --
253
          var mapServiceRequest;
254
          var distributionQuery = mapElement.attr('distributionQuery');
255

    
256
          if(distributionQuery !== undefined){
257
            distributionQuery = mergeQueryStrings(distributionQuery, '&recalculate=false');
258
            if(typeof legendPosition === 'number'){
259
              distributionQuery = mergeQueryStrings(distributionQuery, 'legend=1&mlp=' + opts.legendPosition);
260
            }
261
            if(opts.boundingBox){
262
              distributionQuery = mergeQueryStrings(distributionQuery, 'bbox=' + boundingBox);
263
            }
264

    
265
            distributionQuery = mergeQueryStrings(distributionQuery, 'callback=?');
266
            var legendFormatQuery = mapElement.attr('legendFormatQuery');
267
            if(legendFormatQuery !== undefined){
268
              legendImgSrc = mergeQueryStrings('/GetLegendGraphic?SERVICE=WMS&VERSION=1.1.1', legendFormatQuery);
269
            }
270

    
271
            mapServiceRequest = mapserverBaseUrl + mapServicePath + '/' + mapserverVersion + '/rest_gen.php?' + distributionQuery;
272

    
273
            LAYER_DATA_CNT++;
274
            jQuery.ajax({
275
              url: mapServiceRequest,
276
              dataType: "jsonp",
277
              success: function(data){
278
                  var layers = createDataLayer(data, "AREA");
279
                  addLayers(layers);
280
                  layerDataLoaded();
281
              }
282
            });
283
          }
284

    
285
          // -- Occurrence Layer --
286
          var occurrenceQuery = mapElement.attr('occurrenceQuery');
287
          if(occurrenceQuery !== undefined){
288
            occurrenceQuery = mergeQueryStrings(occurrenceQuery, '&recalculate=false');
289
//              if(typeof legendPosition == 'number'){
290
//              occurrenceQuery = mergeQueryStrings(distributionQuery, 'legend=1&mlp=' + opts.legendPosition);
291
//              }
292

    
293

    
294
            occurrenceQuery = mergeQueryStrings(occurrenceQuery, 'callback=?');
295
//              var legendFormatQuery = mapElement.attr('legendFormatQuery');
296
//              if(legendFormatQuery !== undefined){
297
//              legendImgSrc = mergeQueryStrings('/GetLegendGraphic?SERVICE=WMS&VERSION=1.1.1', legendFormatQuery);
298
//              }
299
            if(opts.boundingBox){
300
              occurrenceQuery = mergeQueryStrings(occurrenceQuery, 'bbox=' + boundingBox);
301
            }
302

    
303
            mapServiceRequest = mapserverBaseUrl + mapServicePath + '/' + mapserverVersion + '/rest_gen.php?' + occurrenceQuery;
304

    
305
            LAYER_DATA_CNT++;
306
            jQuery.ajax({
307
              url: mapServiceRequest,
308
              dataType: "jsonp",
309
              success: function(data){
310
                  var layers = createDataLayer(data, "POINT");
311
                  addLayers(layers);
312
                  layerDataLoaded();
313
              }
314
            });
315
          }
316

    
317
          if(LAYER_DATA_CNT === 0) {
318
            // a map only with base layer
319
            initPostDataLoaded();
320
          }
321

    
322
          // -- Overlay Layer --
323
          if(opts.wmsOverlayLayerData.params){
324
            overlay_layer_params = opts.wmsOverlayLayerData.params;
325
            overlay_layer_params.transparent=true;
326
            wmsOverlay = createWMSLayer(
327
              opts.wmsOverlayLayerData.name,
328
              opts.wmsOverlayLayerData.url,
329
              overlay_layer_params,
330
              null,
331
              null,
332
              null,
333
              null
334
            );
335

    
336
            if(map.addLayer(wmsOverlay)){
337
              // map.setLayerZIndex(wmsOverlay, 100);
338
              wmsOverlay.setVisibility(true);
339
              log("Overlay wms added");
340
            } else {
341
              log("ERROR adding overlay wms layer")
342
            }
343
          }
344

    
345
          log("Map viewer creation complete.");
346

    
347
        };
348

    
349
        var layerDataLoaded = function() {
350
          LAYER_DATA_CNT--;
351
          if(LAYER_DATA_CNT === 0){
352
            initPostDataLoaded();
353
          }
354
        };
355

    
356
        var initPostDataLoaded = function () {
357
          // all layers prepared, make the visible
358
          map.layers.forEach(function(layer){
359

    
360
            // hack for cuba
361
            if(layer.name === "flora_cuba_2016_regions"){
362
              map.setLayerZIndex(layer, 5);
363
            }
364
            if(layer.name === "flora_cuba_2016_provinces"){
365
              map.setLayerZIndex(layer, 6);
366
            }
367
            if(layer.name === "flora_cuba_2016_world"){
368
              map.setLayerZIndex(layer, 4);
369
            }
370

    
371
            layer.setVisibility(true);
372
          });
373

    
374
          // zoom to the zoomToBounds
375
          log(" > starting zoomToExtend " + zoomToBounds, true);
376
          map.zoomToExtent(zoomToBounds, zoomToClosestLevel);
377

    
378
          if(map.getZoom() > opts.maxZoom){
379
            map.zoomTo(opts.maxZoom);
380
          } else if(map.getZoom() < opts.minZoom){
381
            map.zoomTo(opts.minZoom);
382
          }
383

    
384
          log(" > zoomToExtend done", true);
385
        };
386

    
387
        var getHeight = function(){
388
          return mapContainerElement.width() / opts.aspectRatio;
389
        };
390

    
391
        var getWidth = function(){
392
          return mapContainerElement.width();
393
        };
394

    
395
        var adjustHeight = function() {
396
          mapContainerElement.css("height", getHeight());
397
        };
398

    
399
        /**
400
         * public function
401
         */
402
        this.registerEvents = function(events){
403
            for (var key in events) {
404
                if (events.hasOwnProperty(key)) {
405
                    map.events.register(key, map , events[key]);
406
                }
407
            }
408
        };
409

    
410

    
411
        /**
412
         * public function
413
         */
414
        this.getMap = function(){
415
            return map;
416
        };
417

    
418
        /**
419
         * Prints info on the current map into the jQuery element
420
         * as set in the options (opts.infoElement)
421
         * public function
422
         *
423
         */
424
        this.printInfo = function(){
425

    
426

    
427
            var mapExtendDegree = null;
428
            if(map.getExtent() != null){
429
              // If the baselayer is not yet set, getExtent() returns null.
430
              mapExtendDegree = map.getExtent().clone();
431
              mapExtendDegree.transform(map.baseLayer.projection, CdmOpenLayers.projections.epsg_4326);
432
            }
433

    
434
            var info = "<dl>";
435
            info += "<dt>zoom:<dt><dd>" + map.getZoom() + "</dd>";
436
            if(opts.debug){
437
                info += "<dt>map resolution:<dt><dd>" + map.getResolution() + "</dd>";
438
                info += "<dt>map max resolution:<dt><dd>" + map.getMaxResolution() + "</dd>";
439
                info += "<dt>map scale:<dt><dd>" + map.getScale() + "</dd>";
440
                info += "<dt>map width, height:<dt><dd>" + mapContainerElement.width() +  ", " + mapContainerElement.height() + "</dd>";
441
                info += "<dt>map aspect ratio:<dt><dd>" + mapContainerElement.width() / mapContainerElement.height() + "</dd>";
442
                if(map.getExtent() != null){
443
                  info += "<dt>map extent bbox:<dt><dd class=\"map-extent-bbox\">" + map.getExtent().toBBOX() + ", <strong>degree:</strong> <span class=\"degree-value\">" + mapExtendDegree.toBBOX() + "</span></dd>";
444
                  info += "<dt>map maxExtent bbox:<dt><dd>" + map.getMaxExtent().toBBOX() + "</dd>";
445
                  info += "<dt>baselayer extent bbox:<dt><dd class=\"baselayer-extent-bbox\">" +  map.baseLayer.getExtent().toBBOX() + ", <strong>degree:</strong> <span class=\"degree-value\">"
446
                    + map.baseLayer.getExtent().clone().transform(map.baseLayer.projection, CdmOpenLayers.projections.epsg_4326) + "</span></dd>"
447
                  info += "<dt>baselayer projection:<dt><dd>" + map.baseLayer.projection.getCode() + "</dd>";
448
                }
449
            } else {
450
                info += "<dt>bbox:<dt><dd>" + (mapExtendDegree != null ? mapExtendDegree.toBBOX() : 'NULL') + "</dd>";
451
            }
452
            info += "</dl>";
453

    
454
            if(infoElement == null){
455
                infoElement = jQuery('<div class="map_info"></div>');
456
                mapElement.parent().after(infoElement);
457
            }
458
            infoElement.html(info);
459
        };
460

    
461
        /**
462
         * Initialize the Openlayers Map with the base layer
463
         */
464
        var initMap = function(){
465

    
466
          if(opts.showLayerSwitcher === true){
467
              defaultControls.push(new OpenLayers.Control.LayerSwitcher({'ascending':false}));
468
          }
469

    
470
          // defaultControls.unshift(layerLoadingControl()); // as first control, needs to be below all others!
471

    
472
//          var maxExtentByAspectRatio = cropBoundsToAspectRatio(defaultBaseLayer.maxExtent, getWidth/getHeight);
473
          var maxResolution = null;
474
          // gmaps has no maxExtent at this point, need to check for null
475
          if(defaultBaseLayer.maxExtent != null){
476
              maxResolution = Math[(opts.displayOutsideMaxExtent ? 'max' : 'min')](
477
                      defaultBaseLayer.maxExtent.getWidth() / getWidth(),
478
                      defaultBaseLayer.maxExtent.getHeight() / getHeight()
479
              );
480
          }
481
          console.log("mapOptions.maxResolution: " + maxResolution);
482
          console.log("mapOptions.restrictedExtent: " + defaultBaseLayer.maxExtent);
483

    
484
          map = new OpenLayers.Map(
485
            mapElement.attr('id'),
486
            {
487
              // defines the map ui elements and interaction features
488
              controls: defaultControls,
489

    
490
              // maxResolution determines the lowest zoom level and thus places the map
491
              // in its maximum extent into the available view port so that no additinal
492
              // gutter is visible and no parts of the map are hidden
493
              // see http://trac.osgeo.org/openlayers/wiki/SettingZoomLevels
494
              // IMPORTANT!!!
495
              // the maxResulution set here will be overwritten if the baselayers maxResolution
496
              // it is set
497
              maxResolution: maxResolution,
498

    
499
              // setting restrictedExtent the the maxExtent prevents from panning the
500
              // map out of its bounds
501
              restrictedExtent: defaultBaseLayer.maxExtent,
502
//                      maxExtent: defaultBaseLayer.maxExtent,
503

    
504
              // Setting the map.fractionalZoom property to true allows zooming to an arbitrary level
505
              // (between the min and max resolutions).
506
              // fractional tiles are not supported by XYZ layers like OSM so this option would
507
              // break the tile retrieval for OSM (e.g.: tile for fractional zoom level
508
              // 1.2933333333333332 = http://b.tile.openstreetmap.org/1.2933333333333332/1/0.png)
509
              fractionalZoom: defaultBaseLayer.CLASS_NAME != "OpenLayers.Layer.OSM" && defaultBaseLayer.CLASS_NAME != "OpenLayers.Layer.XYZ",
510

    
511
              eventListeners: opts.eventListeners,
512
              // creating the map with a null theme, since we include the stylesheet directly in the page
513
              theme: null
514

    
515
            }
516
          );
517

    
518
          //add the base layers
519

    
520
          addLayers(baseLayers);
521
          map.setBaseLayer(defaultBaseLayer);
522

    
523
          // calculate the bounds to zoom to
524
          zoomToBounds = zoomToBoundsFor(opts.boundingBox ? opts.boundingBox : defaultBaseLayerBoundingBox, defaultBaseLayer);
525
          zoomToBounds = cropBoundsToAspectRatio(zoomToBounds, map.getSize().w / map.getSize().h);
526
          console.log("baselayer zoomToBounds: " + zoomToBounds);
527

    
528
        };
529

    
530
        var addLayers = function(layers){
531

    
532
          layers.forEach(function(layer){
533
            // layer.setVisibility(false);
534
          });
535

    
536
          map.addLayers(layers);
537
        };
538

    
539
        /**
540
         * add a distribution or occurrence layer
541
         *
542
         * @param mapResponseObj
543
         *   The reponse object returned by the edit map service
544
         * @param dataType
545
         *   either "AREA" or "POINT"
546
         */
547
        var createDataLayer = function(mapResponseObj, dataType){
548

    
549
            console.log("creating data layer of type " + dataType);
550

    
551
            var dataLayerOptions = {
552
                    isBaseLayer: false,
553
                    displayInLayerSwitcher: true,
554
                    maxExtent: map.maxExtent.clone().transform(new OpenLayers.Projection("EPSG:4326"), map.baseLayer.projection),
555
                    displayOutsideMaxExtent: true
556
            };
557

    
558
            var layers = [];
559
            // add additional layers, get them from the mapResponseObj
560
            if(mapResponseObj !== undefined){
561
                if(dataType == "POINT" && mapResponseObj.points_sld !== undefined){
562
                  var pointLayer;
563
                  // it is a response for an point map
564
                  var geoserverUri;
565
                  if(mapResponseObj.geoserver) {
566
                      geoserverUri = mapResponseObj.geoserver;
567
                  } else {
568
                      // it is an old service which is not providing the corresponding geoserver URI, so we guess it
569
                      geoserverUri = mapserverBaseUrl + "/geoserver/wms";
570
                  }
571

    
572
                  //TODO points_sld should be renamed to sld in response + fill path to sld should be given
573
                  pointLayer = new OpenLayers.Layer.WMS(
574
                          'points',
575
                          geoserverUri,
576
                          {
577
                              layers: 'topp:rest_points',
578
                              transparent:"true",
579
                              format:"image/png"
580
                          },
581
                          dataLayerOptions
582
                  );
583

    
584
                  var sld = mapResponseObj.points_sld;
585
                  if(sld.indexOf("http://") !== 0){
586
                      // it is an old servive which is not providing the full sdl URI, so we guess it
587
                      //  http://edit.africamuseum.be/synthesys/www/v1/sld/
588
                      //  http://edit.br.fgov.be/synthesys/www/v1/sld/
589
                      sld =  mapserverBaseUrl + "/synthesys/www/v1/sld/" + sld;
590
                  }
591
                  pointLayer.params.SLD = sld;
592

    
593
                  layers.push(pointLayer);
594
                } else {
595
                    // it is a response from for a distribution map
596
                    console.log("start with adding distribution layers :");
597
                    for ( var i in mapResponseObj.layers) {
598
                        var layerData = mapResponseObj.layers[i];
599

    
600
                        console.log(" " + i +" -> " + layerData.tdwg);
601
                        var layer = new OpenLayers.Layer.WMS(
602
                                layerData.tdwg,
603
                                mapResponseObj.geoserver + "/wms",
604
                                {
605
                                    layers: layerByNameMap[layerData.tdwg],
606
                                    transparent:"true",
607
                                    format:"image/png"
608
                                },
609
                                dataLayerOptions
610
                                );
611
                        layer.params.SLD = layerData.sld;
612
                        layer.setOpacity(opts.distributionOpacity);
613

    
614
                        layers.push(layer);
615
                    }
616
                }
617

    
618
                if(layers.length > 0) {
619
                  // calculate zoomBounds using the first layer
620
                  if(mapResponseObj.bbox !== undefined){
621
                    // mapResponseObj.bbox are bounds for the projection of the specific layer
622
                    var newBounds =  OpenLayers.Bounds.fromString( mapResponseObj.bbox );
623
                    newBounds.transform(layers[0].projection, map.getProjectionObject());
624
                    if(dataBounds !== null){
625
                      dataBounds.extend(newBounds);
626
                    } else if(newBounds !== undefined){
627
                      dataBounds = newBounds;
628
                    }
629

    
630
                    zoomToBounds = dataBounds;
631
                    console.log("data layer zoomToBounds: " + zoomToBounds);
632
                    zoomToClosestLevel = false;
633
                  }
634
                }
635

    
636

    
637

    
638
                if(legendImgSrc != null && opts.legendPosition !== undefined && mapResponseObj.legend !== undefined){
639
                    var legendSrcUrl = mapResponseObj.geoserver + legendImgSrc + mapResponseObj.legend;
640
                    addLegendAsElement(legendSrcUrl);
641
                    //addLegendAsLayer(legendSrcUrl, map);
642
                }
643

    
644
                return layers;
645
            }
646

    
647
        };
648

    
649
        /**
650
         *
651
         */
652
        var addLegendAsElement= function(legendSrcUrl){
653

    
654
            var legendElement = jQuery('<div class="openlayers_legend"></div>');
655
            var legendImage = jQuery('<img src="' + legendSrcUrl + '"/>');
656
            legendElement
657
                .css('opacity', opts.legendOpacity)
658
                .css('position', 'relative')
659
                .css('z-index', '1002')
660
                .css('top', -mapElement.height());
661
            legendImage.load(function () {
662
                jQuery(this).parent()
663
                    .css('left', getWidth() - jQuery(this).width())
664
                    .width(jQuery(this).width());
665
                // reset height to original value
666
                adjustHeight();
667
            });
668
            legendElement.html(legendImage);
669
            mapElement.after(legendElement);
670
        };
671

    
672
         var adjustLegendAsElementPosition = function (){
673
           var legendContainer = mapContainerElement.children('.openlayers_legend');
674
           var legendImage = legendContainer.children('img');
675
           legendContainer.css('top', -mapElement.height())
676
             .css('left', getWidth() - legendImage.width());
677
         };
678

    
679

    
680
        var addLegendAsLayer= function(legendSrcUrl, map){
681
            var w, h;
682

    
683
            // 1. download image to find height and width
684
            mapElement.after('<div class="openlayers_legend"><img src="' + legendSrcUrl + '"></div>');
685
            mapElement.next('.openlayers_legend').css('display', 'none').css('opacity', opts.legendOpacity).find('img').load(function () {
686

    
687
                w = mapElement.next('.openlayers_legend').find('img').width();
688
                h = mapElement.next('.openlayers_legend').find('img').height();
689
                mapElement.next('.openlayers_legend').remove();
690

    
691
//              createLegendLayer();
692
//              // 2. create the Legend Layer
693
                //TODO createLegendLayer as inner function seems like an error
694
//              var createLegendLayer = function(){
695
                //
696
                //
697
//              var legendLayerOptions={
698
//              maxResolution: '.$maxRes.',
699
//              maxExtent: new OpenLayers.Bounds(0, 0, w, h)
700
//              };
701
                //
702
//              var legendLayer = new OpenLayers.Layer.Image(
703
//              'Legend',
704
//              legendSrcUrl,
705
//              new OpenLayers.Bounds(0, 0, w, h),
706
//              new OpenLayers.Size(w, h),
707
//              imageLayerOptions);
708
//              };
709
            });
710

    
711

    
712
        };
713

    
714
        /**
715
         * merge 2 Url query strings
716
         */
717
        var mergeQueryStrings = function(queryStr1, queryStr2){
718
            if(queryStr1.charAt(queryStr1.length - 1) != '&'){
719
                queryStr1 += '&';
720
            }
721
            if(queryStr2.charAt(0) == '&'){
722
                return queryStr1 + queryStr2.substr(1);
723
            } else {
724
                return queryStr1 + queryStr2;
725
            }
726

    
727
        };
728

    
729
        /**
730
         *
731
         */
732
        var createBaseLayers = function( baseLayerNames, defaultBaseLayerName, customWMSBaseLayerData){
733

    
734
            for(var i = 0; i <  baseLayerNames.length; i++) {
735
                // create the layer
736
                if (baseLayerNames[i] === "custom_wms_base_layer_1"){
737
                    wmsBaseLayer =createWMSLayer(
738
                            customWMSBaseLayerData.name,
739
                            customWMSBaseLayerData.url,
740
                            customWMSBaseLayerData.params,
741
                            customWMSBaseLayerData.projection,
742
                            customWMSBaseLayerData.proj4js_def,
743
                            customWMSBaseLayerData.units,
744
                            customWMSBaseLayerData.max_extent
745
                    );
746
                  wmsBaseLayer.setIsBaseLayer(true);
747
                  baseLayers[i] = wmsBaseLayer;
748
                } else {
749
                    baseLayers[i] = window.CdmOpenLayers.getLayerByName(baseLayerNames[i]);
750
                }
751
                // set default baselayer
752
                if(baseLayerNames[i] === defaultBaseLayerName){
753
                    defaultBaseLayer = baseLayers[i];
754
                }
755

    
756
            }
757
        };
758

    
759
        /**
760
         * returns the intersection of the bounds b1 and b2.
761
         * The b1 and b2 do not intersect b1 will be returned.
762
         *
763
         * @param OpenLayers.Bounds b1
764
         * @param OpenLayers.Bounds b2
765
         *
766
         * @return the bounds of the intersection between both rectangles
767
         */
768
        var intersectionOfBounds = function (b1, b2){
769

    
770
            if(b1.intersectsBounds(b2)){
771

    
772
                var left = Math.max(b1.left, b2.left);
773
                var bottom = Math.max(b1.bottom, b2.bottom);
774
                var right = Math.min(b1.right, b2.right);
775
                var top = Math.min(b1.top, b2.top);
776

    
777
                return new OpenLayers.Bounds(left, bottom, right, top);
778

    
779
            } else {
780
                return b1;
781
            }
782
        };
783

    
784
        /**
785
         *
786
         * @param OpenLayers.Bounds b
787
         * @param float aspectRatio width/height
788
         *
789
         * @return the bounds cropped to the given aspectRatio
790
         */
791
        var cropBoundsToAspectRatio = function (b, aspectRatio){
792

    
793
            var cropedB = b.clone();
794

    
795
            if(aspectRatio == 1){
796
                return cropedB;
797
            }
798

    
799
            /*
800
             * LonLat:
801
             *   lon {Float} The x-axis coodinate in map units
802
             *   lat {Float} The y-axis coordinate in map units
803
             */
804
            var center = cropedB.getCenterLonLat();
805
            if(aspectRatio < 1){
806
                var dist = (b.getHeight() / 2) * aspectRatio;
807
                cropedB.top = center.lat + dist;
808
                cropedB.cropedBottom = center.lat - dist;
809
            } else if(aspectRatio > 1){
810
                var dist = (b.getWidth() / 2) / aspectRatio;
811
                cropedB.left = center.lon - dist;
812
                cropedB.right = center.lon + dist;
813
            }
814
            return cropedB;
815
        };
816

    
817
        /**
818
         * returns the version number contained in the version string:
819
         *   v1.1 --> 1.1
820
         *   v1.2_dev --> 1.2
821
         */
822
        var mapServerVersionNumber = function() {
823
            var pattern = /v([\d\.]+).*$/;
824
            var result;
825
            if (result = mapserverVersion.match(pattern) !== null) {
826
                return result[0];
827
            } else {
828
                return null;
829
            }
830
        };
831

    
832

    
833

    
834
      /**
835
       * returns the zoom to bounds.
836
       *
837
       * NOTE: only used for the base layer
838
       *
839
       * @param bboxString
840
       *     a string representation of the bounds in degree for epsg_4326
841
       * @param layer
842
       *     the Openlayers.Layer
843
       *
844
       * @return the bboxstring projected onto the layer and intersected with the maximum extent of the layer
845
       */
846
      var zoomToBoundsFor = function(bboxString, layer){
847
        var zoomToBounds;
848
        if(bboxString) {
849
          zoomToBounds = OpenLayers.Bounds.fromString(bboxString);
850
          // transform bounding box given in degree values to the projection of the base layer
851
          zoomToBounds.transform(CdmOpenLayers.projections.epsg_4326, layer.projection);
852
        } else if(layer.maxExtent) {
853
          zoomToBounds = layer.maxExtent;
854
          // no need to transform since the bounds are obtained from the layer
855
        } else {
856
          zoomToBounds = new OpenLayers.Bounds(-180, -90, 180, 90);
857
          // transform bounding box given in degree values to the projection of the base layer
858
          zoomToBounds.transform(CdmOpenLayers.projections.epsg_4326, layer.projection);
859
        }
860

    
861
        zoomToBounds = intersectionOfBounds(layer.maxExtent, zoomToBounds);
862

    
863
        return zoomToBounds;
864
      };
865

    
866
        var log = function(message, addTimeStamp){
867
          var timestamp = '';
868
          if(addTimeStamp == true){
869
            var time = new Date();
870
            timestamp = time.getSeconds() + '.' + time.getMilliseconds() + 's';
871
          }
872
          console.log(timestamp + message);
873
        };
874

    
875
        /**
876
         * Creates a WMS Base layer
877
         * @param String name
878
         *     A name for the layer
879
         * @param String url
880
         *     Base url for the WMS (e.g.  http://wms.jpl.nasa.gov/wms.cgi)
881
         * @param Object params
882
         *     An object with key/value pairs representing the GetMap query string parameters and parameter values.
883
         * @param Object projection
884
         *    A OpenLayers.Projection object
885
         */
886
        var createWMSLayer= function(name, url, params, projection, proj4js_def, units, maxExtent){
887

    
888
            console.log("creating WMS Layer " + name);
889

    
890
            if(projection && proj4js_def){
891
                // in case projection has been defined for the layer and if there is also
892
                // a Proj4js.defs, add it!
893
                Proj4js.defs[projection] = proj4js_def;
894
            }
895

    
896
            if(maxExtent === null){
897
                maxExtent = CdmOpenLayers.mapExtends.epsg_4326.clone();
898
                maxExtent.transform(CdmOpenLayers.projections.epsg_4326, projection);
899
            }
900

    
901
          wmsLayer = new OpenLayers.Layer.WMS(
902
            name,
903
            url,
904
            params,
905
            {
906
              maxExtent: maxExtent,
907
              projection: projection,
908
              units: units,
909
              isBaseLayer: false,
910
              displayInLayerSwitcher: true
911
            }
912
          );
913

    
914
          if(wmsLayer === null){
915
            console.log("Error creating WMS Layer");
916
          }
917

    
918
          return  wmsLayer;
919
        };
920

    
921
        var layerLoadingControl = function() {
922

    
923
          var control = new OpenLayers.Control();
924

    
925
          OpenLayers.Util.extend(control, {
926

    
927
            LAYERS_LOADING: 0,
928

    
929
            updateState: function () {
930
              if(this.div != null){
931
                if (this.LAYERS_LOADING > 0) {
932
                  this.div.style.display = "block";
933
                } else {
934
                  this.div.style.display = "none";
935
                }
936
              }
937
            },
938

    
939
            updateSize: function () {
940
              this.div.style.width = this.map.size.w + "px";
941
              this.div.style.height = this.map.size.h  + "px";
942
              this.div.style.textAlign = "center";
943
              this.div.style.lineHeight = this.map.size.h  + "px";
944
            },
945

    
946
            counterIncrease: function (layer) {
947
              this.control.LAYERS_LOADING++;
948
              log(' > loading start : ' + this.layer.name + ' ' + this.control.LAYERS_LOADING, true);
949
              this.control.updateState();
950
            },
951

    
952
            counterDecrease: function (layer) {
953
              this.control.LAYERS_LOADING--;
954
              log(' > loading end : ' + this.layer.name + ' ' + this.control.LAYERS_LOADING, true);
955
              this.control.updateState();
956
            },
957

    
958
            draw: function () {
959

    
960
              // call the default draw function to initialize this.div
961
              OpenLayers.Control.prototype.draw.apply(this, arguments);
962

    
963
              this.map.events.register('updatesize', this, function(e){
964
                  this.updateSize();
965
                }
966
              );
967

    
968
              var loadingIcon = document.createElement("i");
969
              var fa_class = document.createAttribute("class");
970
              // fa-circle-o-notch fa-spin
971
              // fa-spinner fa-pulse
972
              // fa-refresh
973
              fa_class.value = "fa fa-refresh fa-spin fa-5x";
974
              loadingIcon.attributes.setNamedItem(fa_class);
975

    
976
              this.updateSize();
977

    
978
              this.div.appendChild(loadingIcon);
979

    
980
              this.registerEvents();
981

    
982
              return this.div;
983
            },
984

    
985
            registerEvents: function() {
986

    
987
              this.map.events.register('preaddlayer', this, function(e){
988
                console.log(" > preaddlayer " + e.layer.name);
989
                e.layer.events.register('loadstart', {control: this, layer: e.layer}, this.counterIncrease);
990
                e.layer.events.register('loadend', {control: this, layer: e.layer}, this.counterDecrease);
991
              });
992
            }
993

    
994
          });
995

    
996
          return control;
997
        }
998

    
999
    }; // end of CdmOpenLayers.Map
1000
})();
1001

    
1002

    
1003

    
1004

    
1005

    
1006

    
1007

    
1008

    
1009

    
(2-2/2)