xref: /webtrees/resources/views/modules/pedigree-map/chart.phtml (revision 36409e74031e7511ee5eb54dedf4f1503b5937b5)
1<?php
2use Fisharebest\Webtrees\I18N;
3use Fisharebest\Webtrees\Individual;
4use Fisharebest\Webtrees\View;
5
6/**
7 * @var Individual $individual
8 */
9?>
10
11
12<div class="py-4">
13    <div class="row gchart osm-wrapper">
14        <div id="osm-map" class="col-sm-9 wt-ajax-load osm-user-map" dir="ltr"></div>
15        <ul class="col-sm-3 osm-sidebar wt-page-options-value list-unstyled p-0"></ul>
16    </div>
17</div>
18
19<?php View::push('styles') ?>
20<style>
21    .osm-wrapper, .osm-user-map {
22        height: 75vh
23    }
24
25    .osm-sidebar {
26        height: 100%;
27        overflow-y: auto;
28        padding: 0;
29        margin: 0;
30        border: 0;
31        display: none;
32        font-size: small;
33    }
34
35    .osm-sidebar .gchart {
36        margin: 1px;
37        padding: 2px
38    }
39
40    .osm-sidebar .gchart img {
41        height: 15px;
42        width: 25px
43    }
44
45    .osm-sidebar .border-danger:hover {
46        cursor: not-allowed
47    }
48</style>
49<?php View::endpush() ?>
50
51<?php View::push('javascript') ?>
52<script type="application/javascript">
53  "use strict";
54
55  window.WT_OSM = (function() {
56    let baseData = {
57      minZoom: 2,
58      providerName: "OpenStreetMap.Mapnik",
59      providerOptions: [],
60    };
61
62    let map          = null;
63    let zoom         = null;
64    let markers      = L.markerClusterGroup({
65      showCoverageOnHover: false
66    });
67
68    let resetControl = L.Control.extend({
69      options: {
70        position: 'topleft'
71      },
72
73      onAdd: function (map) {
74        let container     = L.DomUtil.create('div', 'leaflet-bar leaflet-control leaflet-control-custom');
75        container.onclick = function () {
76          if (zoom) {
77            map.flyTo(markers.getBounds().getCenter(), zoom);
78          } else {
79            map.flyToBounds(markers.getBounds().pad(0.2));
80          }
81          let sidebar = $(".osm-sidebar");
82          sidebar.scrollTo(sidebar.children(":first"));
83
84          return false;
85        };
86        let anchor   = L.DomUtil.create('a', 'leaflet-control-reset', container);
87        let reset = <?= json_encode(I18N::translate('Reset to initial map state')) ?>;
88        anchor.href  = '#';
89        anchor.title = reset;
90        anchor.role  = 'button';
91        $(anchor).attr('aria-label', 'reset');
92        let image = L.DomUtil.create('i', 'fas fa-redo', anchor);
93        image.alt = reset;
94
95        return container;
96      },
97    });
98
99    /**
100     *
101     * @private
102     */
103    let _drawMap = function () {
104      map = L.map('osm-map', {
105        center     : [0, 0],
106        minZoom    : baseData.minZoom, // maxZoom set by leaflet-providers.js
107        zoomControl: false, // remove default
108      });
109      L.tileLayer.provider(baseData.providerName, baseData.providerOptions).addTo(map);
110      L.control.zoom({ // Add zoom with localised text
111        zoomInTitle : <?= json_encode(I18N::translate('Zoom in')) ?>,
112        zoomOutTitle: <?= json_encode(I18N::translate('Zoom out')) ?>,
113      }).addTo(map);
114    };
115
116    /**
117     * @param Generations
118     * @private
119     */
120    let _addLayer = function (Generations) {
121      let geoJsonLayer;
122      let domObj  = '.osm-sidebar';
123      let sidebar = '';
124
125      $.getJSON(<?= json_encode(route('module', ['module' => 'pedigree-map', 'action' => 'MapData', 'tree' => $individual->tree()->name(), 'xref' => $individual->xref()])) ?>, {
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">' + <?= json_encode(I18N::translate('No mappable items')) ?> + '</div>');
187              break;
188            default: // Anything else
189              map.fitWorld();
190              $(domObj).append('<div class="bg-danger text-white">' + <?= json_encode(I18N::translate('An unknown error occurred')) ?> + '</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     * @param generations integer
212     * @private
213     */
214    let _initialize = function (generations) {
215      // Activate marker popup when sidebar entry clicked
216      $(function () {
217        $('.osm-sidebar')
218        // open marker popup if sidebar event is clicked
219          .on('click', '.gchart', function (e) {
220            // first close any existing
221            map.closePopup();
222            let eventId = $(this).data('id');
223            //find the marker corresponding to the clicked event
224            let mkrLayer = markers.getLayers().filter(function (v) {
225              return typeof(v.feature) !== 'undefined' && v.feature.id === eventId;
226            });
227            let mkr = mkrLayer.pop();
228            // Unfortunately zoomToShowLayer zooms to maxZoom
229            // when all marker in a cluster have exactly the
230            // same co-ordinates
231            markers.zoomToShowLayer(mkr, function (e) {
232              mkr.openPopup();
233            });
234            return false;
235          })
236          .on('click', 'a', function (e) { // stop click on a person also opening the popup
237            e.stopPropagation();
238          });
239      });
240
241      _drawMap();
242      _addLayer(generations);
243    };
244
245    return {
246      /**
247       * @param generations integer
248       */
249      drawMap: function (generations) {
250        _initialize(generations);
251      }
252    };
253  })();
254
255    WT_OSM.drawMap(<?= json_encode($generations) ?>);
256</script>
257<?php View::endpush() ?>
258