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