Project

General

Profile

Download (19.5 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/**
3
 * @file
4
 * Functions for dealing maps
5
 *
6
 * @copyright
7
 *   (C) 2007-2013 EDIT
8
 *   European Distributed Institute of Taxonomy
9
 *   http://www.e-taxonomy.eu
10
 *
11
 *   The contents of this module are subject to the Mozilla
12
 *   Public License Version 1.1.
13
 * @see http://www.mozilla.org/MPL/MPL-1.1.html
14
 *
15
 * @author
16
 *   - Andreas Kohlbecker <a.kohlbecker@BGBM.org>
17
 */
18

    
19
/**
20
 * Compose an render array for distribution and occurrence
21
 * maps.
22
 *
23
 * The map can either be a plain image or a dynamic open layers map
24
 * depending on the settings
25
 *
26
 * compose_hook() implementation
27
 *
28
 * @param $map_id
29
 * @param string $occurrence_query
30
 * @param string $distribution_query
31
 * @param string $legend_format_query
32
 * @param array $event_listeners
33
 *   An associative array of with OpenLayers.Map event names as key and corresponding js callbacks.
34
 *   In addition to the event names '#execute' as key is also allowed.
35
 *   Valid events are:
36
 *      - move
37
 *      - moveend
38
 *      - zoomend
39
 *      - changelayer
40
 *      - changebaselayer
41
 *      - #execute:
42
 *            force execution of the given callback after registration of the event handlers
43
 *   see http://dev.openlayers.org/apidocs/files/OpenLayers/Map-js.html#OpenLayers.Map.events for more
44
 * @param bool $resizable
45
 *    only possible for openlayers_map
46
 * @param string $force_map_type
47
 *   Can be used to override the map_type setting stored in the settings variable CDM_MAP_DISTRIBUTION
48
 *   - 1: openlayers_map
49
 *   - 0: image_map
50
 * @return array A drupal render array
51
 * A drupal render array
52
 * @ingroup compose
53
 */
54
function compose_map($map_id, $occurrence_query = NULL, $distribution_query = NULL, $legend_format_query = NULL, array $event_listeners = array(), $resizable = false, $force_map_type = NULL) {
55

    
56
    $map_settings = get_array_variable_merged(CDM_MAP_DISTRIBUTION, CDM_MAP_DISTRIBUTION_DEFAULT);
57

    
58
    if($force_map_type === NULL){
59
      $force_map_type = $map_settings['map_type'];
60
    }
61

    
62
    if ($force_map_type == 1) {
63
      _add_jquery_ui();
64
      $map_html = cdm_map_openlayers(
65
        $map_id,
66
        $occurrence_query,
67
        $distribution_query,
68
        $legend_format_query,
69
        $map_settings['caption'],
70
        $event_listeners,
71
        $resizable
72
      );
73
    }
74
     else {
75
      $map_height = round($map_settings['image_map']['width'] / (float)$map_settings['aspect_ratio']);
76
      $map_html = cdm_map_plain_image(
77
        $map_settings['image_map']['width'],
78
        $map_height,
79
        $occurrence_query,
80
        $distribution_query,
81
        $legend_format_query,
82
        $map_settings['caption']
83
      );
84
     }
85
  return markup_to_render_array($map_html);
86
}
87

    
88
/**
89
 * Adds the javascript for a openlayers map to the page as well as all javascript libs.
90
 *
91
 *
92
 * @param $map_id
93
 * @param $map_settings
94
 *   The map settings array as retrieved by e.g. get_array_variable_merged(CDM_MAP_DISTRIBUTION, CDM_MAP_DISTRIBUTION_DEFAULT);
95
 * @param array $event_listeners
96
 *   An associative array of with OpenLayers.Map event names as key and corresponding js callbacks.
97
 *   In addition to the event names '#execute' as key is also allowed.
98
 *   Valid events are:
99
 *      - move
100
 *      - moveend
101
 *      - zoomend
102
 *      - changelayer
103
 *      - changebaselayer
104
 *      - #execute:
105
 *            force execution of the given callback after registration of the event handlers
106
 *   see http://dev.openlayers.org/apidocs/files/OpenLayers/Map-js.html#OpenLayers.Map.events for more
107
 * @param bool $resizable
108
 *   The map is made resizable when set to true
109
 */
110
function _add_js_openlayers_map($map_id, $map_settings, array $event_listeners = array(), $resizable = false) {
111

    
112
  font_awesome_icon_markup(); // no icon specified, only used to add the font and styles
113

    
114
  _add_js_openlayers();
115

    
116
  $edit_map_service = get_edit_map_service_settings();
117

    
118
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/map/openlayers_map.js',
119
    array(
120
      'type' => 'file',
121
      'group' => JS_DEFAULT, //  module-layer JavaScript.
122
      'weight' => 0,
123
      'cache' => TRUE,
124
      'preprocess' => FALSE
125
  ));
126
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/map/openlayers_layers.js',
127
    array(
128
      'type' => 'file',
129
      'group' => JS_DEFAULT,
130
       'weight' => 1, // after openlayers_map.js
131
      'cache' => TRUE,
132
      'preprocess' => FALSE
133
  ));
134

    
135
  $cdm_openlayers_options = array(
136
      'legendPosition'  => '3',
137
      'boundingBox' => $map_settings['bbox'],
138
      'maxZoom' => $map_settings['maxZoom'],
139
      'aspectRatio' => $map_settings['aspect_ratio'],
140
      'distributionOpacity' => $map_settings['distribution_opacity'],
141
      'legendOpacity' => $map_settings['legend']['opacity'],
142
      'showLayerSwitcher' => $map_settings['openlayers']['show_layer_switcher']  ==  1,
143
      'displayOutsideMaxExtent' => $map_settings['openlayers']['display_outside_max_extent'] == 1,
144
      'resizable' => $resizable
145
//       'imgPath' => drupal_get_path('module', 'cdm_dataportal') . '/js/map/OpenLayers-2.13.1/img/' // path to the control icons
146
      // if no baseLayerNames or defaultBaseLayerName are not defined
147
      // the defaults in cdm_openlayers.js will be used
148
  );
149

    
150
  // --- setting the base layer options
151
  if (is_array($map_settings['openlayers']['base_layers']) && count($map_settings['openlayers']['base_layers']) > 0) {
152

    
153
    $base_layer_names = $map_settings['openlayers']['base_layers'];
154

    
155
    foreach($base_layer_names as $name){
156
      if(str_beginsWith($name, 'g')){
157
        if( isset($map_settings['openlayers']['google_maps_api_key']) && strlen($map_settings['openlayers']['google_maps_api_key']) == 39) {
158
          // google layer detected
159
          //drupal_add_js("https://maps.googleapis.com/maps/api/js?key=" . $map_settings['openlayers']['google_maps_api_key'],
160
          //drupal_add_js("https://maps.google.com/maps/api/js?callback=initMap&key=" . $map_settings['openlayers']['google_maps_api_key'],
161
          drupal_add_js("http://maps.google.com/maps/api/js?v=3&key=" . $map_settings['openlayers']['google_maps_api_key'],
162
          array(
163
            'type' => 'external',
164
            'defer' => true
165
            ));
166

    
167
          //drupal_add_js("http://maps.google.com/maps/api/js?callback=initMap&key=" . $map_settings['openlayers']['google_maps_api_key'], 'external');
168
        } else {
169
          drupal_set_message('A Google Maps layer is configured but the API key is either missing or invalid. 
170
          Please set your Google Maps API key in the '  . l('Geo & Map Settings', 'admin/config/cdm_dataportal/settings/geo') .'.', 'warning');
171
        }
172
      }
173
    }
174

    
175
    // get default layer and remove the 'PREFERRED' from the list to avoid duplicate layers
176
    $preferred_baseLayer = $base_layer_names['PREFERRED'];
177
    unset($base_layer_names['PREFERRED']);
178

    
179
    $cdm_openlayers_options['baseLayerNames'] = array_values($base_layer_names);
180

    
181
    if($preferred_baseLayer){
182
      $cdm_openlayers_options['defaultBaseLayerName'] = $preferred_baseLayer;
183
      if(array_search($preferred_baseLayer, $cdm_openlayers_options['baseLayerNames']) === false){
184
        // the default layer must also  be in the list of base layers
185
        $cdm_openlayers_options['baseLayerNames'][] = $preferred_baseLayer;
186
      }
187
    }
188

    
189
  }
190

    
191
  // --- custom wms base layer
192
  $map_settings['openlayers']['custom_wms_base_layer']['params'] = json_decode($map_settings['openlayers']['custom_wms_base_layer']['params']);
193
  $cdm_openlayers_options['customWMSBaseLayerData'] = $map_settings['openlayers']['custom_wms_base_layer'];
194

    
195

    
196
  // --- wms_overlay_layer
197
  if(isset($map_settings['openlayers']['wms_overlay_layer']) && $map_settings['openlayers']['wms_overlay_layer']['is_enabled']) {
198
    $map_settings['openlayers']['wms_overlay_layer']['params'] = json_decode($map_settings['openlayers']['wms_overlay_layer']['params']);
199
    $cdm_openlayers_options['wmsOverlayLayerData'] = $map_settings['openlayers']['wms_overlay_layer'];
200
  }
201

    
202
  // --- eventhandlers
203
  $event_listeners_js = '';
204
  $execute_handler = '';
205
  foreach($event_listeners as $event=>$js_callback){
206
    if($event == '#execute'){
207
      $execute_handler = 'map_container.each(function(){' . $js_callback . '();});';
208
    } else {
209
      $event_listeners_js .= ($event_listeners_js ? ",\n": "\n") .'"' . $event . '": ' . $js_callback;
210
    }
211
  }
212

    
213
  $mapserver_base_uri = $edit_map_service['base_uri'];
214
  $is_https = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on';
215
  $http_protocol = $is_https ? 'https' : 'http';
216
  $mapserver_base_uri = preg_replace('/^https?:/', $http_protocol . ':', $mapserver_base_uri);
217

    
218
  // window.onload - is executed when the document and images etc is fully loaded
219
  // Query(document).ready - is executed much earlier, when the DOM is loaded
220
  drupal_add_js("
221
          jQuery(document).ready(function() {
222
                jQuery(window).load(function () {
223
                  var map_container = jQuery('#openlayers-map-" . $map_id . "').cdm_openlayers_map(
224
                   '" . $mapserver_base_uri . "',
225
                   '" . $edit_map_service['version'] . "',
226
                   " .  json_encode($cdm_openlayers_options) . "
227
                );
228
                map_container.each(function(){
229
                        this.cdmOpenlayersMap.registerEvents({" . "
230
                        " . $event_listeners_js . "
231
                        });
232
                });
233
                " . $execute_handler . "
234
        });
235
      });
236
    ", array('type' => 'inline'));
237

    
238
}
239

    
240

    
241
/**
242
 * Creates markup for an openlayers based dynamic map.
243
 *
244
 * @param string $bounding_box
245
 * @param string $occurrenceQuery
246
 * @param string $distributionQuery
247
 * @param string $legendFormatQuery
248
 * @param string $map_caption
249
 * @param array $event_listeners
250
 *   An associative array of with OpenLayers.Map event names as key and corresponding js callbacks.
251
 *   In addition to the event names '#execute' as key is also allowed.
252
 *   Valid events are:
253
 *      - move
254
 *      - moveend
255
 *      - zoomend
256
 *      - changelayer
257
 *      - changebaselayer
258
 *      - #execute:
259
 *            force execution of the given callback after registration of the event handlers
260
 *   see http://dev.openlayers.org/apidocs/files/OpenLayers/Map-js.html#OpenLayers.Map.events for more
261
 *
262
 * @return String
263
 *    The markup for the map
264
 */
265
function cdm_map_openlayers($map_id, $occurrenceQuery = FALSE, $distributionQuery = FALSE,
266
                            $legendFormatQuery = FALSE, $map_caption = FALSE, array $event_listeners = array(),
267
                            $resizable = false) {
268

    
269
  $map_settings = get_array_variable_merged(CDM_MAP_DISTRIBUTION, CDM_MAP_DISTRIBUTION_DEFAULT);
270

    
271
  if($map_id == NULL){
272
    $map_id = sha1($occurrenceQuery . $distributionQuery);
273
  }
274

    
275
  _add_js_openlayers_map($map_id, $map_settings, $event_listeners, $resizable);
276

    
277
  $out = '<div id=""openlayers-container-' . $map_id . '" class="openlayers-container openlayers_width ui-widget-content" style="width: 100%;">';
278
  $out .= '<div id="openlayers-map-' . $map_id . '" class="smallmap" style="width:100%; height:100%; margin: 10px;"';
279

    
280
  // Additional query parameters as set in the data portal admin section.
281
  $labels_on = $map_settings['show_labels'];
282

    
283
  // need to set the ms parameter to some value in order to satisfy the
284
  // map service even if this value should not be required:
285
  $width = 512;
286

    
287
  $openlayers_map_query_string = '&img=false&ms=' . $width
288
  . ($labels_on ? '&label=' . $labels_on : '');
289

    
290
  if ($occurrenceQuery) {
291
    // @todo Fix $occurrenceQuery.
292
    //     $occurrenceQuery .= '&bbox=-180,-90,180,90';
293
    $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0'; // TODO why are we using v:atbi,e_w_0 as layer ???
294
    // $occurrenceQuery .= '&l=v:e_w_0';
295
    // TODO add to cdm service?
296
    $occurrenceQuery .= '&legend=0';
297

    
298
    $out .= ' occurrenceQuery="' . $occurrenceQuery . '&' . $openlayers_map_query_string . '"';
299
  }
300

    
301
  if ($distributionQuery) {
302
    //HACK for testing (this must be done in js)
303
//     $distributionQuery .= "&layer=em_tiny_jan2003&dest_projection_epsg=7777777";
304
    $out .= ' distributionQuery="' . $distributionQuery . '&' . $openlayers_map_query_string . '"';
305
  }
306

    
307
  if ($legendFormatQuery) {
308
    $out .= ' legendFormatQuery="' . $legendFormatQuery . '"';
309
  }
310

    
311
  $out .= '></div></div>';
312

    
313
  // Showing map caption.
314
  if ($map_caption) {
315
    $out .= '<div class="distribution_map_caption">' . $map_caption . '</div>';
316
  }
317
  return $out;
318
}
319

    
320

    
321
/**
322
 * Composes the render array for a distribution map using the given distribution query string.
323
 *
324
 * The distribution map can either be a plain image or a dynamic open layers map
325
 * depending on the settings.
326
 *
327
 * compose_hook() implementation
328
 *
329
 * @param string $query_string
330
 *    An EDIT map services distribution query string
331
 *
332
 * @return array
333
 *    A drupal render array
334
 *
335
 * Similar compose function compose_map()
336
 *
337
 * @ingroup compose
338
 */
339
function compose_distribution_map($query_string) {
340

    
341
  $fontStyles = array(
342
      0 => "plane",
343
      1 => "italic",
344
  );
345

    
346
  if (!$query_string) {
347
    // The $query_string is empty if there are no distribution areas defined.
348
    return null;
349
  }
350

    
351
  /* ------ choose the display mode, either openlayers or static image ------ */
352

    
353
  $map_settings = get_array_variable_merged(CDM_MAP_DISTRIBUTION, CDM_MAP_DISTRIBUTION_DEFAULT);
354

    
355
  if ($map_settings['map_type'] == 1) {
356

    
357
    /* =========== display distributions using the openlayers map viewer =========== */
358

    
359
    $legendFormatQueryStr = "format=image" . urlencode('/') . "png"
360
      . "&TRANSPARENT=TRUE"
361
      . "&WIDTH=" . $map_settings['legend']['icon_width']
362
      . "&HEIGHT=" . $map_settings['legend']['icon_height']
363
      // TODO why is the layer=topp:tdwg_level_4 parameter needed at all here??
364
      // AK: i think the tdwg_level_4 is used as place holder and will be replaced later on
365
      // => search for "tdwg_level_4" in the code
366
      . "&layer=topp" . urlencode(':') . "tdwg_level_4"
367
      . "&LEGEND_OPTIONS=forceLabels" . urlencode(':') . "on"
368
      . ";fontStyle" . urlencode(':') . $fontStyles[$map_settings['legend']['font_style']]
369
      . ";fontSize" . urlencode(':') .  $map_settings['legend']['font_size']
370
      . "&SLD=";
371

    
372
    /*$out .= cdm_map_openlayers(
373
        $map_settings['bbox'],
374
        NULL,
375
        $query_string,
376
        $legendFormatQueryStr,
377
        $map_settings['caption']
378
    );
379
    */
380
  }
381
  else {
382
    $legendFormatQueryStr = '';
383
    /*
384
        cdm_map_plain_image(
385
            $map_settings['image_map']['width'],
386
            $map_settings['image_map']['height'],
387
            $map_settings['bbox'],
388
            NULL,
389
            $query_string,
390
            $legendFormatQueryStr,
391
            $map_settings['caption']
392
        );
393
    */
394
  }
395
  $out = compose_map('distribution', NULL, $query_string, $legendFormatQueryStr);
396

    
397
  return $out;
398
}
399

    
400

    
401

    
402

    
403
/**
404
 * Composes the markup for a plain image map.
405
 *
406
 * @param int $width
407
 * @param string $occurrenceQuery
408
 * @param string $distributionQuery
409
 * @param string $legendFormatQuery
410
 * @param string $map_caption
411
 *
412
* @return String
413
 *    rendered html
414
 */
415
function cdm_map_plain_image($width, $height= NULL, $occurrenceQuery = FALSE, $distributionQuery = FALSE,
416
                             $legendFormatQuery = FALSE, $map_caption = FALSE) {
417

    
418
  $map_settings = get_array_variable_merged(CDM_MAP_DISTRIBUTION, CDM_MAP_DISTRIBUTION_DEFAULT);
419

    
420
  $baselayer_name = $map_settings['image_map']['base_layer'];
421
  if(empty($baselayer_name)){
422
    $baselayer_name = "earth";
423
  }
424

    
425
  $query_string = '&img=true&recalculate=false&ms=' . $width . ($height ? ',' . $height : '')
426
  // Additional query parameters as set in the data portal admin section.
427
  . ($map_settings['bbox'] ? '&bbox=' . $map_settings['bbox'] : '')
428
  . ($map_settings['show_labels'] ? '&label=' . $map_settings['show_labels'] : '');
429

    
430
  if ($map_caption) {
431
    $query_string .= '&mlp=3&mc_s=Georgia,15,blue&mc=' . $map_caption;
432
  }
433

    
434
  if (get_edit_map_service_version_number() >= 1.1) {
435

    
436
    // Either occurrence or distribution - combined maps will be possible
437
    // in the future.
438
    if ($occurrenceQuery) {
439
      // @todo Fix $occurrenceQuery.
440
      $occurrenceQuery = str_replace("&image=false", "", $occurrenceQuery);
441
      // $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
442

    
443
      // Will be replaced below.. HACK!!!
444
      $occurrenceQuery .= '&l=' . $baselayer_name . '&as=';
445

    
446
      $query_string .= "&" . $occurrenceQuery;
447
    }
448
    elseif ($distributionQuery) {
449
      $query_string .= '&l=' . $baselayer_name . "&" .$distributionQuery;
450
    }
451

    
452
    // Apply Plain Image map settings special for version >= 1.1.
453
    /*
454
    example : title=a:Naturalized++non-invasive
455
    &ad=cyprusdivs:bdcode:a:5&as=a:ff9900,,0.1,&l=tdwg4
456
    &ms=500&bbox=32,34,35,36&img=true&legend=1&mlp=3
457
    &mc_s=Georgia,15,blue&mc=&recalculate=false
458

    
459
    http://edit.br.fgov.be/edit_wp5/v1/rest_gen.php?
460
    l=background_gis:b,cyprusdivs&ad=cyprusdivs%3Abdcode%3Aa%3A8%2C4
461
    &as=a%3A339966%2C%2C0.1%2C|b:0000ff,,
462
    &bbox=32%2C34%2C35%2C36&img=true&legend=1&mc=&mc_s=Georgia%2C15%2Cblue
463
    &mlp=3&ms=500&recalculate=false&title=a%3Aindigenous
464
    */
465

    
466
    $map_service_script_name = "rest_gen.php";
467

    
468
    $bgcolor_areaStyleId = "Y";
469
    $baselayer_areaStyleId = "Z";
470
    $bgcolor_layer = '';
471
    $additional_area_styles = array();
472

    
473
    // Background color:
474
    if ($map_settings['image_map']['bg_color'] ) {
475
      $bgcolor_layer = "background_gis:" . $bgcolor_areaStyleId;
476
      $additional_area_styles[] = $bgcolor_areaStyleId . ":" . $map_settings['image_map']['bg_color'] . ",,";
477
    }
478

    
479
    // TODO HACK to replace the default base layer which currently is tdwg4 !!!
480
    // only needed for distribution maps.
481
    if (strpos($query_string, "?l=") !== FALSE) {
482
      $layer_param_token = "?l=";
483
    }
484
    else {
485
      $layer_param_token = "&l=";
486
    }
487
    if (strpos($query_string, "?as=") !== FALSE) {
488
      $areystyle_param_token = "?as=";
489
    }
490
    else {
491
      $areystyle_param_token = "&as=";
492
    }
493
    if ($map_settings['image_map']['base_layer']) {
494
      $query_string = str_replace($layer_param_token .$baselayer_name, "$layer_param_token" . $map_settings['image_map']['base_layer'] . ":" . $baselayer_areaStyleId, $query_string);
495
    }
496
    else {
497
      $query_string = str_replace($layer_param_token . $baselayer_name, $layer_param_token . $baselayer_name . ":" . $baselayer_areaStyleId . ",", $query_string);
498
    }
499

    
500
    if ($bgcolor_layer) {
501
      $query_string = str_replace($layer_param_token, $layer_param_token . $bgcolor_layer . ",", $query_string);
502
    }
503

    
504
    if ($map_settings['image_map']['layer_style']) {
505
      $additional_area_styles[] = $baselayer_areaStyleId . ":" . $map_settings['image_map']['layer_style'];
506
    }
507

    
508
    if(isset($map_settings['projection'])){
509
      $query_string .= "&srs=" . $map_settings['projection'];
510
    }
511

    
512
    if(isset($map_settings['legend']['show']) && $map_settings['legend']['show']){
513
      $query_string .= "&legend=1";
514
    }
515

    
516
    foreach ($additional_area_styles as $as) {
517
      $query_string = str_replace($areystyle_param_token, $areystyle_param_token . $as . "|", $query_string);
518
    }
519

    
520
  }
521
  else {
522
    // Pre 1.1. version of map service.
523
    if ($occurrenceQuery) {
524

    
525
      $map_service_script_name = "point.php";
526

    
527
      // Fix $occurrenceQuery.
528
      $occurrenceQuery = str_replace("&image=false", "", $occurrenceQuery);
529
      // $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
530
      $occurrenceQuery .= '&l=v:e_w_0';
531
      $query_string .= "&" . $occurrenceQuery;
532
    }
533
    elseif ($distributionQuery) {
534
      $query_string .= "&" . $distributionQuery;
535
      $map_service_script_name = "areas.php";
536
    }
537
  }
538

    
539
  $mapUri = url(get_edit_map_service_full_uri() . '/' . $map_service_script_name . '?' .  $query_string);
540
  $out = '<img class="distribution_map" src="' . $mapUri . '" alt="Map" />';
541
  // Showing map caption.
542
  if ($map_caption) {
543
    $out .= '<div class="distribution_map_caption">' . $map_caption . '</div>';
544
  }
545

    
546
  return $out;
547
}
548

    
549

    
(3-3/10)