Project

General

Profile

Download (17.9 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 string $occurrence_query
29
 * @param string $distribution_query
30
 * @param string $legend_format_query
31
 * @param array $event_listeners
32
 *   An associative array of with OpenLayers.Map event names as key and corresponding js callbacks.
33
 *   In addition to the event names '#execute' as key is also allowed.
34
 *   Valid events are:
35
 *      - move
36
 *      - moveend
37
 *      - zoomend
38
 *      - changelayer
39
 *      - changebaselayer
40
 *      - #execute:
41
 *            force execution of the given callback after registration of the event handlers
42
 *   see http://dev.openlayers.org/apidocs/files/OpenLayers/Map-js.html#OpenLayers.Map.events for more
43
 * @param bool $resizable
44
 *    only possible for openlayers_map
45
 * @param string $force_map_type
46
 *   Can be used to override the map_type setting stored in the settings variable CDM_MAP_DISTRIBUTION
47
 *   - 1: openlayers_map
48
 *   - 0: image_map
49
 *
50
 * @return array
51
 *    A drupal render array
52
 *
53
 * Similar compose function compose_distribution_map()
54
 *
55
 * @ingroup compose
56
 */
57
function compose_map($occurrence_query = NULL, $distribution_query = NULL,
58
                     $legend_format_query = NULL, array $event_listeners = array(), $resizable = false,
59
                     $force_map_type = NULL) {
60

    
61
    $map_settings = get_array_variable_merged(CDM_MAP_DISTRIBUTION, CDM_MAP_DISTRIBUTION_DEFAULT);
62

    
63
    if($force_map_type === NULL){
64
      $force_map_type = $map_settings['map_type'];
65
    }
66

    
67
    if ($force_map_type == 1) {
68
      _add_jquery_ui();
69
    $map_html = get_openlayers_map(
70
        $occurrence_query,
71
        $distribution_query,
72
        $legend_format_query,
73
        $map_settings['caption'],
74
        $event_listeners,
75
        $resizable
76
    );
77
    }
78
     else {
79
      $map_height = round($map_settings['image_map']['width'] / (float)$map_settings['aspect_ratio']);
80
      $map_html = get_image_map(
81
        $map_settings['image_map']['width'],
82
        $map_height,
83
        $occurrence_query,
84
        $distribution_query,
85
        $legend_format_query,
86
        $map_settings['caption']
87
      );
88
     }
89
  return markup_to_render_array($map_html);
90
}
91

    
92
/**
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_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
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/map/openlayers_layers.js');
120

    
121
  $cdm_openlayers_options = array(
122
      'legendPosition'  => '3',
123
      'boundingBox' => $map_settings['bbox'],
124
      'aspectRatio' => $map_settings['aspect_ratio'],
125
      'distributionOpacity' => $map_settings['distribution_opacity'],
126
      'legendOpacity' => $map_settings['legend']['opacity'],
127
      'showLayerSwitcher' => $map_settings['openlayers']['show_layer_switcher']  ==  1,
128
      'displayOutsideMaxExtent' => $map_settings['openlayers']['display_outside_max_extent'] == 1,
129
      'resizable' => $resizable
130
//       'imgPath' => drupal_get_path('module', 'cdm_dataportal') . '/js/map/OpenLayers-2.13.1/img/' // path to the control icons
131
      // if no baseLayerNames or defaultBaseLayerName are not defined
132
      // the defaults in cdm_openlayers.js will be used
133
  );
134

    
135
  // --- setting the base layer options
136
  if (is_array($map_settings['openlayers']['base_layers']) && count($map_settings['openlayers']['base_layers']) > 0) {
137

    
138
    $layer_names = $map_settings['openlayers']['base_layers'];
139

    
140
    foreach($layer_names as $name){
141
      if(str_beginsWith($name, 'g')){
142
        if( isset($map_settings['openlayers']['google_maps_api_key']) && strlen($map_settings['openlayers']['google_maps_api_key']) == 39) {
143
          // google layer detected
144
          drupal_add_js("https://maps.googleapis.com/maps/api/js?key=" . $map_settings['openlayers']['google_maps_api_key'] . "&callback=initMap", 'external');
145
        } else {
146
          drupal_set_message('A Google Maps layer is configured but the API key is either missing or invalid. 
147
          Please set your Google Maps API key in the '  . l('Geo & Map Settings', 'admin/config/cdm_dataportal/settings/geo') .'.', 'warning');
148
        }
149

    
150
      }
151
    }
152

    
153
    $cdm_openlayers_options['baseLayerNames'] = array_values($layer_names);
154

    
155
    if($layer_names['PREFERRED']){
156
      $cdm_openlayers_options['defaultBaseLayerName'] = $layer_names['PREFERRED'];
157
      unset($layer_names['PREFERRED']); // why is this needed?
158
      if(!array_search($cdm_openlayers_options['defaultBaseLayerName'], $cdm_openlayers_options['baseLayerNames'])){
159
        // the default layer must also  be in the list of base layers
160
        $cdm_openlayers_options['baseLayerNames'][] = $cdm_openlayers_options['defaultBaseLayerName'];
161
      }
162
    }
163

    
164

    
165
  }
166

    
167
  // --- custom wms base layer
168
  $map_settings['openlayers']['custom_wms_base_layer']['params'] = json_decode($map_settings['openlayers']['custom_wms_base_layer']['params']);
169
  $cdm_openlayers_options['customWMSBaseLayerData'] = $map_settings['openlayers']['custom_wms_base_layer'];
170

    
171
  // --- eventhandlers
172
  $event_listeners_js = '';
173
  $execute_handler = '';
174
  foreach($event_listeners as $event=>$js_callback){
175
    if($event == '#execute'){
176
      $execute_handler = 'map_container.each(function(){' . $js_callback . '();});';
177
    } else {
178
      $event_listeners_js .= ($event_listeners_js ? ",\n": "\n") .'"' . $event . '": ' . $js_callback;
179
    }
180
  }
181

    
182
  $mapserver_base_uri = $edit_map_service['base_uri'];
183
  $is_https = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on';
184
  $http_protocol = $is_https ? 'https' : 'http';
185
  $mapserver_base_uri = preg_replace('/^https?:/', $http_protocol . ':', $mapserver_base_uri);
186

    
187
  // window.onload - is executed when the document and images etc is fully loaded
188
  // Query(document).ready - is executed much earlier, when the DOM is loaded
189
  drupal_add_js("
190
          jQuery(document).ready(function() {
191
                jQuery(window).load(function () {
192
                  var map_container = jQuery('#openlayers_map').cdm_openlayers_map(
193
                   '" . $mapserver_base_uri . "',
194
                   '" . $edit_map_service['version'] . "',
195
                   " .  json_encode($cdm_openlayers_options) . "
196
                );
197
                map_container.each(function(){
198
                        this.cdmOpenlayersMap.registerEvents({" . "
199
                        " . $event_listeners_js . "
200
                        });
201
                });
202
                " . $execute_handler . "
203
        });
204
      });
205
    ", array('type' => 'inline'));
206

    
207
}
208

    
209

    
210
/**
211
 * @todo Enter description here ...
212
 *
213
 * @param string $bounding_box
214
 * @param string $occurrenceQuery
215
 * @param string $distributionQuery
216
 * @param string $legendFormatQuery
217
 * @param string $map_caption
218
 * @param array $event_listeners
219
 *   An associative array of with OpenLayers.Map event names as key and corresponding js callbacks.
220
 *   In addition to the event names '#execute' as key is also allowed.
221
 *   Valid events are:
222
 *      - move
223
 *      - moveend
224
 *      - zoomend
225
 *      - changelayer
226
 *      - changebaselayer
227
 *      - #execute:
228
 *            force execution of the given callback after registration of the event handlers
229
 *   see http://dev.openlayers.org/apidocs/files/OpenLayers/Map-js.html#OpenLayers.Map.events for more
230
 *
231
 * @return String
232
 *    rendered html
233
 */
234
function get_openlayers_map($occurrenceQuery = FALSE, $distributionQuery = FALSE,
235
                            $legendFormatQuery = FALSE, $map_caption = FALSE, array $event_listeners = array(),
236
                            $resizable = false) {
237

    
238
  $map_settings = get_array_variable_merged(CDM_MAP_DISTRIBUTION, CDM_MAP_DISTRIBUTION_DEFAULT);
239

    
240
  _add_js_openlayers_map($map_settings, $event_listeners, $resizable);
241

    
242
  $out = '<div id="openlayers_container" class="openlayers_width ui-widget-content" style="width: 100%;">';
243
  $out .= '<div id="openlayers_map" class="smallmap" style="width:100%; height:100%; margin: 10px;"';
244

    
245
  // Additional query parameters as set in the data portal admin section.
246
  $labels_on = $map_settings['show_labels'];
247

    
248
  // need to set the ms parameter to some value in order to satisfy the
249
  // map service even if this value should not be required:
250
  $width = 512;
251

    
252
  $openlayers_map_query_string = '&img=false&ms=' . $width
253
  . ($labels_on ? '&label=' . $labels_on : '');
254

    
255
  if ($occurrenceQuery) {
256
    // @todo Fix $occurrenceQuery.
257
    //     $occurrenceQuery .= '&bbox=-180,-90,180,90';
258
    $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0'; // TODO why are we using v:atbi,e_w_0 as layer ???
259
    // $occurrenceQuery .= '&l=v:e_w_0';
260
    // TODO add to cdm service?
261
    $occurrenceQuery .= '&legend=0';
262

    
263
    $out .= ' occurrenceQuery="' . $occurrenceQuery . '&' . $openlayers_map_query_string . '"';
264
  }
265

    
266
  if ($distributionQuery) {
267
    //HACK for testing (this must be done in js)
268
//     $distributionQuery .= "&layer=em_tiny_jan2003&dest_projection_epsg=7777777";
269
    $out .= ' distributionQuery="' . $distributionQuery . '&' . $openlayers_map_query_string . '"';
270
  }
271

    
272
  if ($legendFormatQuery) {
273
    $out .= ' legendFormatQuery="' . $legendFormatQuery . '"';
274
  }
275

    
276
  $out .= '></div></div>';
277

    
278
  // Showing map caption.
279
  if ($map_caption) {
280
    $out .= '<div class="distribution_map_caption">' . $map_caption . '</div>';
281
  }
282
  return $out;
283
}
284

    
285

    
286
/**
287
 * Composes the render array for a distribution map of the given taxon.
288
 *
289
 * The distribution map can either be a plain image or a dynamic open layers map
290
 * depending on the settings.
291
 *
292
 * compose_hook() implementation
293
 *
294
 * @param $taxon
295
 *   The CDM Taxon instance to create the distribution map for.
296
 * @return array
297
 *    A drupal render array
298
 *
299
 * Similar compose function compose_map()
300
 *
301
 * @ingroup compose
302
 */
303
function compose_distribution_map($taxon, $query_string) {
304

    
305
  $out = '';
306

    
307
  $fontStyles = array(
308
      0 => "plane",
309
      1 => "italic",
310
  );
311

    
312
  if (!$query_string) {
313
    // The $query_string is empty if there are no distribution areas defined.
314
    return null;
315
  }
316

    
317
  /* ------ choose the display mode, either openlayers or static image ------ */
318

    
319
  $map_settings = get_array_variable_merged(CDM_MAP_DISTRIBUTION, CDM_MAP_DISTRIBUTION_DEFAULT);
320

    
321
  if ($map_settings['map_type'] == 1) {
322

    
323
    /* =========== display distributions using the openlayers map viewer =========== */
324

    
325
    $legendFormatQueryStr = "format=image" . urlencode('/') . "png"
326
      . "&TRANSPARENT=TRUE"
327
      . "&WIDTH=" . $map_settings['legend']['icon_width']
328
      . "&HEIGHT=" . $map_settings['legend']['icon_height']
329
      // TODO why is the layer=topp:tdwg_level_4 parameter needed at all here??
330
      // AK: i think the tdwg_level_4 is used as place holder and will be replaced later on
331
      // => search for "tdwg_level_4" in the code
332
      . "&layer=topp" . urlencode(':') . "tdwg_level_4"
333
      . "&LEGEND_OPTIONS=forceLabels" . urlencode(':') . "on"
334
      . ";fontStyle" . urlencode(':') . $fontStyles[$map_settings['legend']['font_style']]
335
      . ";fontSize" . urlencode(':') .  $map_settings['legend']['font_size']
336
      . "&SLD=";
337

    
338
    /*$out .= get_openlayers_map(
339
        $map_settings['bbox'],
340
        NULL,
341
        $query_string,
342
        $legendFormatQueryStr,
343
        $map_settings['caption']
344
    );
345
    */
346
  }
347
  else {
348
    $legendFormatQueryStr = '';
349
    /*
350
        get_image_map(
351
            $map_settings['image_map']['width'],
352
            $map_settings['image_map']['height'],
353
            $map_settings['bbox'],
354
            NULL,
355
            $query_string,
356
            $legendFormatQueryStr,
357
            $map_settings['caption']
358
        );
359
    */
360
  }
361
  $out = compose_map(NULL, $query_string, $legendFormatQueryStr);
362

    
363
  return $out;
364
}
365

    
366

    
367

    
368

    
369
/**
370
 * @todo Enter description here ...
371
 *
372
 * @param unknown_type $width
373
 * @param unknown_type $occurrenceQuery
374
 * @param unknown_type $distributionQuery
375
 * @param unknown_type $legendFormatQuery
376
 * @param unknown_type $map_caption
377
 *
378
* @return String
379
 *    rendered html
380
 */
381
function get_image_map($width, $height= NULL, $occurrenceQuery = FALSE, $distributionQuery = FALSE,
382
                       $legendFormatQuery = FALSE, $map_caption = FALSE) {
383

    
384
  $map_settings = get_array_variable_merged(CDM_MAP_DISTRIBUTION, CDM_MAP_DISTRIBUTION_DEFAULT);
385

    
386
  $baselayer_name = $map_settings['image_map']['base_layer'];
387
  if(empty($baselayer_name)){
388
    $baselayer_name = "earth";
389
  }
390

    
391
  $query_string = '&img=true&recalculate=false&ms=' . $width . ($height ? ',' . $height : '')
392
  // Additional query parameters as set in the data portal admin section.
393
  . ($map_settings['bbox'] ? '&bbox=' . $map_settings['bbox'] : '')
394
  . ($map_settings['show_labels'] ? '&label=' . $map_settings['show_labels'] : '');
395

    
396
  if ($map_caption) {
397
    $query_string .= '&mlp=3&mc_s=Georgia,15,blue&mc=' . $map_caption;
398
  }
399

    
400
  if (get_edit_map_service_version_number() >= 1.1) {
401

    
402
    // Either occurrence or distribution - combined maps will be possible
403
    // in the future.
404
    if ($occurrenceQuery) {
405
      // @todo Fix $occurrenceQuery.
406
      $occurrenceQuery = str_replace("&image=false", "", $occurrenceQuery);
407
      // $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
408

    
409
      // Will be replaced below.. HACK!!!
410
      $occurrenceQuery .= '&l=' . $baselayer_name . '&as=';
411

    
412
      $query_string .= "&" . $occurrenceQuery;
413
    }
414
    elseif ($distributionQuery) {
415
      $query_string .= '&l=' . $baselayer_name . "&" .$distributionQuery;
416
    }
417

    
418
    // Apply Plain Image map settings special for version >= 1.1.
419
    /*
420
    example : title=a:Naturalized++non-invasive
421
    &ad=cyprusdivs:bdcode:a:5&as=a:ff9900,,0.1,&l=tdwg4
422
    &ms=500&bbox=32,34,35,36&img=true&legend=1&mlp=3
423
    &mc_s=Georgia,15,blue&mc=&recalculate=false
424

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

    
432
    $map_service_script_name = "rest_gen.php";
433

    
434
    $bgcolor_areaStyleId = "Y";
435
    $baselayer_areaStyleId = "Z";
436
    $bgcolor_layer = '';
437
    $additional_area_styles = array();
438

    
439
    // Background color:
440
    if ($map_settings['image_map']['bg_color'] ) {
441
      $bgcolor_layer = "background_gis:" . $bgcolor_areaStyleId;
442
      $additional_area_styles[] = $bgcolor_areaStyleId . ":" . $map_settings['image_map']['bg_color'] . ",,";
443
    }
444

    
445
    // TODO HACK to replace the default base layer which currently is tdwg4 !!!
446
    // only needed for distribution maps.
447
    if (strpos($query_string, "?l=") !== FALSE) {
448
      $layer_param_token = "?l=";
449
    }
450
    else {
451
      $layer_param_token = "&l=";
452
    }
453
    if (strpos($query_string, "?as=") !== FALSE) {
454
      $areystyle_param_token = "?as=";
455
    }
456
    else {
457
      $areystyle_param_token = "&as=";
458
    }
459
    if ($map_settings['image_map']['base_layer']) {
460
      $query_string = str_replace($layer_param_token .$baselayer_name, "$layer_param_token" . $map_settings['image_map']['base_layer'] . ":" . $baselayer_areaStyleId, $query_string);
461
    }
462
    else {
463
      $query_string = str_replace($layer_param_token . $baselayer_name, $layer_param_token . $baselayer_name . ":" . $baselayer_areaStyleId . ",", $query_string);
464
    }
465

    
466
    if ($bgcolor_layer) {
467
      $query_string = str_replace($layer_param_token, $layer_param_token . $bgcolor_layer . ",", $query_string);
468
    }
469

    
470
    if ($map_settings['image_map']['layer_style']) {
471
      $additional_area_styles[] = $baselayer_areaStyleId . ":" . $map_settings['image_map']['layer_style'];
472
    }
473

    
474
    if(isset($map_settings['projection'])){
475
      $query_string .= "&srs=" . $map_settings['projection'];
476
    }
477

    
478
    if(isset($map_settings['legend']['show']) && $map_settings['legend']['show']){
479
      $query_string .= "&legend=1";
480
    }
481

    
482
    foreach ($additional_area_styles as $as) {
483
      $query_string = str_replace($areystyle_param_token, $areystyle_param_token . $as . "|", $query_string);
484
    }
485

    
486
  }
487
  else {
488
    // Pre 1.1. version of map service.
489
    if ($occurrenceQuery) {
490

    
491
      $map_service_script_name = "point.php";
492

    
493
      // Fix $occurrenceQuery.
494
      $occurrenceQuery = str_replace("&image=false", "", $occurrenceQuery);
495
      // $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
496
      $occurrenceQuery .= '&l=v:e_w_0';
497
      $query_string .= "&" . $occurrenceQuery;
498
    }
499
    elseif ($distributionQuery) {
500
      $query_string .= "&" . $distributionQuery;
501
      $map_service_script_name = "areas.php";
502
    }
503
  }
504

    
505
  $mapUri = url(get_edit_map_service_full_uri() . '/' . $map_service_script_name . '?' .  $query_string);
506
  $out = '<img class="distribution_map" src="' . $mapUri . '" alt="Map" />';
507
  // Showing map caption.
508
  if ($map_caption) {
509
    $out .= '<div class="distribution_map_caption">' . $map_caption . '</div>';
510
  }
511

    
512
  return $out;
513
}
514

    
515

    
(3-3/10)