Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

cdm-dataportal / modules / cdm_dataportal / includes / maps.inc @ 669f08ee

History | View | Annotate | Download (18.5 KB)

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
      'aspectRatio' => $map_settings['aspect_ratio'],
139
      'distributionOpacity' => $map_settings['distribution_opacity'],
140
      'legendOpacity' => $map_settings['legend']['opacity'],
141
      'showLayerSwitcher' => $map_settings['openlayers']['show_layer_switcher']  ==  1,
142
      'displayOutsideMaxExtent' => $map_settings['openlayers']['display_outside_max_extent'] == 1,
143
      'resizable' => $resizable
144
//       'imgPath' => drupal_get_path('module', 'cdm_dataportal') . '/js/map/OpenLayers-2.13.1/img/' // path to the control icons
145
      // if no baseLayerNames or defaultBaseLayerName are not defined
146
      // the defaults in cdm_openlayers.js will be used
147
  );
148

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

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

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

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

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

    
177
  }
178

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

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

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

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

    
219
}
220

    
221

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

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

    
252
  if($map_id == NULL){
253
    $map_id = sha1($occurrenceQuery . $distributionQuery);
254
  }
255

    
256
  _add_js_openlayers_map($map_id, $map_settings, $event_listeners, $resizable);
257

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

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

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

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

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

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

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

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

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

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

    
301

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

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

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

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

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

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

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

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

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

    
378
  return $out;
379
}
380

    
381

    
382

    
383

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

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

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

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

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

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

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

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

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

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

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

    
447
    $map_service_script_name = "rest_gen.php";
448

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

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

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

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

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

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

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

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

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

    
506
      $map_service_script_name = "point.php";
507

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

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

    
527
  return $out;
528
}
529

    
530

    
Add picture from clipboard (Maximum size: 40 MB)