Project

General

Profile

Download (15.7 KB) Statistics
| Branch: | Tag: | Revision:
1
function CdmOpenlayersMap(mapElement, mapserverBaseUrl, mapserverVersion, options){
2

    
3
  var mapServicePath = '/edit_wp5';
4

    
5
  var legendImgSrc = null;
6

    
7
  var map = null;
8

    
9
  var dataBounds = null;
10

    
11
  var baseLayers = [];
12
  var defaultBaseLayer;
13

    
14
  var defaultControls = [
15
           new OpenLayers.Control.PanZoom(),
16
           new OpenLayers.Control.Navigation({zoomWheelEnabled: false, handleRightClicks:true, zoomBoxKeyMask: OpenLayers.Handler.MOD_CTRL})
17
         ];
18
  /*
19
   * EPSG:4326 and EPSG:900913 extends
20
   */
21
  var mapExtend_4326 = new OpenLayers.Bounds(-180, -90, 180, 90);
22
  var mapExtend_900913 = new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34);
23

    
24
  var mapOptions={
25
      EPSG900913: {
26
        controls: defaultControls,
27
        maxExtent: mapExtend_900913,
28
        //maxResolution: (mapExtend_900913.getWidth() / options.displayWidth),
29
        maxResolution: (mapExtend_900913.getHeight() / (options.displayWidth / 2)),
30
        //maxResolution:156543.0339 * 20,
31
        units:'m',
32
        restrictedExtent: mapExtend_900913,
33
        projection: new OpenLayers.Projection("EPSG:900913")
34
      },
35
      EPSG4326: {
36
        controls: defaultControls,
37
        maxExtent: mapExtend_4326,
38
        maxResolution: (mapExtend_4326.getWidth() / options.displayWidth),
39
        units:'degrees',
40
        restrictedExtent: mapExtend_4326,
41
        projection: new OpenLayers.Projection("EPSG:4326")
42
      }
43
  };
44

    
45

    
46
  var dataProj = new OpenLayers.Projection("EPSG:4326");
47

    
48
  var dataLayerOptions = {
49
      maxExtent: mapExtend_900913,
50
      isBaseLayer: false,
51
      displayInLayerSwitcher: true
52
  };
53

    
54
  var layerByNameMap = {
55
      tdwg1: 'topp:tdwg_level_1',
56
      tdwg2: 'topp:tdwg_level_2',
57
      tdwg3: 'topp:tdwg_level_3',
58
      tdwg4: 'topp:tdwg_level_4'
59
  };
60

    
61
  /**
62
   *
63
   */
64
  this.init = function(){ // public function
65

    
66
    createLayers(options.baseLayerNames, options.defaultBaseLayerName);
67

    
68
     //HACK !!!!!!!!!!!!!!!!!!!!!!!!!!!!
69
    if(defaultBaseLayer.projection == mapOptions.EPSG900913.projection){
70
      options.minZoom = 1;
71
    }
72

    
73
    initOpenLayers();
74

    
75

    
76

    
77
    // -- Distribution Layer --
78
    var mapServiceRequest;
79
    var distributionQuery = mapElement.attr('distributionQuery');
80

    
81
    if(distributionQuery !== undefined){
82
      if(typeof legendPosition == 'number'){
83
        distributionQuery = mergeQueryStrings(distributionQuery, 'legend=1&mlp=' + options.legendPosition);
84
      }
85

    
86
      distributionQuery = mergeQueryStrings(distributionQuery, 'callback=?');
87
      var legendFormatQuery = mapElement.attr('legendFormatQuery');
88
      if(legendFormatQuery !== undefined){
89
        legendImgSrc = mergeQueryStrings('/GetLegendGraphic?SERVICE=WMS&VERSION=1.1.1', legendFormatQuery);
90
      }
91

    
92
      mapServiceRequest = mapserverBaseUrl + mapServicePath + '/' + mapserverVersion + '/areas.php?' + distributionQuery;
93

    
94
      jQuery.ajax({
95
          url: mapServiceRequest,
96
          dataType: "jsonp",
97
          success: function(data){
98
            addDataLayer(data);
99
          }
100
        });
101
    }
102

    
103
    // -- Occurrence Layer --
104
    var occurrenceQuery = mapElement.attr('occurrenceQuery');
105
    if(occurrenceQuery !== undefined){
106
//      if(typeof legendPosition == 'number'){
107
//        occurrenceQuery = mergeQueryStrings(distributionQuery, 'legend=1&mlp=' + options.legendPosition);
108
//      }
109

    
110
      occurrenceQuery = mergeQueryStrings(occurrenceQuery, 'callback=?');
111
//      var legendFormatQuery = mapElement.attr('legendFormatQuery');
112
//      if(legendFormatQuery !== undefined){
113
//        legendImgSrc = mergeQueryStrings('/GetLegendGraphic?SERVICE=WMS&VERSION=1.1.1', legendFormatQuery);
114
//      }
115

    
116
      mapServiceRequest = mapserverBaseUrl + mapServicePath + '/' + mapserverVersion + '/points.php?' + occurrenceQuery;
117

    
118
      jQuery.ajax({
119
          url: mapServiceRequest,
120
          dataType: "jsonp",
121
          success: function(data){
122
            addDataLayer(data);
123
          }
124
        });
125
    }
126

    
127

    
128
  };
129

    
130
  /**
131
   * Initialize the Openlayers viewer with the base layer
132
   */
133
  var initOpenLayers = function(){
134

    
135
    // instantiate the openlayers viewer
136
    if(defaultBaseLayer.projection == mapOptions.EPSG900913.projection){
137
      map = new OpenLayers.Map('openlayers_map', mapOptions.EPSG900913);
138
    } else {
139
      map = new OpenLayers.Map('openlayers_map', mapOptions.EPSG4326);
140
    }
141

    
142
    //add the base layers
143
    map.addLayers(baseLayers);
144
    map.setBaseLayer(defaultBaseLayer);
145

    
146
    if(options.showLayerSwitcher === true){
147
      map.addControl(new OpenLayers.Control.LayerSwitcher({'ascending':false}));
148
    }
149

    
150
    // zoom to the required area
151
    var boundsStr = (typeof options.boundingBox == 'string' && options.boundingBox.length > 6 ? options.boundingBox : '-180, -90, 180, 90');
152
    var zoomToBounds = OpenLayers.Bounds.fromString( boundsStr );
153
    map.zoomToExtent(zoomToBounds.transform(dataProj, map.getProjectionObject()), false);
154
    if(map.getZoom() > options.maxZoom){
155
      map.zoomTo(options.maxZoom);
156
    } else if(map.getZoom() < options.minZoom){
157
      map.zoomTo(options.minZoom);
158
    }
159

    
160
    // adjust height of openlayers container div
161
    jQuery('#openlayers').css('height', jQuery('#openlayers #openlayers_map').height());
162

    
163
  };
164

    
165
  /**
166
   * add a distribution layer
167
   */
168
  var addDataLayer = function(mapResponseObj){
169

    
170
    var layer;
171
    // add additional layers, get them from the mapResponseObj
172
    if(mapResponseObj !== undefined){
173
      if(mapResponseObj.points_sld !== undefined){
174
        // it is a response from the points.php
175

    
176
    	var geoserverUri;
177
    	if(mapResponseObj.geoserver) {
178
    		geoserverUri = mapResponseObj.geoserver;
179
    	} else {
180
    		// it is an old servive which is not providing the corresponding geoserver URI, so we guess it
181
    		geoserverUri = mapserverBaseUrl + "/geoserver/wms";
182
    	}
183

    
184
    	//TODO points_sld should be renamed to sld in response + fill path to sld should be given
185
        layer = new OpenLayers.Layer.WMS.Untiled(
186
            'points',
187
            geoserverUri,
188
            {layers: 'topp:rest_points' ,transparent:"true", format:"image/png"},
189
            dataLayerOptions );
190

    
191
        var sld = mapResponseObj.points_sld;
192
        if(sld.indexOf("http://") !== 0){
193
          // it is an old servive which is not providing the full sdl URI, so we guess it
194
          //  http://edit.africamuseum.be/synthesys/www/v1/sld/
195
          //  http://edit.br.fgov.be/synthesys/www/v1/sld/
196
          sld =  mapserverBaseUrl + "/synthesys/www/v1/sld/" + sld;
197

    
198
        }
199

    
200
        layer.params.SLD = sld;
201
        map.addLayers([layer]);
202

    
203
      } else {
204
        // it is a response from the areas.php
205
        for ( var i in mapResponseObj.layers) {
206
        var layerData = mapResponseObj.layers[i];
207

    
208
          layer = new OpenLayers.Layer.WMS.Untiled(
209
              layerData.tdwg,
210
              mapResponseObj.geoserver + "/wms",
211
              {layers: layerByNameMap[layerData.tdwg] ,transparent:"true", format:"image/png"},
212
              dataLayerOptions );
213
          layer.params.SLD = layerData.sld;
214
          layer.setOpacity(options.distributionOpacity);
215
          map.addLayers([layer]);
216

    
217
        }
218

    
219
      }
220

    
221
      // zoom to the required area
222
      if(mapResponseObj.bbox !== undefined){
223
        var newBounds =  OpenLayers.Bounds.fromString( mapResponseObj.bbox );
224
        if(dataBounds !== null){
225
          dataBounds.extend(newBounds);
226
        } else if(newBounds !== undefined){
227
          dataBounds = newBounds;
228
        }
229
        map.zoomToExtent(dataBounds.transform(dataProj, map.getProjectionObject()), false);
230
        if(map.getZoom() > options.maxZoom){
231
          map.zoomTo(options.maxZoom);
232
        } else if(map.getZoom() < options.minZoom){
233
          map.zoomTo(options.minZoom);
234
        }
235
      }
236

    
237

    
238
      if(options.legendPosition !== undefined && mapResponseObj.legend !== undefined){
239
        var legendSrcUrl = mapResponseObj.geoserver + legendImgSrc + mapResponseObj.legend;
240
        addLegendAsElement(legendSrcUrl);
241
        //addLegendAsLayer(legendSrcUrl, map);
242
      }
243
    }
244

    
245
  };
246

    
247
  /**
248
   *
249
   */
250
  var addLegendAsElement= function(legendSrcUrl){
251

    
252
    mapElement.after('<div class="openlayers_legend"><img src="' + legendSrcUrl + '"></div>');
253
    mapElement.next('.openlayers_legend').css('opacity', options.legendOpacity).find('img').load(function () {
254
      jQuery(this).parent()
255
        .css('position', 'relative')
256
        .css('z-index', '1002')
257
        .css('top', -mapElement.height())
258
        .css('left', mapElement.width()- jQuery(this).width())
259
        .width(jQuery(this).width());
260
    });
261
  };
262

    
263

    
264
  var addLegendAsLayer= function(legendSrcUrl, map){
265
    var w, h;
266

    
267
    // 1. download imge to find height and width
268
    mapElement.after('<div class="openlayers_legend"><img src="' + legendSrcUrl + '"></div>');
269
    mapElement.next('.openlayers_legend').css('display', 'none').css('opacity', options.legendOpacity).find('img').load(function () {
270

    
271
      w = mapElement.next('.openlayers_legend').find('img').width();
272
      h = mapElement.next('.openlayers_legend').find('img').height();
273
      mapElement.next('.openlayers_legend').remove();
274

    
275
//      createLegendLayer();
276
//      // 2. create the Legend Layer
277
      //TODO createLegendLayer as inner fiinction seems like an error
278
//      var createLegendLayer = function(){
279
//
280
//
281
//        var legendLayerOptions={
282
//            maxResolution: '.$maxRes.',
283
//            maxExtent: new OpenLayers.Bounds(0, 0, w, h)
284
//        };
285
//
286
//        var legendLayer = new OpenLayers.Layer.Image(
287
//            'Legend',
288
//            legendSrcUrl,
289
//            new OpenLayers.Bounds(0, 0, w, h),
290
//            new OpenLayers.Size(w, h),
291
//            imageLayerOptions);
292
//      };
293
    });
294

    
295

    
296
  };
297

    
298
  /**
299
   * merge 2 Url query strings
300
   */
301
   var mergeQueryStrings = function(queryStr1, queryStr2){
302
    if(queryStr1.charAt(queryStr1.length - 1) != '&'){
303
      queryStr1 += '&';
304
    }
305
    if(queryStr2.charAt(0) == '&'){
306
      return queryStr1 + queryStr2.substr(1);
307
    } else {
308
      return queryStr1 + queryStr2;
309
    }
310

    
311
   };
312

    
313
   /**
314
    *
315
    */
316
   var createLayers = function( baseLayerNames, defaultBaseLayerName){
317
     for(var i = 0; i <  baseLayerNames.length; i++) {
318
       baseLayers[i] = getLayersByName(baseLayerNames[i]);
319
       if(baseLayerNames[i] == defaultBaseLayerName){
320
         defaultBaseLayer = baseLayers[i];
321
       }
322
     }
323
   };
324

    
325
   /**
326
    * returns the version number contained in the version string:
327
    *   v1.1 --> 1.1
328
    *   v1.2_dev --> 1.2
329
    */
330
   var mapServerVersionNumber = function() {
331
	   var pattern = /v([\d\.]+).*$/;
332
	   var result;
333
	   if (result = mapserverVersion.match(pattern) !== null) {
334
		   return result[0];
335
	   } else {
336
		   return null;
337
	   }
338
   }
339

    
340
  /**
341
   *
342
   */
343
  var getLayersByName = function(layerName){
344

    
345
    var baseLayer = null;
346

    
347
    switch(layerName){
348

    
349
      case 'metacarta_vmap0':
350
        /**
351
         * NOTE: labs.metacarta.com is currently unavailable
352
         *
353
         * Available Projections:
354
         *     EPSG:900913
355
         *     EPSG:4326
356
         */
357
        baseLayer = new OpenLayers.Layer.WMS(
358
              "Metacarta Vmap0",
359
              "http://labs.metacarta.com/wms/vmap0",
360
              {layers: 'basic', format:"png"},
361
              {
362
              maxExtent: mapExtend_4326,
363
              isBaseLayer: true,
364
              displayInLayerSwitcher: true
365
            }
366
        );
367
      break;
368

    
369
      case 'osgeo_vmap0':
370
        /**
371
         * Available Projections:
372
         *     EPSG:4269
373
              EPSG:4326
374
              EPSG:900913
375
         */
376
        baseLayer = new OpenLayers.Layer.WMS(
377
              "Metacarta Vmap0",
378
              "http://vmap0.tiles.osgeo.org/wms/vmap0",
379
              {layers: 'basic', format:"png"},
380
              {
381
            maxExtent: mapExtend_900913,
382
            isBaseLayer: true,
383
            displayInLayerSwitcher: true
384
          }
385
        );
386
      break;
387

    
388
      case 'edit-etopo1':
389
        baseLayer = new OpenLayers.Layer.WMS(
390
              "ETOPO1 Global Relief Model",
391
              "http://edit.br.fgov.be:8080/geoserver/wms",
392
              {layers: 'topp:color_etopo1_ice_full', format:"image/png"},
393
              {
394
            maxExtent: mapExtend_900913,
395
            isBaseLayer: true,
396
            displayInLayerSwitcher: true
397
          }
398
        );
399
      break;
400

    
401
      case 'edit-vmap0_world_basic':
402
        baseLayer = new OpenLayers.Layer.WMS(
403
              "EDIT Vmap0",
404
              "http://edit.br.fgov.be:8080/geoserver/wms",
405
              {layers: 'vmap0_world_basic', format:"image/png"},
406
              {
407
            maxExtent: mapExtend_900913,
408
            isBaseLayer: true,
409
            displayInLayerSwitcher: true
410
          }
411
        );
412
      break;
413

    
414
      // create Google Mercator layers
415
      case 'gmap':
416
        baseLayer = new OpenLayers.Layer.Google(
417
                  "Google Streets",
418
                  {'sphericalMercator': true}
419
              );
420
      break;
421

    
422

    
423
      case 'gsat':
424
        baseLayer = new OpenLayers.Layer.Google(
425
                  "Google Satellite",
426
                  {type: G_SATELLITE_MAP, 'sphericalMercator': true, numZoomLevels: 22}
427
              );
428
      break;
429

    
430
      case 'ghyb':
431
        baseLayer = new OpenLayers.Layer.Google(
432
                  "Google Hybrid",
433
                  {type: G_HYBRID_MAP, 'sphericalMercator': true}
434
              );
435
      break;
436

    
437
      case 'veroad':
438
        baseLayer = new OpenLayers.Layer.VirtualEarth(
439
                  "Virtual Earth Roads",
440
                  {'type': VEMapStyle.Road, 'sphericalMercator': true}
441
              );
442
      break;
443

    
444
      case 'veaer':
445
        baseLayer = new OpenLayers.Layer.VirtualEarth(
446
                  "Virtual Earth Aerial",
447
                  {'type': VEMapStyle.Aerial, 'sphericalMercator': true}
448
              );
449
      break;
450

    
451
      case 'vehyb':
452
        baseLayer = new OpenLayers.Layer.VirtualEarth(
453
                  "Virtual Earth Hybrid",
454
                  {'type': VEMapStyle.Hybrid, 'sphericalMercator': true}
455
              );
456
      break;
457

    
458
      case 'yahoo':
459
        baseLayer = new OpenLayers.Layer.Yahoo(
460
                  "Yahoo Street",
461
                  {'sphericalMercator': true}
462
              );
463
      break;
464

    
465
      case 'yahoosat':
466
        baseLayer = new OpenLayers.Layer.Yahoo(
467
                  "Yahoo Satellite",
468
                  {'type': YAHOO_MAP_SAT, 'sphericalMercator': true}
469
              );
470
      break;
471

    
472
      case 'yahoohyb':
473
         rebaseLayer = new OpenLayers.Layer.Yahoo(
474
                  "Yahoo Hybrid",
475
                  {'type': YAHOO_MAP_HYB, 'sphericalMercator': true}
476
              );
477
      break;
478

    
479
      case 'mapnik':
480
        baseLayer = new OpenLayers.Layer.OSM();
481
      break;
482

    
483
      case 'oam':
484
        baseLayer = new OpenLayers.Layer.XYZ(
485
                "OpenAerialMap",
486
                "http://tile.openaerialmap.org/tiles/1.0.0/openaerialmap-900913/${z}/${x}/${y}.png",
487
                {
488
                    sphericalMercator: true
489
                }
490
            );
491
      break;
492

    
493
      case 'osmarender':
494
        baseLayer = new OpenLayers.Layer.OSM(
495
                "OpenStreetMap (Tiles@Home)",
496
                "http://tah.openstreetmap.org/Tiles/tile/${z}/${x}/${y}.png"
497
               );
498
      break;
499

    
500
    }
501

    
502
    return baseLayer;
503
  };
504

    
505
}
506

    
507

    
508
(function($){
509

    
510
  $.fn.cdm_openlayers_map = function(mapserverBaseUrl, mapserverVersion, options) {
511

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

    
514
    return this.each(function(){
515

    
516
      var openlayers_map = new CdmOpenlayersMap($(this), mapserverBaseUrl, mapserverVersion, opts);
517
      openlayers_map.init();
518

    
519
     }); // END each
520

    
521
  }; // END cdm_openlayers_map
522

    
523
})(jQuery);
524

    
525
(function($){
526
$.fn.cdm_openlayers_map.defaults = {  // set up default options
527
    legendPosition:  null,      // 1,2,3,4,5,6 = display a legend in the corner specified by the number
528
    displayWidth: 400,
529
    distributionOpacity: 0.75,
530
    legendOpacity: 0.75,
531
    boundingBox: null,
532
    showLayerSwitcher: false,
533
    baseLayerNames: ["osgeo_vmap0"],
534
    defaultBaseLayerName: 'osgeo_vmap0',
535
    maxZoom: 4,
536
    minZoom: 0
537
};
538
})(jQuery);
539

    
(12-12/13)