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