Project

General

Profile

Download (18.1 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
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/map/openlayers_layers.js');
119

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

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

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

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

    
149
      }
150
    }
151

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

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

    
163

    
164
  }
165

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

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

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

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

    
206
}
207

    
208

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

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

    
239
  if($map_id == NULL){
240
    $map_id = "openlayers-container-" . sha1($occurrenceQuery . $distributionQuery);
241
  }
242

    
243
  _add_js_openlayers_map($map_settings, $event_listeners, $resizable);
244

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

    
248
  // Additional query parameters as set in the data portal admin section.
249
  $labels_on = $map_settings['show_labels'];
250

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

    
255
  $openlayers_map_query_string = '&img=false&ms=' . $width
256
  . ($labels_on ? '&label=' . $labels_on : '');
257

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

    
266
    $out .= ' occurrenceQuery="' . $occurrenceQuery . '&' . $openlayers_map_query_string . '"';
267
  }
268

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

    
275
  if ($legendFormatQuery) {
276
    $out .= ' legendFormatQuery="' . $legendFormatQuery . '"';
277
  }
278

    
279
  $out .= '></div></div>';
280

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

    
288

    
289
/**
290
 * Composes the render array for a distribution map using the given distribution query string.
291
 *
292
 * The distribution map can either be a plain image or a dynamic open layers map
293
 * depending on the settings.
294
 *
295
 * compose_hook() implementation
296
 *
297
 * @param string $query_string
298
 *    An EDIT map services distribution query string
299
 *
300
 * @return array
301
 *    A drupal render array
302
 *
303
 * Similar compose function compose_map()
304
 *
305
 * @ingroup compose
306
 */
307
function compose_distribution_map($query_string) {
308

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

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

    
319
  /* ------ choose the display mode, either openlayers or static image ------ */
320

    
321
  $map_settings = get_array_variable_merged(CDM_MAP_DISTRIBUTION, CDM_MAP_DISTRIBUTION_DEFAULT);
322

    
323
  if ($map_settings['map_type'] == 1) {
324

    
325
    /* =========== display distributions using the openlayers map viewer =========== */
326

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

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

    
365
  return $out;
366
}
367

    
368

    
369

    
370

    
371
/**
372
 * Composes the markup for a plain image map.
373
 *
374
 * @param int $width
375
 * @param string $occurrenceQuery
376
 * @param string $distributionQuery
377
 * @param string $legendFormatQuery
378
 * @param string $map_caption
379
 *
380
* @return String
381
 *    rendered html
382
 */
383
function cdm_map_plain_image($width, $height= NULL, $occurrenceQuery = FALSE, $distributionQuery = FALSE,
384
                             $legendFormatQuery = FALSE, $map_caption = FALSE) {
385

    
386
  $map_settings = get_array_variable_merged(CDM_MAP_DISTRIBUTION, CDM_MAP_DISTRIBUTION_DEFAULT);
387

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

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

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

    
402
  if (get_edit_map_service_version_number() >= 1.1) {
403

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

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

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

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

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

    
434
    $map_service_script_name = "rest_gen.php";
435

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

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

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

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

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

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

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

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

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

    
493
      $map_service_script_name = "point.php";
494

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

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

    
514
  return $out;
515
}
516

    
517

    
(3-3/10)