Project

General

Profile

Download (37.5 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: 15,
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
        untiled: null
64
    },
65
    wmsOverlayLayerData: {
66
      name: null,
67
      url: null,
68
      params: null,
69
      untiled: null
70
    },
71
    /**
72
     * when true the map is made resizable by adding the jQueryUI widget resizable
73
     * to the map container. This feature requires that the jQueryUI is loaded
74
     */
75
    resizable: false
76
  };
77
})(jQuery);
78

    
79
/**************************************************************************
80
 *                          CdmOpenLayers
81
 **************************************************************************/
82
(function() {
83

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

    
89
        // EPSG:3857 from http://spatialreference.org/ref/sr-org/6864/proj4/
90
        // OpenStreetMap etc
91
        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';
92

    
93
        var projections = {
94
                epsg_4326: new OpenLayers.Projection("EPSG:4326"),
95
                epsg_900913: new OpenLayers.Projection("EPSG:900913"),
96
                epsg_3857:  new OpenLayers.Projection("EPSG:3857")
97
        };
98
        var mapExtends = {
99
                epsg_4326: new OpenLayers.Bounds(-180, -90, 180, 90),
100
                //  Spherical Mercator epsg_900913 is not supporting the whole marble
101
                epsg_900913: new OpenLayers.Bounds(-179, -85, 179, 85),
102
                //  Spherical Mercator
103
                epsg_3857: new OpenLayers.Bounds(-179, -85, 179, 85)
104
        };
105
        // transform epsg_900913 to units meter
106
        mapExtends.epsg_900913.transform(projections.epsg_4326, projections.epsg_900913);
107
        mapExtends.epsg_3857.transform(projections.epsg_4326, projections.epsg_3857);
108

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

    
117
    })(); // end of namespace definition for CdmOpenLayers
118

    
119
    /**
120
     * The CdmOpenLayers.Map constructor
121
     * @param mapElement
122
     * @param mapserverBaseUrl
123
     * @param mapserverVersion
124
     * @param opts
125
     * @returns
126
     */
127
    window.CdmOpenLayers.Map = function(mapElement, mapserverBaseUrl, mapserverVersion, opts){
128

    
129
      var mapServicePath = '/edit_wp5';
130

    
131
      // firebug console stub (avoids errors if firebug is not active)
132
      if(typeof console === "undefined") {
133
          console = { log: function() { } };
134
      }
135

    
136
      // sanitize given options
137
      try {
138
          opts.customWMSBaseLayerData.max_extent = OpenLayers.Bounds.fromString(opts.customWMSBaseLayerData.max_extent);
139
      } catch(e){
140
          opts.customWMSBaseLayerData.max_extent = null;
141
      }
142

    
143

    
144
      var legendImgSrc = null;
145

    
146
      var map = null;
147

    
148
      var infoElement = null;
149

    
150
      var baseLayers = [];
151

    
152
      var defaultBaseLayer = null;
153

    
154
      /**
155
       * The top most layer which will be places above all data layers
156
       *
157
       * @type {null}
158
       */
159
      var wmsOverlay = null;
160

    
161
      /**
162
       * Default bounding box for map viewport in the projection of the base layer.
163
       * as defined by the user, can be null.
164
       *
165
       * These are bounds in the epsg_4326 projection, and will be transformed to the baselayer projection.
166
       *
167
       * @type string
168
       */
169
      var defaultBaseLayerBoundingBox = "-180,-90,180,90";
170

    
171
      /**
172
       * bounding box for map viewport as defined by the user, can be null.
173
       *
174
       * These are bounds in the projection of the base layer.
175
       *
176
       * @type string
177
       */
178
      var boundingBox = null;
179

    
180
      /**
181
       * Bounds for the view port calculated from the data layer responses.
182
       * These are either calculated by the minimum bounding box which
183
       * encloses the data in the data layers, or it is equal to the
184
       * boundingBox as defined by the user.
185
       *
186
       * These are bounds in the projection of the base layer.
187
       *
188
       * @see boundingBox
189
       *
190
       * @type OpenLayers.Bounds
191
       */
192
      var dataBounds = null;
193

    
194
      /**
195
       * Final value for the view port, calculated from the other bounds.
196
       *
197
       * These are bounds in the projection of the base layer.
198
       *
199
       * @type OpenLayers.Bounds
200
       */
201
      var zoomToBounds = null;
202

    
203
      var zoomToClosestLevel = true;
204

    
205
      var LAYER_DATA_CNT = 0;
206

    
207
      /* this is usually the <div id="openlayers"> element */
208
      var mapContainerElement = mapElement.parent();
209

    
210
      var defaultControls = [
211
         new OpenLayers.Control.PanZoom(),
212
         new OpenLayers.Control.Navigation(
213
           {
214
             zoomWheelEnabled: false,
215
             handleRightClicks:true,
216
             zoomBoxKeyMask: OpenLayers.Handler.MOD_CTRL
217
           }
218
         )
219
      ];
220

    
221

    
222
      var layerByNameMap = {
223
              tdwg1: 'topp:tdwg_level_1',
224
              tdwg2: 'topp:tdwg_level_2',
225
              tdwg3: 'topp:tdwg_level_3',
226
              tdwg4: 'topp:tdwg_level_4'
227
      };
228

    
229
      if(opts.resizable === true) {
230
        // resizable requires jQueryUI to  be loaded!!!
231
        mapContainerElement.resizable({
232
          resize: function( event, ui ) {
233
            map.updateSize();
234
            //   this.printInfo();
235
          }
236
        });
237
      }
238

    
239
        /**
240
         *
241
         */
242
        this.create = function(){ // public function
243

    
244
          // set the height of the container element
245
          adjustHeight();
246

    
247
          // register for resize events to be able to adjust the map aspect ratio and legend position
248
          jQuery( window ).resize(function() {
249
            adjustHeight();
250
            adjustLegendAsElementPosition();
251
          });
252

    
253
          createBaseLayers(opts.baseLayerNames, opts.defaultBaseLayerName, opts.customWMSBaseLayerData);
254

    
255
          initMap();
256

    
257
          // now it is
258
          if(opts.boundingBox){
259
            boundingBox = OpenLayers.Bounds.fromString(opts.boundingBox);
260
            boundingBox.transform(CdmOpenLayers.projections.epsg_4326, map.getProjectionObject());
261
          }
262

    
263
          // -- Distribution Layer --
264
          var mapServiceRequest;
265
          var distributionQuery = mapElement.attr('distributionQuery');
266

    
267
          if(distributionQuery !== undefined){
268
            distributionQuery = mergeQueryStrings(distributionQuery, '&recalculate=false');
269
            if(typeof legendPosition === 'number'){
270
              distributionQuery = mergeQueryStrings(distributionQuery, 'legend=1&mlp=' + opts.legendPosition);
271
            }
272
            if(opts.boundingBox){
273
              distributionQuery = mergeQueryStrings(distributionQuery, 'bbox=' + boundingBox);
274
            }
275

    
276
            distributionQuery = mergeQueryStrings(distributionQuery, 'callback=?');
277
            var legendFormatQuery = mapElement.attr('legendFormatQuery');
278
            if(legendFormatQuery !== undefined){
279
              legendImgSrc = mergeQueryStrings('/GetLegendGraphic?SERVICE=WMS&VERSION=1.1.1', legendFormatQuery);
280
            }
281

    
282
            mapServiceRequest = mapserverBaseUrl + mapServicePath + '/' + mapserverVersion + '/rest_gen.php?' + distributionQuery;
283

    
284
            LAYER_DATA_CNT++;
285
            jQuery.ajax({
286
              url: mapServiceRequest,
287
              dataType: "jsonp",
288
              success: function(data){
289
                  var layers = createDataLayer(data, "AREA");
290
                  addLayers(layers);
291
                  layerDataLoaded();
292
              }
293
            });
294
          }
295

    
296
          // -- Occurrence Layer --
297
          var occurrenceQuery = mapElement.attr('occurrenceQuery');
298
          if(occurrenceQuery !== undefined){
299
            occurrenceQuery = mergeQueryStrings(occurrenceQuery, '&recalculate=false');
300
//              if(typeof legendPosition == 'number'){
301
//              occurrenceQuery = mergeQueryStrings(distributionQuery, 'legend=1&mlp=' + opts.legendPosition);
302
//              }
303

    
304

    
305
            occurrenceQuery = mergeQueryStrings(occurrenceQuery, 'callback=?');
306
//              var legendFormatQuery = mapElement.attr('legendFormatQuery');
307
//              if(legendFormatQuery !== undefined){
308
//              legendImgSrc = mergeQueryStrings('/GetLegendGraphic?SERVICE=WMS&VERSION=1.1.1', legendFormatQuery);
309
//              }
310
            if(opts.boundingBox){
311
              occurrenceQuery = mergeQueryStrings(occurrenceQuery, 'bbox=' + boundingBox);
312
            }
313

    
314
            mapServiceRequest = mapserverBaseUrl + mapServicePath + '/' + mapserverVersion + '/rest_gen.php?' + occurrenceQuery;
315

    
316
            LAYER_DATA_CNT++;
317
            jQuery.ajax({
318
              url: mapServiceRequest,
319
              dataType: "jsonp",
320
              success: function(data){
321
                  var layers = createDataLayer(data, "POINT");
322
                  addLayers(layers);
323
                  layerDataLoaded();
324
              }
325
            });
326
          }
327

    
328
          if(LAYER_DATA_CNT === 0) {
329
            // a map only with base layer
330
            initPostDataLoaded();
331
          }
332

    
333
          // -- Overlay Layer --
334
          if(opts.wmsOverlayLayerData.params){
335
            overlay_layer_params = opts.wmsOverlayLayerData.params;
336
            overlay_layer_params.transparent=true;
337
            wmsOverlay = createWMSLayer(
338
              opts.wmsOverlayLayerData.name,
339
              opts.wmsOverlayLayerData.url,
340
              overlay_layer_params,
341
              null,
342
              null,
343
              null,
344
              null,
345
              opts.wmsOverlayLayerData.untiled
346
            );
347

    
348
            if(map.addLayer(wmsOverlay)){
349
              wmsOverlay.setVisibility(true);
350
              map.setLayerIndex(wmsOverlay, 100);
351
              log("Overlay wms added");
352
            } else {
353
              log("ERROR adding overlay wms layer")
354
            }
355
          }
356

    
357
          log("Map viewer creation complete.");
358

    
359
        };
360

    
361
        var layerDataLoaded = function() {
362
          LAYER_DATA_CNT--;
363
          if(LAYER_DATA_CNT === 0){
364
            initPostDataLoaded();
365
          }
366
        };
367

    
368
        var initPostDataLoaded = function () {
369
          // all layers prepared, make the visible
370
          map.layers.forEach(function(layer){
371
            layer.setVisibility(true);
372
          });
373

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

    
378

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

    
385
          // make sure the wmsOverlay is still on top
386
          if(wmsOverlay){
387
            map.setLayerIndex(wmsOverlay, 100);
388
          }
389

    
390
          log(" > zoomToExtend done", true);
391
        };
392

    
393
      /**
394
       * Returns  the projection of the defaultBaseLayer which is the
395
       * the projection to which all other layers and locations must be transformed.
396
       */
397
      var referenceProjection = function() {
398
        if(defaultBaseLayer){
399
          return defaultBaseLayer.projection;
400
        } else {
401
          log("Error - referenceProjection() defaultBaseLayer not set");
402
          return null;
403
        }
404
      };
405

    
406
      /**
407
       * Returns the maxExtent of the defaultBaseLayer.
408
       */
409
      var referenceMaxExtent = function() {
410
        if(defaultBaseLayer){
411
          return defaultBaseLayer.maxExtent;
412
        } else {
413
          log("Error - referenceMaxExtent() defaultBaseLayer not set");
414
          return null;
415
        }
416
      };
417

    
418
        var getHeight = function(){
419
          return mapContainerElement.width() / opts.aspectRatio;
420
        };
421

    
422
        var getWidth = function(){
423
          return mapContainerElement.width();
424
        };
425

    
426
        var adjustHeight = function() {
427
          mapContainerElement.css("height", getHeight());
428
        };
429

    
430
        /**
431
         * public function
432
         */
433
        this.registerEvents = function(events){
434
            for (var key in events) {
435
                if (events.hasOwnProperty(key)) {
436
                    map.events.register(key, map , events[key]);
437
                }
438
            }
439
        };
440

    
441

    
442
        /**
443
         * public function
444
         */
445
        this.getMap = function(){
446
            return map;
447
        };
448

    
449
        /**
450
         * Prints info on the current map into the jQuery element
451
         * as set in the options (opts.infoElement)
452
         * public function
453
         *
454
         */
455
        this.printInfo = function(){
456

    
457

    
458
            var mapExtendDegree = null;
459
            if(map.getExtent() != null){
460
              // If the baselayer is not yet set, getExtent() returns null.
461
              mapExtendDegree = map.getExtent().clone();
462
              mapExtendDegree.transform(map.baseLayer.projection, CdmOpenLayers.projections.epsg_4326);
463
            }
464

    
465
            var info = "<dl>";
466
            info += "<dt>zoom:<dt><dd>" + map.getZoom() + "</dd>";
467
            if(opts.debug){
468
                info += "<dt>map resolution:<dt><dd>" + map.getResolution() + "</dd>";
469
                info += "<dt>map max resolution:<dt><dd>" + map.getMaxResolution() + "</dd>";
470
                info += "<dt>map scale:<dt><dd>" + map.getScale() + "</dd>";
471
                info += "<dt>map width, height:<dt><dd>" + mapContainerElement.width() +  ", " + mapContainerElement.height() + "</dd>";
472
                info += "<dt>map aspect ratio:<dt><dd>" + mapContainerElement.width() / mapContainerElement.height() + "</dd>";
473
                if(map.getExtent() != null){
474
                  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>";
475
                  info += "<dt>map maxExtent bbox:<dt><dd>" + map.getMaxExtent().toBBOX() + "</dd>";
476
                  info += "<dt>baselayer extent bbox:<dt><dd class=\"baselayer-extent-bbox\">" +  map.baseLayer.getExtent().toBBOX() + ", <strong>degree:</strong> <span class=\"degree-value\">"
477
                    + map.baseLayer.getExtent().clone().transform(map.baseLayer.projection, CdmOpenLayers.projections.epsg_4326) + "</span></dd>"
478
                  info += "<dt>baselayer projection:<dt><dd>" + map.baseLayer.projection.getCode() + "</dd>";
479
                }
480
            } else {
481
                info += "<dt>bbox:<dt><dd>" + (mapExtendDegree !== null ? mapExtendDegree.toBBOX() : 'NULL') + "</dd>";
482
            }
483
            info += "</dl>";
484

    
485
            if(infoElement === null){
486
                infoElement = jQuery('<div class="map_info"></div>');
487
                mapElement.parent().after(infoElement);
488
            }
489
            infoElement.html(info);
490
        };
491

    
492
        /**
493
         * Initialize the Openlayers Map with the base layer
494
         */
495
        var initMap = function(){
496

    
497
          if(opts.showLayerSwitcher === true){
498
              defaultControls.push(new OpenLayers.Control.LayerSwitcher({'ascending':false}));
499
          }
500

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

    
503
//          var maxExtentByAspectRatio = cropBoundsToAspectRatio(defaultBaseLayer.maxExtent, getWidth/getHeight);
504
          var maxResolution = null;
505
          // gmaps has no maxExtent at this point, need to check for null
506
          if(referenceMaxExtent() !== null){
507
              maxResolution = Math[(opts.displayOutsideMaxExtent ? 'max' : 'min')](
508
                referenceMaxExtent().getWidth() / getWidth(),
509
                referenceMaxExtent().getHeight() / getHeight()
510
              );
511
          }
512
          console.log("mapOptions.maxResolution: " + maxResolution);
513
          console.log("mapOptions.restrictedExtent: " + referenceMaxExtent());
514

    
515
          map = new OpenLayers.Map(
516
            mapElement.attr('id'),
517
            {
518
              // defines the map ui elements and interaction features
519
              controls: defaultControls,
520

    
521
              // maxResolution determines the lowest zoom level and thus places the map
522
              // in its maximum extent into the available view port so that no additinal
523
              // gutter is visible and no parts of the map are hidden
524
              // see http://trac.osgeo.org/openlayers/wiki/SettingZoomLevels
525
              // IMPORTANT!!!
526
              // the maxResulution set here will be overwritten if the baselayers maxResolution
527
              // it is set
528
              maxResolution: maxResolution,
529

    
530
              // setting restrictedExtent the the maxExtent prevents from panning the
531
              // map out of its bounds
532
              restrictedExtent: referenceMaxExtent(),
533
//                      maxExtent: referenceMaxExtent(),
534

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

    
542
              eventListeners: opts.eventListeners,
543
              // creating the map with a null theme, since we include the stylesheet directly in the page
544
              theme: null
545

    
546
            }
547
          );
548

    
549
          //add the base layers
550

    
551
          addLayers(baseLayers);
552
          map.setBaseLayer(defaultBaseLayer);
553

    
554
          // calculate the bounds to zoom to
555
          zoomToBounds = calculateZoomToBounds(opts.boundingBox ? opts.boundingBox : defaultBaseLayerBoundingBox);
556
          // zoomToBounds = cropBoundsToAspectRatio(zoomToBounds, map.getSize().w / map.getSize().h);
557
          console.log("baselayer zoomToBounds: " + zoomToBounds);
558

    
559
        };
560

    
561
        var addLayers = function(layers){
562

    
563
          layers.forEach(function(layer){
564
            // layer.setVisibility(false);
565
          });
566

    
567
          map.addLayers(layers);
568
        };
569

    
570
        /**
571
         * add a distribution or occurrence layer
572
         *
573
         * @param mapResponseObj
574
         *   The reponse object returned by the edit map service
575
         * @param dataType
576
         *   either "AREA" or "POINT"
577
         */
578
        var createDataLayer = function(mapResponseObj, dataType){
579

    
580
          console.log("creating data layer of type " + dataType);
581

    
582
          dataLayerOptions = makeWMSLayerOptions();
583
          dataLayerOptions.displayOutsideMaxExtent = true; // move into makeWMSLayerOptions?
584

    
585
          var layers = [];
586
          // add additional layers, get them from the mapResponseObj
587
          if(mapResponseObj !== undefined){
588
            if(dataType === "POINT" && mapResponseObj.points_sld !== undefined){
589
              var pointLayer;
590
              // it is a response for an point map
591
              var geoserverUri;
592
              if(mapResponseObj.geoserver) {
593
                  geoserverUri = mapResponseObj.geoserver;
594
              } else {
595
                  // it is an old service which is not providing the corresponding geoserver URI, so we guess it
596
                  geoserverUri = mapserverBaseUrl + "/geoserver/wms";
597
              }
598

    
599
              //TODO points_sld should be renamed to sld in response + fill path to sld should be given
600
              pointLayer = new OpenLayers.Layer.WMS(
601
                'points',
602
                geoserverUri,
603
                {
604
                    layers: 'topp:rest_points',
605
                    transparent:"true",
606
                    format:"image/png"
607
                },
608
                dataLayerOptions
609
              );
610

    
611
              var sld = mapResponseObj.points_sld;
612
              if(sld.indexOf("http://") !== 0){
613
                  // it is an old servive which is not providing the full sdl URI, so we guess it
614
                  //  http://edit.africamuseum.be/synthesys/www/v1/sld/
615
                  //  http://edit.br.fgov.be/synthesys/www/v1/sld/
616
                  sld =  mapserverBaseUrl + "/synthesys/www/v1/sld/" + sld;
617
              }
618
              pointLayer.params.SLD = sld;
619

    
620
              layers.push(pointLayer);
621
            } else {
622
              // it is a response from for a distribution map
623
              console.log("start with adding distribution layers :");
624
              for ( var i in mapResponseObj.layers) {
625
                var layerData = mapResponseObj.layers[i];
626

    
627
                console.log(" " + i +" -> " + layerData.tdwg);
628
                var layer = new OpenLayers.Layer.WMS(
629
                  layerData.tdwg,
630
                  mapResponseObj.geoserver + "/wms",
631
                  {
632
                      layers: layerByNameMap[layerData.tdwg],
633
                      transparent:"true",
634
                      format:"image/png"
635
                  },
636
                  dataLayerOptions
637
                  );
638
                layer.params.SLD = layerData.sld;
639
                layer.setOpacity(opts.distributionOpacity);
640

    
641
                layers.push(layer);
642
              }
643
            }
644

    
645
            if(layers.length > 0) {
646
              // calculate zoomBounds using the first layer
647
              if(mapResponseObj.bbox !== undefined){
648
                // mapResponseObj.bbox are bounds for the projection of the specific layer
649
                var newBounds =  OpenLayers.Bounds.fromString( mapResponseObj.bbox );
650
                newBounds.transform(layers[0].projection, map.getProjectionObject());
651
                if(dataBounds !== null){
652
                  dataBounds.extend(newBounds);
653
                } else if(newBounds !== undefined){
654
                  dataBounds = newBounds;
655
                }
656

    
657
                zoomToBounds = dataBounds;
658
                console.log("data layer zoomToBounds: " + zoomToBounds);
659
                zoomToClosestLevel = false;
660
              }
661
            }
662

    
663

    
664

    
665
            if(legendImgSrc != null && opts.legendPosition !== undefined && mapResponseObj.legend !== undefined){
666
                var legendSrcUrl = mapResponseObj.geoserver + legendImgSrc + mapResponseObj.legend;
667
                addLegendAsElement(legendSrcUrl);
668
                //addLegendAsLayer(legendSrcUrl, map);
669
            }
670

    
671
            return layers;
672
          }
673

    
674
        };
675

    
676
        /**
677
         *
678
         */
679
        var addLegendAsElement= function(legendSrcUrl){
680

    
681
            var legendElement = jQuery('<div class="openlayers_legend"></div>');
682
            var legendImage = jQuery('<img src="' + legendSrcUrl + '"/>');
683
            legendElement
684
                .css('opacity', opts.legendOpacity)
685
                .css('position', 'relative')
686
                .css('z-index', '1002')
687
                .css('top', -mapElement.height());
688
            legendImage.load(function () {
689
                jQuery(this).parent()
690
                    .css('left', getWidth() - jQuery(this).width())
691
                    .width(jQuery(this).width());
692
                // reset height to original value
693
                adjustHeight();
694
            });
695
            legendElement.html(legendImage);
696
            mapElement.after(legendElement);
697
        };
698

    
699
         var adjustLegendAsElementPosition = function (){
700
           var legendContainer = mapContainerElement.children('.openlayers_legend');
701
           var legendImage = legendContainer.children('img');
702
           legendContainer.css('top', -mapElement.height())
703
             .css('left', getWidth() - legendImage.width());
704
         };
705

    
706

    
707
        var addLegendAsLayer= function(legendSrcUrl, map){
708
            var w, h;
709

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

    
714
                w = mapElement.next('.openlayers_legend').find('img').width();
715
                h = mapElement.next('.openlayers_legend').find('img').height();
716
                mapElement.next('.openlayers_legend').remove();
717

    
718
//              createLegendLayer();
719
//              // 2. create the Legend Layer
720
                //TODO createLegendLayer as inner function seems like an error
721
//              var createLegendLayer = function(){
722
                //
723
                //
724
//              var legendLayerOptions={
725
//              maxResolution: '.$maxRes.',
726
//              maxExtent: new OpenLayers.Bounds(0, 0, w, h)
727
//              };
728
                //
729
//              var legendLayer = new OpenLayers.Layer.Image(
730
//              'Legend',
731
//              legendSrcUrl,
732
//              new OpenLayers.Bounds(0, 0, w, h),
733
//              new OpenLayers.Size(w, h),
734
//              imageLayerOptions);
735
//              };
736
            });
737

    
738

    
739
        };
740

    
741
        /**
742
         * merge 2 Url query strings
743
         */
744
        var mergeQueryStrings = function(queryStr1, queryStr2){
745
            if(queryStr1.charAt(queryStr1.length - 1) != '&'){
746
                queryStr1 += '&';
747
            }
748
            if(queryStr2.charAt(0) == '&'){
749
                return queryStr1 + queryStr2.substr(1);
750
            } else {
751
                return queryStr1 + queryStr2;
752
            }
753

    
754
        };
755

    
756
        /**
757
         *
758
         */
759
        var createBaseLayers = function( baseLayerNames, defaultBaseLayerName, customWMSBaseLayerData){
760

    
761
            for(var i = 0; i <  baseLayerNames.length; i++) {
762
                // create the layer
763
                if (baseLayerNames[i] === "custom_wms_base_layer_1"){
764
                    wmsBaseLayer =createWMSLayer(
765
                            customWMSBaseLayerData.name,
766
                            customWMSBaseLayerData.url,
767
                            customWMSBaseLayerData.params,
768
                            customWMSBaseLayerData.projection,
769
                            customWMSBaseLayerData.proj4js_def,
770
                            customWMSBaseLayerData.units,
771
                            customWMSBaseLayerData.max_extent,
772
                            customWMSBaseLayerData.untiled
773
                    );
774
                  wmsBaseLayer.setIsBaseLayer(true);
775
                  baseLayers[i] = wmsBaseLayer;
776
                } else {
777
                    baseLayers[i] = window.CdmOpenLayers.getLayerByName(baseLayerNames[i]);
778
                }
779
                // set default baselayer
780
                if(baseLayerNames[i] === defaultBaseLayerName){
781
                    defaultBaseLayer = baseLayers[i];
782
                }
783

    
784
            }
785
        };
786

    
787
        /**
788
         * returns the intersection of the bounds b1 and b2.
789
         * The b1 and b2 do not intersect b1 will be returned.
790
         *
791
         * @param OpenLayers.Bounds b1
792
         * @param OpenLayers.Bounds b2
793
         *
794
         * @return the bounds of the intersection between both rectangles
795
         */
796
        var intersectionOfBounds = function (b1, b2){
797

    
798
            if(b1.intersectsBounds(b2)){
799

    
800
                var left = Math.max(b1.left, b2.left);
801
                var bottom = Math.max(b1.bottom, b2.bottom);
802
                var right = Math.min(b1.right, b2.right);
803
                var top = Math.min(b1.top, b2.top);
804

    
805
                return new OpenLayers.Bounds(left, bottom, right, top);
806

    
807
            } else {
808
                return b1;
809
            }
810
        };
811

    
812
        /**
813
         *
814
         * @param b OpenLayers.Bounds to crop
815
         * @param aspectRatio as fraction of width/height as float value
816
         *
817
         * @return the bounds cropped to the given aspectRatio
818
         */
819
        var cropBoundsToAspectRatio = function (b, aspectRatio){
820

    
821
            var cropedB = b.clone();
822

    
823
            if(aspectRatio === 1){
824
                return cropedB;
825
            }
826

    
827
            /*
828
             * LonLat:
829
             *   lon {Float} The x-axis coordinate in map units
830
             *   lat {Float} The y-axis coordinate in map units
831
             */
832
            var center = cropedB.getCenterLonLat();
833
            var dist;
834
            if(aspectRatio < 1){
835
                dist = (b.getHeight() / 2) * aspectRatio;
836
                cropedB.top = center.lat + dist;
837
                cropedB.cropedBottom = center.lat - dist;
838
            } else if(aspectRatio > 1){
839
                dist = (b.getWidth() / 2) / aspectRatio;
840
                cropedB.left = center.lon - dist;
841
                cropedB.right = center.lon + dist;
842
            }
843
            return cropedB;
844
        };
845

    
846
        /**
847
         * returns the version number contained in the version string:
848
         *   v1.1 --> 1.1
849
         *   v1.2_dev --> 1.2
850
         */
851
        var mapServerVersionNumber = function() {
852
            var pattern = /v([\d\.]+).*$/;
853
            var result;
854
            if (result = mapserverVersion.match(pattern) !== null) {
855
                return result[0];
856
            } else {
857
                return null;
858
            }
859
        };
860

    
861

    
862

    
863
      /**
864
       * returns the zoom to bounds.
865
       *
866
       * @param bboxString
867
       *     a string representation of the bounds in degree for epsg_4326
868
       *
869
       * @return the bboxstring projected onto the layer and intersected with the maximum extent of the layer
870
       */
871
      var calculateZoomToBounds = function(bboxString){
872
        var zoomToBounds;
873
        if(bboxString) {
874
          zoomToBounds = OpenLayers.Bounds.fromString(bboxString);
875
          if(referenceProjection().proj.projName){
876
            // SpericalMercator is not supporting the full extent -180,-90,180,90
877
            // crop if need to -179, -85, 179, 85
878
            if(zoomToBounds.left < -179){
879
              zoomToBounds.left =  -179;
880
            }
881
            if(zoomToBounds.bottom < -85){
882
              zoomToBounds.bottom =  -85;
883
            }
884
            if(zoomToBounds.right > 179){
885
              zoomToBounds.right =  179;
886
            }
887
            if(zoomToBounds.top > 85){
888
              zoomToBounds.top = 85;
889
            }
890
          }
891
          // transform bounding box given in degree values to the projection of the base layer
892
          zoomToBounds.transform(CdmOpenLayers.projections.epsg_4326, referenceProjection());
893
        } else if(referenceMaxExtent()) {
894
          zoomToBounds = referenceMaxExtent();
895
          // no need to transform since the bounds are obtained from the layer
896
        } else {
897
          // use the more narrow bbox of the SphericalMercator to avoid reprojection problems
898
          // SpericalMercator is not supporting the full extent!
899
          zoomToBounds = CdmOpenLayers.mapExtends.epsg_900913;
900
          // transform bounding box given in degree values to the projection of the base layer
901
          zoomToBounds.transform(CdmOpenLayers.projections.epsg_4326, referenceProjection());
902
        }
903

    
904
        zoomToBounds = intersectionOfBounds(referenceMaxExtent(), zoomToBounds);
905

    
906
        log("zoomBounds calculated: " + zoomToBounds.toString());
907

    
908
        return zoomToBounds;
909
      };
910

    
911
      var log = function(message, addTimeStamp){
912
        var timestamp = '';
913
        if(addTimeStamp === true){
914
          var time = new Date();
915
          timestamp = time.getSeconds() + '.' + time.getMilliseconds() + 's';
916
        }
917
        console.log(timestamp + message);
918
      };
919

    
920
      var makeWMSLayerOptions = function(projection, proj4js_def, maxExtent, units, untiled) {
921
        var wmsOptions = {
922
          isBaseLayer: false,
923
          displayInLayerSwitcher: true
924
        };
925

    
926
        if (projection) {
927
          if (proj4js_def) {
928
            // in case projection has been defined for the layer and if there is also
929
            // a Proj4js.defs, add it!
930
            Proj4js.defs[projection] = proj4js_def;
931
          }
932
          wmsOptions.projection = projection;
933
          if (maxExtent === null) {
934
            maxExtent = CdmOpenLayers.mapExtends.epsg_4326.clone();
935
            maxExtent.transform(CdmOpenLayers.projections.epsg_4326, projection);
936
          }
937
        } else {
938
          // use the projection and maxextent of the base layer
939
          maxExtent = referenceMaxExtent();
940
        }
941

    
942
        if (maxExtent) {
943
          wmsOptions.maxExtent = maxExtent;
944
        }
945

    
946
        if (units) {
947
          wmsOptions.units = units;
948
        }
949

    
950
        if (untiled) {
951
          wmsOptions.singleTile = true;
952
          wmsOptions.ratio = 1;
953
        }
954

    
955
        return wmsOptions;
956
      };
957

    
958
      /**
959
       * Creates a WMS Base layer
960
       * @param String name
961
       *     A name for the layer
962
       * @param String url
963
       *     Base url for the WMS (e.g.  http://wms.jpl.nasa.gov/wms.cgi)
964
       * @param Object params
965
       *     An object with key/value pairs representing the GetMap query string parameters and parameter values.
966
       * @param Object projection
967
       *    A OpenLayers.Projection object
968
       */
969
      var createWMSLayer= function(name, url, params, projection, proj4js_def, units, maxExtent, untiled){
970

    
971
        console.log("creating WMS Layer " + name);
972

    
973
        var wmsOptions = makeWMSLayerOptions(projection, proj4js_def, maxExtent, units, untiled);
974

    
975
        var wmsLayer = new OpenLayers.Layer.WMS(
976
            name,
977
            url,
978
            params,
979
            wmsOptions
980
          );
981

    
982
          if(wmsLayer === null){
983
            console.log("Error creating WMS Layer");
984
          }
985

    
986
          return  wmsLayer;
987
        };
988

    
989
        var layerLoadingControl = function() {
990

    
991
          var control = new OpenLayers.Control();
992

    
993
          OpenLayers.Util.extend(control, {
994

    
995
            LAYERS_LOADING: 0,
996

    
997
            updateState: function () {
998
              if(this.div != null){
999
                if (this.LAYERS_LOADING > 0) {
1000
                  this.div.style.display = "block";
1001
                } else {
1002
                  this.div.style.display = "none";
1003
                }
1004
              }
1005
            },
1006

    
1007
            updateSize: function () {
1008
              this.div.style.width = this.map.size.w + "px";
1009
              this.div.style.height = this.map.size.h  + "px";
1010
              this.div.style.textAlign = "center";
1011
              this.div.style.lineHeight = this.map.size.h  + "px";
1012
            },
1013

    
1014
            counterIncrease: function (layer) {
1015
              this.control.LAYERS_LOADING++;
1016
              log(' > loading start : ' + this.layer.name + ' ' + this.control.LAYERS_LOADING, true);
1017
              this.control.updateState();
1018
            },
1019

    
1020
            counterDecrease: function (layer) {
1021
              this.control.LAYERS_LOADING--;
1022
              log(' > loading end : ' + this.layer.name + ' ' + this.control.LAYERS_LOADING, true);
1023
              this.control.updateState();
1024
            },
1025

    
1026
            draw: function () {
1027

    
1028
              // call the default draw function to initialize this.div
1029
              OpenLayers.Control.prototype.draw.apply(this, arguments);
1030

    
1031
              this.map.events.register('updatesize', this, function(e){
1032
                  this.updateSize();
1033
                }
1034
              );
1035

    
1036
              var loadingIcon = document.createElement("i");
1037
              var fa_class = document.createAttribute("class");
1038
              // fa-circle-o-notch fa-spin
1039
              // fa-spinner fa-pulse
1040
              // fa-refresh
1041
              fa_class.value = "fa fa-refresh fa-spin fa-5x";
1042
              loadingIcon.attributes.setNamedItem(fa_class);
1043

    
1044
              this.updateSize();
1045

    
1046
              this.div.appendChild(loadingIcon);
1047

    
1048
              this.registerEvents();
1049

    
1050
              return this.div;
1051
            },
1052

    
1053
            registerEvents: function() {
1054

    
1055
              this.map.events.register('preaddlayer', this, function(e){
1056
                console.log(" > preaddlayer " + e.layer.name);
1057
                e.layer.events.register('loadstart', {control: this, layer: e.layer}, this.counterIncrease);
1058
                e.layer.events.register('loadend', {control: this, layer: e.layer}, this.counterDecrease);
1059
              });
1060
            }
1061

    
1062
          });
1063

    
1064
          return control;
1065
        }
1066

    
1067
    }; // end of CdmOpenLayers.Map
1068
})();
1069

    
1070

    
1071

    
1072

    
1073

    
1074

    
1075

    
1076

    
1077

    
(2-2/2)