Project

General

Profile

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

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

    
113
  _add_js_openlayers();
114

    
115
  $edit_map_service = get_edit_map_service_settings();
116

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

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

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

    
151
    $layer_names = $map_settings['openlayers']['base_layers'];
152

    
153
    foreach($layer_names as $name){
154
      if(str_beginsWith($name, 'g')){
155
        if( isset($map_settings['openlayers']['google_maps_api_key']) && strlen($map_settings['openlayers']['google_maps_api_key']) == 39) {
156
          // google layer detected
157
          drupal_add_js("https://maps.googleapis.com/maps/api/js?key=" . $map_settings['openlayers']['google_maps_api_key'] . "&callback=initMap", 'external');
158
        } else {
159
          drupal_set_message('A Google Maps layer is configured but the API key is either missing or invalid. 
160
          Please set your Google Maps API key in the '  . l('Geo & Map Settings', 'admin/config/cdm_dataportal/settings/geo') .'.', 'warning');
161
        }
162
      }
163
    }
164

    
165
    $cdm_openlayers_options['baseLayerNames'] = array_values($layer_names);
166

    
167
    if($layer_names['PREFERRED']){
168
      $cdm_openlayers_options['defaultBaseLayerName'] = $layer_names['PREFERRED'];
169
      unset($layer_names['PREFERRED']); // why is this needed?
170
      if(!array_search($cdm_openlayers_options['defaultBaseLayerName'], $cdm_openlayers_options['baseLayerNames'])){
171
        // the default layer must also  be in the list of base layers
172
        $cdm_openlayers_options['baseLayerNames'][] = $cdm_openlayers_options['defaultBaseLayerName'];
173
      }
174
    }
175

    
176
  }
177

    
178
  // --- custom wms base layer
179
  $map_settings['openlayers']['custom_wms_base_layer']['params'] = json_decode($map_settings['openlayers']['custom_wms_base_layer']['params']);
180
  $cdm_openlayers_options['customWMSBaseLayerData'] = $map_settings['openlayers']['custom_wms_base_layer'];
181

    
182
  // --- eventhandlers
183
  $event_listeners_js = '';
184
  $execute_handler = '';
185
  foreach($event_listeners as $event=>$js_callback){
186
    if($event == '#execute'){
187
      $execute_handler = 'map_container.each(function(){' . $js_callback . '();});';
188
    } else {
189
      $event_listeners_js .= ($event_listeners_js ? ",\n": "\n") .'"' . $event . '": ' . $js_callback;
190
    }
191
  }
192

    
193
  $mapserver_base_uri = $edit_map_service['base_uri'];
194
  $is_https = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on';
195
  $http_protocol = $is_https ? 'https' : 'http';
196
  $mapserver_base_uri = preg_replace('/^https?:/', $http_protocol . ':', $mapserver_base_uri);
197

    
198
  // window.onload - is executed when the document and images etc is fully loaded
199
  // Query(document).ready - is executed much earlier, when the DOM is loaded
200
  drupal_add_js("
201
          jQuery(document).ready(function() {
202
                jQuery(window).load(function () {
203
                  var map_container = jQuery('#openlayers_map').cdm_openlayers_map(
204
                   '" . $mapserver_base_uri . "',
205
                   '" . $edit_map_service['version'] . "',
206
                   " .  json_encode($cdm_openlayers_options) . "
207
                );
208
                map_container.each(function(){
209
                        this.cdmOpenlayersMap.registerEvents({" . "
210
                        " . $event_listeners_js . "
211
                        });
212
                });
213
                " . $execute_handler . "
214
        });
215
      });
216
    ", array('type' => 'inline'));
217

    
218
}
219

    
220

    
221
/**
222
 * Creates markup for an openlayers based dynamic map.
223
 *
224
 * @param string $bounding_box
225
 * @param string $occurrenceQuery
226
 * @param string $distributionQuery
227
 * @param string $legendFormatQuery
228
 * @param string $map_caption
229
 * @param array $event_listeners
230
 *   An associative array of with OpenLayers.Map event names as key and corresponding js callbacks.
231
 *   In addition to the event names '#execute' as key is also allowed.
232
 *   Valid events are:
233
 *      - move
234
 *      - moveend
235
 *      - zoomend
236
 *      - changelayer
237
 *      - changebaselayer
238
 *      - #execute:
239
 *            force execution of the given callback after registration of the event handlers
240
 *   see http://dev.openlayers.org/apidocs/files/OpenLayers/Map-js.html#OpenLayers.Map.events for more
241
 *
242
 * @return String
243
 *    The markup for the map
244
 */
245
function cdm_map_openlayers($map_id, $occurrenceQuery = FALSE, $distributionQuery = FALSE,
246
                            $legendFormatQuery = FALSE, $map_caption = FALSE, array $event_listeners = array(),
247
                            $resizable = false) {
248

    
249
  $map_settings = get_array_variable_merged(CDM_MAP_DISTRIBUTION, CDM_MAP_DISTRIBUTION_DEFAULT);
250

    
251
  if($map_id == NULL){
252
    $map_id = "openlayers-container-" . sha1($occurrenceQuery . $distributionQuery);
253
  }
254

    
255
  _add_js_openlayers_map($map_settings, $event_listeners, $resizable);
256

    
257
  $out = '<div id="' . $map_id . '" class="openlayers-container openlayers_width ui-widget-content" style="width: 100%;">';
258
  $out .= '<div id="openlayers_map" class="smallmap" style="width:100%; height:100%; margin: 10px;"';
259

    
260
  // Additional query parameters as set in the data portal admin section.
261
  $labels_on = $map_settings['show_labels'];
262

    
263
  // need to set the ms parameter to some value in order to satisfy the
264
  // map service even if this value should not be required:
265
  $width = 512;
266

    
267
  $openlayers_map_query_string = '&img=false&ms=' . $width
268
  . ($labels_on ? '&label=' . $labels_on : '');
269

    
270
  if ($occurrenceQuery) {
271
    // @todo Fix $occurrenceQuery.
272
    //     $occurrenceQuery .= '&bbox=-180,-90,180,90';
273
    $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0'; // TODO why are we using v:atbi,e_w_0 as layer ???
274
    // $occurrenceQuery .= '&l=v:e_w_0';
275
    // TODO add to cdm service?
276
    $occurrenceQuery .= '&legend=0';
277

    
278
    $out .= ' occurrenceQuery="' . $occurrenceQuery . '&' . $openlayers_map_query_string . '"';
279
  }
280

    
281
  if ($distributionQuery) {
282
    //HACK for testing (this must be done in js)
283
//     $distributionQuery .= "&layer=em_tiny_jan2003&dest_projection_epsg=7777777";
284
    $out .= ' distributionQuery="' . $distributionQuery . '&' . $openlayers_map_query_string . '"';
285
  }
286

    
287
  if ($legendFormatQuery) {
288
    $out .= ' legendFormatQuery="' . $legendFormatQuery . '"';
289
  }
290

    
291
  $out .= '></div></div>';
292

    
293
  // Showing map caption.
294
  if ($map_caption) {
295
    $out .= '<div class="distribution_map_caption">' . $map_caption . '</div>';
296
  }
297
  return $out;
298
}
299

    
300

    
301
/**
302
 * Composes the render array for a distribution map using the given distribution query string.
303
 *
304
 * The distribution map can either be a plain image or a dynamic open layers map
305
 * depending on the settings.
306
 *
307
 * compose_hook() implementation
308
 *
309
 * @param string $query_string
310
 *    An EDIT map services distribution query string
311
 *
312
 * @return array
313
 *    A drupal render array
314
 *
315
 * Similar compose function compose_map()
316
 *
317
 * @ingroup compose
318
 */
319
function compose_distribution_map($query_string) {
320

    
321
  $fontStyles = array(
322
      0 => "plane",
323
      1 => "italic",
324
  );
325

    
326
  if (!$query_string) {
327
    // The $query_string is empty if there are no distribution areas defined.
328
    return null;
329
  }
330

    
331
  /* ------ choose the display mode, either openlayers or static image ------ */
332

    
333
  $map_settings = get_array_variable_merged(CDM_MAP_DISTRIBUTION, CDM_MAP_DISTRIBUTION_DEFAULT);
334

    
335
  if ($map_settings['map_type'] == 1) {
336

    
337
    /* =========== display distributions using the openlayers map viewer =========== */
338

    
339
    $legendFormatQueryStr = "format=image" . urlencode('/') . "png"
340
      . "&TRANSPARENT=TRUE"
341
      . "&WIDTH=" . $map_settings['legend']['icon_width']
342
      . "&HEIGHT=" . $map_settings['legend']['icon_height']
343
      // TODO why is the layer=topp:tdwg_level_4 parameter needed at all here??
344
      // AK: i think the tdwg_level_4 is used as place holder and will be replaced later on
345
      // => search for "tdwg_level_4" in the code
346
      . "&layer=topp" . urlencode(':') . "tdwg_level_4"
347
      . "&LEGEND_OPTIONS=forceLabels" . urlencode(':') . "on"
348
      . ";fontStyle" . urlencode(':') . $fontStyles[$map_settings['legend']['font_style']]
349
      . ";fontSize" . urlencode(':') .  $map_settings['legend']['font_size']
350
      . "&SLD=";
351

    
352
    /*$out .= cdm_map_openlayers(
353
        $map_settings['bbox'],
354
        NULL,
355
        $query_string,
356
        $legendFormatQueryStr,
357
        $map_settings['caption']
358
    );
359
    */
360
  }
361
  else {
362
    $legendFormatQueryStr = '';
363
    /*
364
        cdm_map_plain_image(
365
            $map_settings['image_map']['width'],
366
            $map_settings['image_map']['height'],
367
            $map_settings['bbox'],
368
            NULL,
369
            $query_string,
370
            $legendFormatQueryStr,
371
            $map_settings['caption']
372
        );
373
    */
374
  }
375
  $out = compose_map('distribution', NULL, $query_string, $legendFormatQueryStr);
376

    
377
  return $out;
378
}
379

    
380

    
381

    
382

    
383
/**
384
 * Composes the markup for a plain image map.
385
 *
386
 * @param int $width
387
 * @param string $occurrenceQuery
388
 * @param string $distributionQuery
389
 * @param string $legendFormatQuery
390
 * @param string $map_caption
391
 *
392
* @return String
393
 *    rendered html
394
 */
395
function cdm_map_plain_image($width, $height= NULL, $occurrenceQuery = FALSE, $distributionQuery = FALSE,
396
                             $legendFormatQuery = FALSE, $map_caption = FALSE) {
397

    
398
  $map_settings = get_array_variable_merged(CDM_MAP_DISTRIBUTION, CDM_MAP_DISTRIBUTION_DEFAULT);
399

    
400
  $baselayer_name = $map_settings['image_map']['base_layer'];
401
  if(empty($baselayer_name)){
402
    $baselayer_name = "earth";
403
  }
404

    
405
  $query_string = '&img=true&recalculate=false&ms=' . $width . ($height ? ',' . $height : '')
406
  // Additional query parameters as set in the data portal admin section.
407
  . ($map_settings['bbox'] ? '&bbox=' . $map_settings['bbox'] : '')
408
  . ($map_settings['show_labels'] ? '&label=' . $map_settings['show_labels'] : '');
409

    
410
  if ($map_caption) {
411
    $query_string .= '&mlp=3&mc_s=Georgia,15,blue&mc=' . $map_caption;
412
  }
413

    
414
  if (get_edit_map_service_version_number() >= 1.1) {
415

    
416
    // Either occurrence or distribution - combined maps will be possible
417
    // in the future.
418
    if ($occurrenceQuery) {
419
      // @todo Fix $occurrenceQuery.
420
      $occurrenceQuery = str_replace("&image=false", "", $occurrenceQuery);
421
      // $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
422

    
423
      // Will be replaced below.. HACK!!!
424
      $occurrenceQuery .= '&l=' . $baselayer_name . '&as=';
425

    
426
      $query_string .= "&" . $occurrenceQuery;
427
    }
428
    elseif ($distributionQuery) {
429
      $query_string .= '&l=' . $baselayer_name . "&" .$distributionQuery;
430
    }
431

    
432
    // Apply Plain Image map settings special for version >= 1.1.
433
    /*
434
    example : title=a:Naturalized++non-invasive
435
    &ad=cyprusdivs:bdcode:a:5&as=a:ff9900,,0.1,&l=tdwg4
436
    &ms=500&bbox=32,34,35,36&img=true&legend=1&mlp=3
437
    &mc_s=Georgia,15,blue&mc=&recalculate=false
438

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

    
446
    $map_service_script_name = "rest_gen.php";
447

    
448
    $bgcolor_areaStyleId = "Y";
449
    $baselayer_areaStyleId = "Z";
450
    $bgcolor_layer = '';
451
    $additional_area_styles = array();
452

    
453
    // Background color:
454
    if ($map_settings['image_map']['bg_color'] ) {
455
      $bgcolor_layer = "background_gis:" . $bgcolor_areaStyleId;
456
      $additional_area_styles[] = $bgcolor_areaStyleId . ":" . $map_settings['image_map']['bg_color'] . ",,";
457
    }
458

    
459
    // TODO HACK to replace the default base layer which currently is tdwg4 !!!
460
    // only needed for distribution maps.
461
    if (strpos($query_string, "?l=") !== FALSE) {
462
      $layer_param_token = "?l=";
463
    }
464
    else {
465
      $layer_param_token = "&l=";
466
    }
467
    if (strpos($query_string, "?as=") !== FALSE) {
468
      $areystyle_param_token = "?as=";
469
    }
470
    else {
471
      $areystyle_param_token = "&as=";
472
    }
473
    if ($map_settings['image_map']['base_layer']) {
474
      $query_string = str_replace($layer_param_token .$baselayer_name, "$layer_param_token" . $map_settings['image_map']['base_layer'] . ":" . $baselayer_areaStyleId, $query_string);
475
    }
476
    else {
477
      $query_string = str_replace($layer_param_token . $baselayer_name, $layer_param_token . $baselayer_name . ":" . $baselayer_areaStyleId . ",", $query_string);
478
    }
479

    
480
    if ($bgcolor_layer) {
481
      $query_string = str_replace($layer_param_token, $layer_param_token . $bgcolor_layer . ",", $query_string);
482
    }
483

    
484
    if ($map_settings['image_map']['layer_style']) {
485
      $additional_area_styles[] = $baselayer_areaStyleId . ":" . $map_settings['image_map']['layer_style'];
486
    }
487

    
488
    if(isset($map_settings['projection'])){
489
      $query_string .= "&srs=" . $map_settings['projection'];
490
    }
491

    
492
    if(isset($map_settings['legend']['show']) && $map_settings['legend']['show']){
493
      $query_string .= "&legend=1";
494
    }
495

    
496
    foreach ($additional_area_styles as $as) {
497
      $query_string = str_replace($areystyle_param_token, $areystyle_param_token . $as . "|", $query_string);
498
    }
499

    
500
  }
501
  else {
502
    // Pre 1.1. version of map service.
503
    if ($occurrenceQuery) {
504

    
505
      $map_service_script_name = "point.php";
506

    
507
      // Fix $occurrenceQuery.
508
      $occurrenceQuery = str_replace("&image=false", "", $occurrenceQuery);
509
      // $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
510
      $occurrenceQuery .= '&l=v:e_w_0';
511
      $query_string .= "&" . $occurrenceQuery;
512
    }
513
    elseif ($distributionQuery) {
514
      $query_string .= "&" . $distributionQuery;
515
      $map_service_script_name = "areas.php";
516
    }
517
  }
518

    
519
  $mapUri = url(get_edit_map_service_full_uri() . '/' . $map_service_script_name . '?' .  $query_string);
520
  $out = '<img class="distribution_map" src="' . $mapUri . '" alt="Map" />';
521
  // Showing map caption.
522
  if ($map_caption) {
523
    $out .= '<div class="distribution_map_caption">' . $map_caption . '</div>';
524
  }
525

    
526
  return $out;
527
}
528

    
529

    
(3-3/10)