]> git.openstreetmap.org Git - nominatim-ui.git/blob - dist/assets/js/nominatim-ui.js
54eaa75116be30c9c5d6896ede7159e3b468c618
[nominatim-ui.git] / dist / assets / js / nominatim-ui.js
1 'use strict';
2
3 var map;
4 var last_click_latlng;
5
6 // *********************************************************
7 // DEFAULTS
8 // *********************************************************
9
10 var Nominatim_Config_Defaults = {
11   Nominatim_API_Endpoint: 'http://localhost/nominatim/',
12   Images_Base_Url: '/mapicons/',
13   Search_AreaPolygons: 1,
14   Reverse_Default_Search_Zoom: 18,
15   Map_Default_Lat: 20.0,
16   Map_Default_Lon: 0.0,
17   Map_Default_Zoom: 2,
18   Map_Tile_URL: 'https://{s}.tile.osm.org/{z}/{x}/{y}.png',
19   Map_Tile_Attribution: '<a href="https://osm.org/copyright">OpenStreetMap contributors</a>'
20 };
21
22 // *********************************************************
23 // HELPERS
24 // *********************************************************
25
26
27 function get_config_value(str, default_val) {
28   var value = ((typeof Nominatim_Config !== 'undefined')
29                && (typeof Nominatim_Config[str] !== 'undefined'))
30     ? Nominatim_Config[str]
31     : Nominatim_Config_Defaults[str];
32   return (typeof value !== 'undefined' ? value : default_val);
33 }
34
35 function parse_and_normalize_geojson_string(part) {
36   // normalize places the geometry into a featurecollection, similar to
37   // https://github.com/mapbox/geojson-normalize
38   var parsed_geojson = {
39     type: 'FeatureCollection',
40     features: [
41       {
42         type: 'Feature',
43         geometry: part,
44         properties: {}
45       }
46     ]
47   };
48   return parsed_geojson;
49 }
50
51 function map_link_to_osm() {
52   var zoom = map.getZoom();
53   var lat = map.getCenter().lat;
54   var lng = map.getCenter().lng;
55   return 'https://openstreetmap.org/#map=' + zoom + '/' + lat + '/' + lng;
56 }
57
58 function map_viewbox_as_string() {
59   var bounds = map.getBounds();
60   var west = bounds.getWest();
61   var east = bounds.getEast();
62
63   if ((east - west) >= 360) { // covers more than whole planet
64     west = map.getCenter().lng - 179.999;
65     east = map.getCenter().lng + 179.999;
66   }
67   east = L.latLng(77, east).wrap().lng;
68   west = L.latLng(77, west).wrap().lng;
69
70   return [
71     west.toFixed(5), // left
72     bounds.getNorth().toFixed(5), // top
73     east.toFixed(5), // right
74     bounds.getSouth().toFixed(5) // bottom
75   ].join(',');
76 }
77
78
79 // *********************************************************
80 // PAGE HELPERS
81 // *********************************************************
82
83 function generate_full_api_url(endpoint_name, params) {
84   //
85   // `&a=&b=&c=1` => '&c=1'
86   var param_names = Object.keys(params);
87   for (var i = 0; i < param_names.length; i += 1) {
88     var val = params[param_names[i]];
89     if (typeof (val) === 'undefined' || val === '' || val === null) {
90       delete params[param_names[i]];
91     }
92   }
93
94   var api_url = get_config_value('Nominatim_API_Endpoint') + endpoint_name + '.php?'
95                   + $.param(params);
96   return api_url;
97 }
98
99 function update_last_updated(endpoint_name, params) {
100   if (endpoint_name === 'status') return;
101
102   var api_url = generate_full_api_url(endpoint_name, params);
103   $('#last-updated').show();
104
105   $('#api-request a').attr('href', api_url);
106   $('#api-request').show();
107
108   if (endpoint_name === 'search' || endpoint_name === 'reverse') {
109     $('#api-request-debug a').attr('href', api_url + '&debug=1');
110     $('#api-request-debug').show();
111   } else {
112     $('#api-request-debug').hide();
113   }
114 }
115
116 function fetch_from_api(endpoint_name, params, callback) {
117   var api_url = generate_full_api_url(endpoint_name, params);
118   $.get(api_url, function (data) {
119     if (endpoint_name !== 'status') {
120       update_last_updated(endpoint_name, params);
121     }
122     callback(data);
123   });
124 }
125
126 function update_data_date() {
127   fetch_from_api('status', { format: 'json' }, function (data) {
128     $('#last-updated').show();
129     $('#data-date').text(data.data_updated);
130   });
131 }
132
133 function render_template(el, template_name, page_context) {
134   var template_source = $('#' + template_name).text();
135   var template = Handlebars.compile(template_source);
136   var html = template(page_context);
137   el.html(html);
138 }
139
140 function update_html_title(title) {
141   var prefix = '';
142   if (title && title.length > 1) {
143     prefix = title + ' | ';
144   }
145   $('head title').text(prefix + 'OpenStreetMap Nominatim');
146 }
147
148 function show_error(html) {
149   $('#error-overlay').html(html).show();
150 }
151
152 function hide_error() {
153   $('#error-overlay').empty().hide();
154 }
155
156
157 jQuery(document).ready(function () {
158   hide_error();
159
160   $('#last-updated').hide();
161
162   $(document).ajaxStart(function () {
163     $('#loading').fadeIn('fast');
164   }).ajaxComplete(function () {
165     $('#loading').fadeOut('fast');
166   }).ajaxError(function (event, jqXHR, ajaxSettings/* , thrownError */) {
167     // console.log(thrownError);
168     // console.log(ajaxSettings);
169     var url = ajaxSettings.url;
170     show_error('Error fetching results from <a href="' + url + '">' + url + '</a>');
171   });
172 });
173 // *********************************************************
174 // DETAILS PAGE
175 // *********************************************************
176
177
178 function init_map_on_detail_page(lat, lon, geojson) {
179   var attribution = get_config_value('Map_Tile_Attribution') || null;
180   map = new L.map('map', {
181     // center: [nominatim_map_init.lat, nominatim_map_init.lon],
182     // zoom:   nominatim_map_init.zoom,
183     attributionControl: (attribution && attribution.length),
184     scrollWheelZoom: true, // !L.Browser.touch,
185     touchZoom: false
186   });
187
188   L.tileLayer(get_config_value('Map_Tile_URL'), {
189     // moved to footer
190     // '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
191     attribution: attribution
192   }).addTo(map);
193
194   // var layerGroup = new L.layerGroup().addTo(map);
195
196   var circle = L.circleMarker([lat, lon], {
197     radius: 10, weight: 2, fillColor: '#ff7800', color: 'blue', opacity: 0.75
198   });
199   map.addLayer(circle);
200
201   if (geojson) {
202     var geojson_layer = L.geoJson(
203       // https://leafletjs.com/reference-1.0.3.html#path-option
204       parse_and_normalize_geojson_string(geojson),
205       {
206         style: function () {
207           return { interactive: false, color: 'blue' };
208         }
209       }
210     );
211     map.addLayer(geojson_layer);
212     map.fitBounds(geojson_layer.getBounds());
213   } else {
214     map.setView([lat, lon], 10);
215   }
216
217   var osm2 = new L.TileLayer(
218     get_config_value('Map_Tile_URL'),
219     {
220       minZoom: 0,
221       maxZoom: 13,
222       attribution: (get_config_value('Map_Tile_Attribution') || null)
223     }
224   );
225   (new L.Control.MiniMap(osm2, { toggleDisplay: true })).addTo(map);
226 }
227
228
229 function details_page_load() {
230
231   var search_params = new URLSearchParams(window.location.search);
232   // var place_id = search_params.get('place_id');
233
234   var api_request_params = {
235     place_id: search_params.get('place_id'),
236     osmtype: search_params.get('osmtype'),
237     osmid: search_params.get('osmid'),
238     class: search_params.get('class'),
239     keywords: search_params.get('keywords'),
240     addressdetails: 1,
241     hierarchy: (search_params.get('hierarchy') === '1' ? 1 : 0),
242     group_hierarchy: 1,
243     polygon_geojson: 1,
244     format: 'json'
245   };
246
247   if (api_request_params.place_id || (api_request_params.osmtype && api_request_params.osmid)) {
248     fetch_from_api('details', api_request_params, function (aFeature) {
249       var context = { aPlace: aFeature, base_url: window.location.search };
250
251       render_template($('main'), 'detailspage-template', context);
252       if (api_request_params.place_id) {
253         update_html_title('Details for ' + api_request_params.place_id);
254       } else {
255         update_html_title('Details for ' + api_request_params.osmtype + api_request_params.osmid);
256       }
257
258       update_data_date();
259
260       var lat = aFeature.centroid.coordinates[1];
261       var lon = aFeature.centroid.coordinates[0];
262       init_map_on_detail_page(lat, lon, aFeature.geometry);
263     });
264   } else {
265     render_template($('main'), 'detailspage-index-template');
266   }
267
268   $('#form-by-type-and-id,#form-by-osm-url').on('submit', function (e) {
269     e.preventDefault();
270
271     var val = $(this).find('input[type=edit]').val();
272     var matches = val.match(/^\s*([NWR])(\d+)\s*$/i);
273
274     if (!matches) {
275       matches = val.match(/\/(relation|way|node)\/(\d+)\s*$/);
276     }
277
278     if (matches) {
279       $(this).find('input[name=osmtype]').val(matches[1].charAt(0).toUpperCase());
280       $(this).find('input[name=osmid]').val(matches[2]);
281       $(this).get(0).submit();
282     } else {
283       alert('invalid input');
284     }
285   });
286 }
287
288 // *********************************************************
289 // FORWARD/REVERSE SEARCH PAGE
290 // *********************************************************
291
292
293 function display_map_position(mouse_lat_lng) {
294   //
295   if (mouse_lat_lng) {
296     mouse_lat_lng = map.wrapLatLng(mouse_lat_lng);
297   }
298
299   var html_mouse = 'mouse position: -';
300   if (mouse_lat_lng) {
301     html_mouse = 'mouse position: '
302                   + [mouse_lat_lng.lat.toFixed(5), mouse_lat_lng.lng.toFixed(5)].join(',');
303   }
304   var html_click = 'last click: -';
305   if (last_click_latlng) {
306     html_click = 'last click: '
307                   + [last_click_latlng.lat.toFixed(5), last_click_latlng.lng.toFixed(5)].join(',');
308   }
309
310   var html_center = 'map center: '
311     + map.getCenter().lat.toFixed(5) + ',' + map.getCenter().lng.toFixed(5)
312     + ' <a target="_blank" href="' + map_link_to_osm() + '">view on osm.org</a>';
313
314   var html_zoom = 'map zoom: ' + map.getZoom();
315   var html_viewbox = 'viewbox: ' + map_viewbox_as_string();
316
317   $('#map-position-inner').html([
318     html_center,
319     html_zoom,
320     html_viewbox,
321     html_click,
322     html_mouse
323   ].join('<br/>'));
324
325   var center_lat_lng = map.wrapLatLng(map.getCenter());
326   var reverse_params = {
327     lat: center_lat_lng.lat.toFixed(5),
328     lon: center_lat_lng.lng.toFixed(5)
329     // zoom: 2,
330     // format: 'html'
331   };
332   $('#switch-to-reverse').attr('href', 'reverse.html?' + $.param(reverse_params));
333
334   $('input.api-param-setting').trigger('change');
335 }
336
337 function init_map_on_search_page(is_reverse_search, nominatim_results, request_lat,
338   request_lon, init_zoom) {
339
340   var attribution = get_config_value('Map_Tile_Attribution') || null;
341   map = new L.map('map', {
342     // center: [nominatim_map_init.lat, nominatim_map_init.lon],
343     // zoom:   nominatim_map_init.zoom,
344     attributionControl: (attribution && attribution.length),
345     scrollWheelZoom: true, // !L.Browser.touch,
346     touchZoom: false
347   });
348
349
350   L.tileLayer(get_config_value('Map_Tile_URL'), {
351     // moved to footer
352     // '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
353     attribution: attribution
354   }).addTo(map);
355
356   // console.log(Nominatim_Config);
357
358   map.setView([request_lat, request_lon], init_zoom);
359
360   var osm2 = new L.TileLayer(get_config_value('Map_Tile_URL'), {
361     minZoom: 0,
362     maxZoom: 13,
363     attribution: attribution
364   });
365   new L.Control.MiniMap(osm2, { toggleDisplay: true }).addTo(map);
366
367   if (is_reverse_search) {
368     // We don't need a marker, but an L.circle instance changes radius once you zoom in/out
369     var cm = L.circleMarker(
370       [request_lat, request_lon],
371       {
372         radius: 5,
373         weight: 2,
374         fillColor: '#ff7800',
375         color: 'red',
376         opacity: 0.75,
377         zIndexOffset: 100,
378         clickable: false
379       }
380     );
381     cm.addTo(map);
382   } else {
383     var search_params = new URLSearchParams(window.location.search);
384     var viewbox = search_params.get('viewbox');
385     if (viewbox) {
386       var coords = viewbox.split(','); // <x1>,<y1>,<x2>,<y2>
387       var bounds = L.latLngBounds([coords[1], coords[0]], [coords[3], coords[2]]);
388       L.rectangle(bounds, {
389         color: '#69d53e',
390         weight: 3,
391         dashArray: '5 5',
392         opacity: 0.8,
393         fill: false
394       }).addTo(map);
395     }
396   }
397
398   var MapPositionControl = L.Control.extend({
399     options: {
400       position: 'topright'
401     },
402     onAdd: function (/* map */) {
403       var container = L.DomUtil.create('div', 'my-custom-control');
404
405       $(container).text('show map bounds')
406         .addClass('leaflet-bar btn btn-sm btn-outline-secondary')
407         .on('click', function (e) {
408           e.preventDefault();
409           e.stopPropagation();
410           $('#map-position').show();
411           $(container).hide();
412         });
413       $('#map-position-close a').on('click', function (e) {
414         e.preventDefault();
415         e.stopPropagation();
416         $('#map-position').hide();
417         $(container).show();
418       });
419
420       return container;
421     }
422   });
423
424   map.addControl(new MapPositionControl());
425
426
427
428
429
430   function update_viewbox_field() {
431     // hidden HTML field
432     $('input[name=viewbox]')
433       .val($('input#use_viewbox')
434         .prop('checked') ? map_viewbox_as_string() : '');
435   }
436
437   map.on('move', function () {
438     display_map_position();
439     update_viewbox_field();
440   });
441
442   map.on('mousemove', function (e) {
443     display_map_position(e.latlng);
444   });
445
446   map.on('click', function (e) {
447     last_click_latlng = e.latlng;
448     display_map_position();
449   });
450
451   map.on('load', function () {
452     display_map_position();
453   });
454
455   $('input#use_viewbox').on('change', function () {
456     update_viewbox_field();
457   });
458
459   $('input#option_bounded').on('change', function () {
460     $('input[name=bounded]')
461       .val($('input#option_bounded')
462         .prop('checked') ? '1' : '');
463   });
464
465   $('input#option_dedupe').on('change', function () {
466     $('input[name=dedupe]')
467       .val($('input#option_dedupe')
468         .prop('checked') ? '' : '0');
469   });
470
471   $('input[data-api-param]').on('change', function (e) {
472     $('input[name=' + $(e.target).data('api-param') + ']').val(e.target.value);
473   });
474
475
476   function get_result_element(position) {
477     return $('.result').eq(position);
478   }
479   // function marker_for_result(result) {
480   //   return L.marker([result.lat, result.lon], { riseOnHover: true, title: result.name });
481   // }
482   function circle_for_result(result) {
483     var cm_style = {
484       radius: 10,
485       weight: 2,
486       fillColor: '#ff7800',
487       color: 'blue',
488       opacity: 0.75,
489       clickable: !is_reverse_search
490     };
491     return L.circleMarker([result.lat, result.lon], cm_style);
492   }
493
494   var layerGroup = (new L.layerGroup()).addTo(map);
495
496   function highlight_result(position, bool_focus) {
497     var result = nominatim_results[position];
498     if (!result) { return; }
499     var result_el = get_result_element(position);
500
501     $('.result').removeClass('highlight');
502     result_el.addClass('highlight');
503
504     layerGroup.clearLayers();
505
506     if (result.lat) {
507       var circle = circle_for_result(result);
508       circle.on('click', function () {
509         highlight_result(position);
510       });
511       layerGroup.addLayer(circle);
512     }
513
514     if (result.boundingbox) {
515       var bbox = [
516         [result.boundingbox[0] * 1, result.boundingbox[2] * 1],
517         [result.boundingbox[1] * 1, result.boundingbox[3] * 1]
518       ];
519       map.fitBounds(bbox);
520
521       if (result.geojson && result.geojson.type.match(/(Polygon)|(Line)/)) {
522         //
523         var geojson_layer = L.geoJson(
524           parse_and_normalize_geojson_string(result.geojson),
525           {
526             // https://leafletjs.com/reference-1.0.3.html#path-option
527             style: function (/* feature */) {
528               return { interactive: false, color: 'blue' };
529             }
530           }
531         );
532         layerGroup.addLayer(geojson_layer);
533       }
534       // else {
535       //     var layer = L.rectangle(bounds, {color: "#ff7800", weight: 1} );
536       //     layerGroup.addLayer(layer);
537       // }
538     } else {
539       var result_coord = L.latLng(result.lat, result.lon);
540       if (result_coord) {
541         if (is_reverse_search) {
542           // console.dir([result_coord, [request_lat, request_lon]]);
543           // make sure the search coordinates are in the map view as well
544           map.fitBounds(
545             [result_coord, [request_lat, request_lon]],
546             {
547               padding: [50, 50],
548               maxZoom: map.getZoom()
549             }
550           );
551         } else {
552           map.panTo(result_coord, result.zoom || get_config_value('Map_Default_Zoom'));
553         }
554       }
555     }
556     if (bool_focus) {
557       $('#map').focus();
558     }
559   }
560
561
562   $('.result').on('click', function () {
563     highlight_result($(this).data('position'), true);
564   });
565
566   if (is_reverse_search) {
567     map.on('click', function (e) {
568       $('form input[name=lat]').val(e.latlng.lat);
569       $('form input[name=lon]').val(e.latlng.wrap().lng);
570       $('form').submit();
571     });
572
573     $('#switch-coords').on('click', function (e) {
574       e.preventDefault();
575       e.stopPropagation();
576       var lat = $('form input[name=lat]').val();
577       var lon = $('form input[name=lon]').val();
578       $('form input[name=lat]').val(lon);
579       $('form input[name=lon]').val(lat);
580       $('form').submit();
581     });
582   }
583
584   highlight_result(0, false);
585
586   // common mistake is to copy&paste latitude and longitude into the 'lat' search box
587   $('form input[name=lat]').on('change', function () {
588     var coords_split = $(this).val().split(',');
589     if (coords_split.length === 2) {
590       $(this).val(L.Util.trim(coords_split[0]));
591       $(this).siblings('input[name=lon]').val(L.Util.trim(coords_split[1]));
592     }
593   });
594 }
595
596
597
598 function search_page_load() {
599
600   var is_reverse_search = window.location.pathname.match(/reverse/);
601
602   var search_params = new URLSearchParams(window.location.search);
603
604   // return view('search', [
605   //     'sQuery' => $sQuery,
606   //     'bAsText' => '',
607   //     'sViewBox' => '',
608   //     'aSearchResults' => $aSearchResults,
609   //     'sMoreURL' => 'example.com',
610   //     'sDataDate' => $this->fetch_status_date(),
611   //     'sApiURL' => $url
612   // ]);
613
614   var api_request_params;
615   var context;
616
617   if (is_reverse_search) {
618     api_request_params = {
619       lat: search_params.get('lat'),
620       lon: search_params.get('lon'),
621       zoom: (search_params.get('zoom') > 1
622         ? search_params.get('zoom')
623         : get_config_value('Reverse_Default_Search_Zoom')),
624       format: 'jsonv2'
625     };
626
627     context = {
628       // aPlace: aPlace,
629       fLat: api_request_params.lat,
630       fLon: api_request_params.lon,
631       iZoom: (search_params.get('zoom') > 1
632         ? api_request_params.zoom
633         : get_config_value('Reverse_Default_Search_Zoom'))
634     };
635
636     update_html_title();
637     if (api_request_params.lat && api_request_params.lon) {
638
639       fetch_from_api('reverse', api_request_params, function (aPlace) {
640
641         if (aPlace.error) {
642           aPlace = null;
643         }
644
645         context.bSearchRan = true;
646         context.aPlace = aPlace;
647
648         render_template($('main'), 'reversepage-template', context);
649         update_html_title('Reverse result for '
650                             + api_request_params.lat
651                             + ','
652                             + api_request_params.lon);
653
654         init_map_on_search_page(
655           is_reverse_search,
656           [aPlace],
657           api_request_params.lat,
658           api_request_params.lon,
659           api_request_params.zoom
660         );
661
662         update_data_date();
663       });
664     } else {
665       render_template($('main'), 'reversepage-template', context);
666
667       init_map_on_search_page(
668         is_reverse_search,
669         [],
670         get_config_value('Map_Default_Lat'),
671         get_config_value('Map_Default_Lon'),
672         get_config_value('Map_Default_Zoom')
673       );
674     }
675
676   } else {
677     api_request_params = {
678       q: search_params.get('q'),
679       street: search_params.get('street'),
680       city: search_params.get('city'),
681       county: search_params.get('county'),
682       state: search_params.get('state'),
683       country: search_params.get('country'),
684       postalcode: search_params.get('postalcode'),
685       polygon_geojson: get_config_value('Search_AreaPolygons', false) ? 1 : 0,
686       viewbox: search_params.get('viewbox'),
687       bounded: search_params.get('bounded'),
688       dedupe: search_params.get('dedupe'),
689       'accept-language': search_params.get('accept-language'),
690       countrycodes: search_params.get('countrycodes'),
691       limit: search_params.get('limit'),
692       polygon_threshold: search_params.get('polygon_threshold'),
693       exclude_place_ids: search_params.get('exclude_place_ids'),
694       format: 'jsonv2'
695     };
696
697     context = {
698       sQuery: api_request_params.q,
699       sViewBox: search_params.get('viewbox'),
700       sBounded: search_params.get('bounded'),
701       sDedupe: search_params.get('dedupe'),
702       sLang: search_params.get('accept-language'),
703       sCCode: search_params.get('countrycodes'),
704       sLimit: search_params.get('limit'),
705       sPolyThreshold: search_params.get('polygon_threshold'),
706       env: {}
707     };
708
709     if (api_request_params.street || api_request_params.city || api_request_params.county
710       || api_request_params.state || api_request_params.country || api_request_params.postalcode) {
711       context.hStructured = {
712         street: api_request_params.street,
713         city: api_request_params.city,
714         county: api_request_params.county,
715         state: api_request_params.state,
716         country: api_request_params.country,
717         postalcode: api_request_params.postalcode
718       };
719     }
720
721     if (api_request_params.q || context.hStructured) {
722
723       fetch_from_api('search', api_request_params, function (aResults) {
724
725         context.bSearchRan = true;
726         context.aSearchResults = aResults;
727
728         // lonvia wrote: https://github.com/osm-search/nominatim-ui/issues/24
729         // I would suggest to remove the guessing and always show the link. Nominatim only returns
730         // one or two results when it believes the result to be a good enough match.
731         // if (aResults.length >= 10) {
732         var aExcludePlaceIds = [];
733         if (search_params.has('exclude_place_ids')) {
734           aExcludePlaceIds = search_params.get('exclude_place_ids').split(',');
735         }
736         for (var i = 0; i < aResults.length; i += 1) {
737           aExcludePlaceIds.push(aResults[i].place_id);
738         }
739         var parsed_url = new URLSearchParams(window.location.search);
740         parsed_url.set('exclude_place_ids', aExcludePlaceIds.join(','));
741         context.sMoreURL = '?' + parsed_url.toString();
742
743         render_template($('main'), 'searchpage-template', context);
744         update_html_title('Result for ' + api_request_params.q);
745
746         init_map_on_search_page(
747           is_reverse_search,
748           aResults,
749           get_config_value('Map_Default_Lat'),
750           get_config_value('Map_Default_Lon'),
751           get_config_value('Map_Default_Zoom')
752         );
753
754         $('#q').focus();
755
756         update_data_date();
757       });
758     } else {
759       render_template($('main'), 'searchpage-template', context);
760
761       init_map_on_search_page(
762         is_reverse_search,
763         [],
764         get_config_value('Map_Default_Lat'),
765         get_config_value('Map_Default_Lon'),
766         get_config_value('Map_Default_Zoom')
767       );
768     }
769   }
770 }
771
772
773 // *********************************************************
774 // DELETABLE PAGE
775 // *********************************************************
776
777 function deletable_page_load() {
778
779   var api_request_params = {
780     format: 'json'
781   };
782
783   fetch_from_api('deletable', api_request_params, function (aPolygons) {
784     var context = { aPolygons: aPolygons };
785
786     render_template($('main'), 'deletable-template', context);
787     update_html_title('Deletable objects');
788
789     update_data_date();
790   });
791 }
792 // *********************************************************
793 // BROKEN POLYGON PAGE
794 // *********************************************************
795
796 function polygons_page_load() {
797   //
798   var api_request_params = {
799     format: 'json'
800   };
801
802   fetch_from_api('polygons', api_request_params, function (aPolygons) {
803     var context = { aPolygons: aPolygons };
804
805     render_template($('main'), 'polygons-template', context);
806     update_html_title('Broken polygons');
807
808     update_data_date();
809   });
810 }
811 jQuery(document).ready(function () {
812   var myhistory = [];
813
814   function parse_url_and_load_page() {
815     // 'search', 'reverse', 'details'
816     var pagename = window.location.pathname.replace('.html', '').replace(/^.*\//, '');
817
818     if (pagename === '') pagename = 'search';
819
820     $('body').attr('id', pagename + '-page');
821
822     if (pagename === 'search' || pagename === 'reverse') {
823       search_page_load();
824     } else if (pagename === 'details') {
825       details_page_load();
826     } else if (pagename === 'deletable') {
827       deletable_page_load();
828     } else if (pagename === 'polygons') {
829       polygons_page_load();
830     }
831   }
832
833   function is_relative_url(url) {
834     if (!url) return false;
835     if (url.indexOf('?') === 0) return true;
836     if (url.indexOf('/') === 0) return true;
837     if (url.indexOf('#') === 0) return false;
838     if (url.match(/^http/)) return false;
839     if (!url.match(/\.html/)) return true;
840
841     return false;
842   }
843
844   // remove any URL paramters with empty values
845   // '&empty=&filled=value' => 'filled=value'
846   function clean_up_url_parameters(url) {
847     var url_params = new URLSearchParams(url);
848     var to_delete = []; // deleting inside loop would skip iterations
849     url_params.forEach(function (value, key) {
850       if (value === '') to_delete.push(key);
851     });
852     for (var i = 0; i < to_delete.length; i += 1) {
853       url_params.delete(to_delete[i]);
854     }
855     return url_params.toString();
856   }
857
858   parse_url_and_load_page();
859
860   // load page after form submit
861   $(document).on('submit', 'form', function (e) {
862     e.preventDefault();
863
864     var target_url = $(this).serialize();
865     target_url = clean_up_url_parameters(target_url);
866
867     window.history.pushState(myhistory, '', '?' + target_url);
868
869     parse_url_and_load_page();
870   });
871
872   // load page after click on relative URL
873   $(document).on('click', 'a', function (e) {
874     var target_url = $(this).attr('href');
875     if (!is_relative_url(target_url)) return;
876     if ($(this).parents('#last-updated').length !== 0) return;
877
878     e.preventDefault();
879     e.stopPropagation();
880
881     window.history.pushState(myhistory, '', target_url);
882
883     parse_url_and_load_page();
884   });
885
886   // deal with back-button and other user action
887   window.onpopstate = function () {
888     parse_url_and_load_page();
889   };
890 });
891