xref: /webtrees/resources/views/modules/pedigree-map/chart.phtml (revision d64ed531462150f63b5bc61bef310c002a9cf6f6)
1<?php use Fisharebest\Webtrees\I18N; ?>
2<?php use Fisharebest\Webtrees\View; ?>
3
4<div class="py-4">
5    <div class="row gchart osm-wrapper">
6        <div id="osm-map" class="col-sm-9 wt-ajax-load osm-user-map" dir="ltr"></div>
7        <ul class="col-sm-3 osm-sidebar wt-page-options-value list-unstyled p-0"></ul>
8    </div>
9</div>
10
11<?php View::push('styles') ?>
12<style>
13    .osm-wrapper, .osm-user-map {
14        height: 75vh
15    }
16
17    .osm-sidebar {
18        height: 100%;
19        overflow-y: auto;
20        padding: 0;
21        margin: 0;
22        border: 0;
23        display: none;
24        font-size: small;
25    }
26
27    .osm-sidebar .gchart {
28        margin: 1px;
29        padding: 2px
30    }
31
32    .osm-sidebar .gchart img {
33        height: 15px;
34        width: 25px
35    }
36
37    .osm-sidebar .border-danger:hover {
38        cursor: not-allowed
39    }
40</style>
41<?php View::endpush() ?>
42
43<?php View::push('javascript') ?>
44<script type="application/javascript">
45  "use strict";
46
47  window.WT_OSM = (function() {
48    let baseData = {
49      minZoom: 2,
50      providerName: "OpenStreetMap.Mapnik",
51      providerOptions: [],
52      I18N: {
53        zoomInTitle: <?= json_encode(I18N::translate('Zoom in')) ?>,
54        zoomOutTitle: <?= json_encode(I18N::translate('Zoom out')) ?>,
55        reset: <?= json_encode(I18N::translate('Reset to initial map state')) ?>,
56        noData: <?= json_encode(I18N::translate('No mappable items')) ?>,
57        error: <?= json_encode(I18N::translate('An unknown error occurred')) ?>
58      }
59    };
60
61    let map          = null;
62    let zoom         = null;
63    let markers      = L.markerClusterGroup({
64      showCoverageOnHover: false
65    });
66
67    let resetControl = L.Control.extend({
68      options: {
69        position: 'topleft'
70      },
71
72      onAdd: function (map) {
73        let container     = L.DomUtil.create('div', 'leaflet-bar leaflet-control leaflet-control-custom');
74        container.onclick = function () {
75          if (zoom) {
76            map.flyTo(markers.getBounds().getCenter(), zoom);
77          } else {
78            map.flyToBounds(markers.getBounds().pad(0.2));
79          }
80          return false;
81        };
82        let anchor   = L.DomUtil.create('a', 'leaflet-control-reset', container);
83        anchor.href  = '#';
84        anchor.title = baseData.I18N.reset;
85        anchor.role  = 'button';
86        $(anchor).attr('aria-label', 'reset');
87        let image = L.DomUtil.create('i', 'fas fa-redo', anchor);
88        image.alt = baseData.I18N.reset;
89
90        return container;
91      },
92    });
93
94    /**
95     *
96     * @private
97     */
98    let _drawMap = function () {
99      map = L.map('osm-map', {
100        center     : [0, 0],
101        minZoom    : baseData.minZoom, // maxZoom set by leaflet-providers.js
102        zoomControl: false, // remove default
103      });
104      L.tileLayer.provider(baseData.providerName, baseData.providerOptions).addTo(map);
105      L.control.zoom({ // Add zoom with localised text
106        zoomInTitle : baseData.I18N.zoomInTitle,
107        zoomOutTitle: baseData.I18N.zoomOutTitle,
108      }).addTo(map);
109    };
110
111    /**
112     *
113     * @param reference
114     * @param mapType
115     * @param Generations
116     * @private
117     */
118    let _addLayer = function (reference, mapType, Generations) {
119      let geoJsonLayer;
120      let domObj  = '.osm-sidebar';
121      let sidebar = '';
122
123      $.getJSON(<?= json_encode(route('module', ['module' => 'pedigree-map', 'action' => 'MapData', 'tree' => $individual->tree()->name(), 'xref' => $individual->xref()])) ?>, {
124        reference:   reference,
125        type:        mapType,
126        generations: Generations
127      })
128        .done(function (data, textStatus, jqXHR) {
129          if (jqXHR.status === 200 && data.features.length === 1) {
130            zoom = data.features[0].properties.zoom;
131          }
132          geoJsonLayer = L.geoJson(data, {
133            pointToLayer : function (feature, latlng) {
134              return new L.Marker(latlng, {
135                icon : L.BeautifyIcon.icon({
136                  icon           : feature.properties.icon['name'],
137                  borderColor    : 'transparent',
138                  backgroundColor: feature.valid ? feature.properties.icon['color'] : 'transparent',
139                  iconShape      : 'marker',
140                  textColor      : feature.valid ? 'white' : 'transparent',
141                }),
142                title: feature.properties.tooltip,
143                alt  : feature.properties.tooltip,
144                id   : feature.id
145              })
146                .on('popupopen', function (e) {
147                  let sidebar = $('.osm-sidebar');
148                  let item  = sidebar.children(".gchart[data-id=" + e.target.feature.id + "]");
149                  item.addClass('messagebox');
150                  sidebar.scrollTo(item);
151                })
152                .on('popupclose', function () {
153                  $('.osm-sidebar').children(".gchart")
154                    .removeClass('messagebox');
155                });
156            },
157            onEachFeature: function (feature, layer) {
158              if (feature.properties.polyline) {
159                let pline = L.polyline(feature.properties.polyline.points, feature.properties.polyline.options);
160                markers.addLayer(pline);
161              }
162              layer.bindPopup(feature.properties.summary);
163              let myclass = feature.valid ? 'gchart' : 'border border-danger';
164              sidebar += `<li class="${myclass}" data-id=${feature.id}>${feature.properties.summary}</li>`;
165            },
166          });
167        })
168        .fail(function (jqXHR, textStatus, errorThrown) {
169          console.log(jqXHR, textStatus, errorThrown);
170        })
171        .always(function (data_jqXHR, textStatus, jqXHR_errorThrown) {
172          switch (jqXHR_errorThrown.status) {
173            case 200: // Success
174              $(domObj).append(sidebar);
175              markers.addLayer(geoJsonLayer);
176              map
177                .addControl(new resetControl())
178                .addLayer(markers)
179                .fitBounds(markers.getBounds().pad(0.2));
180              if (zoom) {
181                map.setView(markers.getBounds().getCenter(), zoom);
182              }
183              break;
184            case 204: // No data
185              map.fitWorld();
186              $(domObj).append('<div class="bg-info text-white">' + baseData.I18N.noData + '</div>');
187              break;
188            default: // Anything else
189              map.fitWorld();
190              $(domObj).append('<div class="bg-danger text-white">' + baseData.I18N.error + '</div>');
191          }
192          $(domObj).slideDown(300);
193        });
194    };
195
196    /**
197     *
198     * @param elem
199     * @returns {$}
200     */
201
202    $.fn.scrollTo = function (elem) {
203      let _this = $(this);
204      _this.animate({
205        scrollTop: elem.offset().top - _this.offset().top + _this.scrollTop()
206      });
207      return this;
208    };
209
210    /**
211     *
212     * @param reference string
213     * @param mapType string
214     * @param generations integer
215     * @private
216     */
217    let _initialize = function (reference, mapType, generations) {
218      // Activate marker popup when sidebar entry clicked
219      $(function () {
220        $('.osm-sidebar')
221        // open marker popup if sidebar event is clicked
222          .on('click', '.gchart', function (e) {
223            // first close any existing
224            map.closePopup();
225            let eventId = $(this).data('id');
226            //find the marker corresponding to the clicked event
227            let mkrLayer = markers.getLayers().filter(function (v) {
228              return typeof(v.feature) !== 'undefined' && v.feature.id === eventId;
229            });
230            let mkr = mkrLayer.pop();
231            // Unfortunately zoomToShowLayer zooms to maxZoom
232            // when all marker in a cluster have exactly the
233            // same co-ordinates
234            markers.zoomToShowLayer(mkr, function (e) {
235              mkr.openPopup();
236            });
237            return false;
238          })
239          .on('click', 'a', function (e) { // stop click on a person also opening the popup
240            e.stopPropagation();
241          });
242      });
243
244      _drawMap();
245      _addLayer(reference, mapType, generations);
246    };
247
248    return {
249      /**
250       *
251       * @param reference string
252       * @param mapType string
253       * @param generations integer
254       */
255      drawMap: function (reference, mapType, generations) {
256        mapType     = typeof mapType !== 'undefined' ? mapType : 'individual';
257        generations = typeof generations !== 'undefined' ? generations : null;
258        _initialize(reference, mapType, generations);
259      }
260    };
261  })();
262
263    WT_OSM.drawMap(<?= json_encode($individual->xref()) ?>, <?= json_encode($type) ?>, <?= json_encode($generations ?? null) ?>);
264</script>
265<?php View::endpush() ?>
266