]> git.openstreetmap.org Git - nominatim-ui.git/blob - dist/assets/js/nominatim-ui.js
Merge pull request #15 from mtmail/master
[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 fetch_from_api(endpoint_name, params, callback) {
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   if (endpoint_name !== 'status') {
97     $('#api-request-link').attr('href', api_url);
98   }
99   $.get(api_url, function (data) {
100     callback(data);
101   });
102 }
103
104 function update_data_date() {
105   fetch_from_api('status', { format: 'json' }, function (data) {
106     $('#data-date').text(data.data_updated);
107   });
108 }
109
110 function render_template(el, template_name, page_context) {
111   var template_source = $('#' + template_name).text();
112   var template = Handlebars.compile(template_source);
113   var html = template(page_context);
114   el.html(html);
115 }
116
117 function update_html_title(title) {
118   var prefix = '';
119   if (title && title.length > 1) {
120     prefix = title + ' | ';
121   }
122   $('head title').text(prefix + 'OpenStreetMap Nominatim');
123 }
124
125 function show_error(html) {
126   $('#error-overlay').html(html).show();
127 }
128
129 function hide_error() {
130   $('#error-overlay').empty().hide();
131 }
132
133
134 $(document).ajaxError(function (event, jqXHR, ajaxSettings/* , thrownError */) {
135   // console.log(thrownError);
136   // console.log(ajaxSettings);
137   var url = ajaxSettings.url;
138   show_error('Error fetching results from <a href="' + url + '">' + url + '</a>');
139 });
140
141
142 jQuery(document).ready(function () {
143   hide_error();
144 });
145 // *********************************************************
146 // DETAILS PAGE
147 // *********************************************************
148
149
150 function init_map_on_detail_page(lat, lon, geojson) {
151   var attribution = get_config_value('Map_Tile_Attribution') || null;
152   map = new L.map('map', {
153     // center: [nominatim_map_init.lat, nominatim_map_init.lon],
154     // zoom:   nominatim_map_init.zoom,
155     attributionControl: (attribution && attribution.length),
156     scrollWheelZoom: true, // !L.Browser.touch,
157     touchZoom: false
158   });
159
160   L.tileLayer(get_config_value('Map_Tile_URL'), {
161     // moved to footer
162     // '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
163     attribution: attribution
164   }).addTo(map);
165
166   // var layerGroup = new L.layerGroup().addTo(map);
167
168   var circle = L.circleMarker([lat, lon], {
169     radius: 10, weight: 2, fillColor: '#ff7800', color: 'blue', opacity: 0.75
170   });
171   map.addLayer(circle);
172
173   if (geojson) {
174     var geojson_layer = L.geoJson(
175       // https://leafletjs.com/reference-1.0.3.html#path-option
176       parse_and_normalize_geojson_string(geojson),
177       {
178         style: function () {
179           return { interactive: false, color: 'blue' };
180         }
181       }
182     );
183     map.addLayer(geojson_layer);
184     map.fitBounds(geojson_layer.getBounds());
185   } else {
186     map.setView([lat, lon], 10);
187   }
188
189   var osm2 = new L.TileLayer(
190     get_config_value('Map_Tile_URL'),
191     {
192       minZoom: 0,
193       maxZoom: 13,
194       attribution: (get_config_value('Map_Tile_Attribution') || null)
195     }
196   );
197   (new L.Control.MiniMap(osm2, { toggleDisplay: true })).addTo(map);
198 }
199
200
201 jQuery(document).ready(function () {
202   if (!$('#details-page').length) { return; }
203
204   var search_params = new URLSearchParams(window.location.search);
205   // var place_id = search_params.get('place_id');
206
207   var api_request_params = {
208     place_id: search_params.get('place_id'),
209     osmtype: search_params.get('osmtype'),
210     osmid: search_params.get('osmid'),
211     keywords: search_params.get('keywords'),
212     addressdetails: 1,
213     hierarchy: (search_params.get('hierarchy') === '1' ? 1 : 0),
214     group_hierarchy: 1,
215     polygon_geojson: 1,
216     format: 'json'
217   };
218
219   if (api_request_params.place_id || (api_request_params.osmtype && api_request_params.osmid)) {
220     fetch_from_api('details', api_request_params, function (aFeature) {
221       var context = { aPlace: aFeature, base_url: window.location.search };
222
223       render_template($('main'), 'detailspage-template', context);
224       if (api_request_params.place_id) {
225         update_html_title('Details for ' + api_request_params.place_id);
226       } else {
227         update_html_title('Details for ' + api_request_params.osmtype + api_request_params.osmid);
228       }
229
230       update_data_date();
231
232       var lat = aFeature.centroid.coordinates[1];
233       var lon = aFeature.centroid.coordinates[0];
234       init_map_on_detail_page(lat, lon, aFeature.geometry);
235     });
236   } else {
237     render_template($('main'), 'detailspage-index-template');
238   }
239
240   $('#form-by-type-and-id,#form-by-osm-url').on('submit', function (e) {
241     e.preventDefault();
242
243     var val = $(this).find('input[type=edit]').val();
244     var matches = val.match(/^\s*([NWR])(\d+)\s*$/i);
245
246     if (!matches) {
247       matches = val.match(/\/(relation|way|node)\/(\d+)\s*$/);
248     }
249
250     if (matches) {
251       $(this).find('input[name=osmtype]').val(matches[1].charAt(0).toUpperCase());
252       $(this).find('input[name=osmid]').val(matches[2]);
253       $(this).get(0).submit();
254     } else {
255       alert('invalid input');
256     }
257   });
258 });
259
260 // *********************************************************
261 // FORWARD/REVERSE SEARCH PAGE
262 // *********************************************************
263
264
265 function display_map_position(mouse_lat_lng) {
266   //
267   if (mouse_lat_lng) {
268     mouse_lat_lng = map.wrapLatLng(mouse_lat_lng);
269   }
270
271   var html_mouse = 'mouse position: -';
272   if (mouse_lat_lng) {
273     html_mouse = 'mouse position: '
274                   + [mouse_lat_lng.lat.toFixed(5), mouse_lat_lng.lng.toFixed(5)].join(',');
275   }
276   var html_click = 'last click: -';
277   if (last_click_latlng) {
278     html_click = 'last click: '
279                   + [last_click_latlng.lat.toFixed(5), last_click_latlng.lng.toFixed(5)].join(',');
280   }
281
282   var html_center = 'map center: '
283     + map.getCenter().lat.toFixed(5) + ',' + map.getCenter().lng.toFixed(5)
284     + ' <a target="_blank" href="' + map_link_to_osm() + '">view on osm.org</a>';
285
286   var html_zoom = 'map zoom: ' + map.getZoom();
287   var html_viewbox = 'viewbox: ' + map_viewbox_as_string();
288
289   $('#map-position-inner').html([
290     html_center,
291     html_zoom,
292     html_viewbox,
293     html_click,
294     html_mouse
295   ].join('<br/>'));
296
297   var center_lat_lng = map.wrapLatLng(map.getCenter());
298   var reverse_params = {
299     lat: center_lat_lng.lat.toFixed(5),
300     lon: center_lat_lng.lng.toFixed(5)
301     // zoom: 2,
302     // format: 'html'
303   };
304   $('#switch-to-reverse').attr('href', 'reverse.html?' + $.param(reverse_params));
305
306   $('input#use_viewbox').trigger('change');
307 }
308
309 function init_map_on_search_page(is_reverse_search, nominatim_results, request_lat,
310   request_lon, init_zoom) {
311
312   var attribution = get_config_value('Map_Tile_Attribution') || null;
313   map = new L.map('map', {
314     // center: [nominatim_map_init.lat, nominatim_map_init.lon],
315     // zoom:   nominatim_map_init.zoom,
316     attributionControl: (attribution && attribution.length),
317     scrollWheelZoom: true, // !L.Browser.touch,
318     touchZoom: false
319   });
320
321
322   L.tileLayer(get_config_value('Map_Tile_URL'), {
323     // moved to footer
324     // '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
325     attribution: attribution
326   }).addTo(map);
327
328   // console.log(Nominatim_Config);
329
330   map.setView([request_lat, request_lon], init_zoom);
331
332   var osm2 = new L.TileLayer(get_config_value('Map_Tile_URL'), {
333     minZoom: 0,
334     maxZoom: 13,
335     attribution: attribution
336   });
337   new L.Control.MiniMap(osm2, { toggleDisplay: true }).addTo(map);
338
339   if (is_reverse_search) {
340     // We don't need a marker, but an L.circle instance changes radius once you zoom in/out
341     var cm = L.circleMarker(
342       [request_lat, request_lon],
343       {
344         radius: 5,
345         weight: 2,
346         fillColor: '#ff7800',
347         color: 'red',
348         opacity: 0.75,
349         zIndexOffset: 100,
350         clickable: false
351       }
352     );
353     cm.addTo(map);
354   } else {
355     var search_params = new URLSearchParams(window.location.search);
356     var viewbox = search_params.get('viewbox');
357     if (viewbox) {
358       var coords = viewbox.split(','); // <x1>,<y1>,<x2>,<y2>
359       var bounds = L.latLngBounds([coords[1], coords[0]], [coords[3], coords[2]]);
360       L.rectangle(bounds, {
361         color: '#69d53e',
362         weight: 3,
363         dashArray: '5 5',
364         opacity: 0.8,
365         fill: false
366       }).addTo(map);
367     }
368   }
369
370   var MapPositionControl = L.Control.extend({
371     options: {
372       position: 'topright'
373     },
374     onAdd: function (/* map */) {
375       var container = L.DomUtil.create('div', 'my-custom-control');
376
377       $(container).text('show map bounds')
378         .addClass('leaflet-bar btn btn-sm btn-outline-secondary')
379         .on('click', function (e) {
380           e.preventDefault();
381           e.stopPropagation();
382           $('#map-position').show();
383           $(container).hide();
384         });
385       $('#map-position-close a').on('click', function (e) {
386         e.preventDefault();
387         e.stopPropagation();
388         $('#map-position').hide();
389         $(container).show();
390       });
391
392       return container;
393     }
394   });
395
396   map.addControl(new MapPositionControl());
397
398
399
400
401
402   function update_viewbox_field() {
403     // hidden HTML field
404     $('input[name=viewbox]')
405       .val($('input#use_viewbox')
406         .prop('checked') ? map_viewbox_as_string() : '');
407   }
408
409   map.on('move', function () {
410     display_map_position();
411     update_viewbox_field();
412   });
413
414   map.on('mousemove', function (e) {
415     display_map_position(e.latlng);
416   });
417
418   map.on('click', function (e) {
419     last_click_latlng = e.latlng;
420     display_map_position();
421   });
422
423   map.on('load', function () {
424     display_map_position();
425   });
426
427   $('input#use_viewbox').on('change', function () {
428     update_viewbox_field();
429   });
430
431   $("input[name='query-selector']").click(function () {
432     var query_val = $("input[name='query-selector']:checked").val();
433     if (query_val === 'simple') {
434       $('div.form-group-simple').removeClass('hidden');
435       $('div.form-group-structured').addClass('hidden');
436       $('.form-group-structured').find('input:text').val('');
437     } else if (query_val === 'structured') {
438       console.log('here');
439       $('div.form-group-simple').addClass('hidden');
440       $('div.form-group-structured').removeClass('hidden');
441       $('.form-group-simple').find('input:text').val('');
442     }
443   });
444
445   function get_result_element(position) {
446     return $('.result').eq(position);
447   }
448   // function marker_for_result(result) {
449   //   return L.marker([result.lat, result.lon], { riseOnHover: true, title: result.name });
450   // }
451   function circle_for_result(result) {
452     var cm_style = {
453       radius: 10,
454       weight: 2,
455       fillColor: '#ff7800',
456       color: 'blue',
457       opacity: 0.75,
458       clickable: !is_reverse_search
459     };
460     return L.circleMarker([result.lat, result.lon], cm_style);
461   }
462
463   var layerGroup = (new L.layerGroup()).addTo(map);
464
465   function highlight_result(position, bool_focus) {
466     var result = nominatim_results[position];
467     if (!result) { return; }
468     var result_el = get_result_element(position);
469
470     $('.result').removeClass('highlight');
471     result_el.addClass('highlight');
472
473     layerGroup.clearLayers();
474
475     if (result.lat) {
476       var circle = circle_for_result(result);
477       circle.on('click', function () {
478         highlight_result(position);
479       });
480       layerGroup.addLayer(circle);
481     }
482
483     if (result.boundingbox) {
484       var bbox = [
485         [result.boundingbox[0] * 1, result.boundingbox[2] * 1],
486         [result.boundingbox[1] * 1, result.boundingbox[3] * 1]
487       ];
488       map.fitBounds(bbox);
489
490       if (result.geojson && result.geojson.type.match(/(Polygon)|(Line)/)) {
491         //
492         var geojson_layer = L.geoJson(
493           parse_and_normalize_geojson_string(result.geojson),
494           {
495             // https://leafletjs.com/reference-1.0.3.html#path-option
496             style: function (/* feature */) {
497               return { interactive: false, color: 'blue' };
498             }
499           }
500         );
501         layerGroup.addLayer(geojson_layer);
502       }
503       // else {
504       //     var layer = L.rectangle(bounds, {color: "#ff7800", weight: 1} );
505       //     layerGroup.addLayer(layer);
506       // }
507     } else {
508       var result_coord = L.latLng(result.lat, result.lon);
509       if (result_coord) {
510         if (is_reverse_search) {
511           // console.dir([result_coord, [request_lat, request_lon]]);
512           // make sure the search coordinates are in the map view as well
513           map.fitBounds(
514             [result_coord, [request_lat, request_lon]],
515             {
516               padding: [50, 50],
517               maxZoom: map.getZoom()
518             }
519           );
520         } else {
521           map.panTo(result_coord, result.zoom || get_config_value('Map_Default_Zoom'));
522         }
523       }
524     }
525     if (bool_focus) {
526       $('#map').focus();
527     }
528   }
529
530
531   $('.result').on('click', function () {
532     highlight_result($(this).data('position'), true);
533   });
534
535   if (is_reverse_search) {
536     map.on('click', function (e) {
537       $('form input[name=lat]').val(e.latlng.lat);
538       $('form input[name=lon]').val(e.latlng.wrap().lng);
539       $('form').submit();
540     });
541
542     $('#switch-coords').on('click', function (e) {
543       e.preventDefault();
544       e.stopPropagation();
545       var lat = $('form input[name=lat]').val();
546       var lon = $('form input[name=lon]').val();
547       $('form input[name=lat]').val(lon);
548       $('form input[name=lon]').val(lat);
549       $('form').submit();
550     });
551   }
552
553   highlight_result(0, false);
554
555   // common mistake is to copy&paste latitude and longitude into the 'lat' search box
556   $('form input[name=lat]').on('change', function () {
557     var coords_split = $(this).val().split(',');
558     if (coords_split.length === 2) {
559       $(this).val(L.Util.trim(coords_split[0]));
560       $(this).siblings('input[name=lon]').val(L.Util.trim(coords_split[1]));
561     }
562   });
563 }
564
565
566
567
568 jQuery(document).ready(function () {
569   //
570   if (!$('#search-page,#reverse-page').length) { return; }
571
572   var is_reverse_search = !!($('#reverse-page').length);
573
574   var search_params = new URLSearchParams(window.location.search);
575
576   // return view('search', [
577   //     'sQuery' => $sQuery,
578   //     'bAsText' => '',
579   //     'sViewBox' => '',
580   //     'aSearchResults' => $aSearchResults,
581   //     'sMoreURL' => 'example.com',
582   //     'sDataDate' => $this->fetch_status_date(),
583   //     'sApiURL' => $url
584   // ]);
585
586   var api_request_params;
587   var context;
588
589   if (is_reverse_search) {
590     api_request_params = {
591       lat: search_params.get('lat'),
592       lon: search_params.get('lon'),
593       zoom: (search_params.get('zoom') > 1
594         ? search_params.get('zoom')
595         : get_config_value('Reverse_Default_Search_Zoom')),
596       format: 'jsonv2'
597     };
598
599     context = {
600       // aPlace: aPlace,
601       fLat: api_request_params.lat,
602       fLon: api_request_params.lon,
603       iZoom: (search_params.get('zoom') > 1
604         ? api_request_params.zoom
605         : get_config_value('Reverse_Default_Search_Zoom'))
606     };
607
608     update_html_title();
609     if (api_request_params.lat && api_request_params.lon) {
610
611       fetch_from_api('reverse', api_request_params, function (aPlace) {
612
613         if (aPlace.error) {
614           aPlace = null;
615         }
616
617         context.aPlace = aPlace;
618
619         render_template($('main'), 'reversepage-template', context);
620         update_html_title('Reverse result for '
621                             + api_request_params.lat
622                             + ','
623                             + api_request_params.lon);
624
625         init_map_on_search_page(
626           is_reverse_search,
627           [aPlace],
628           api_request_params.lat,
629           api_request_params.lon,
630           api_request_params.zoom
631         );
632
633         update_data_date();
634       });
635     } else {
636       render_template($('main'), 'reversepage-template', context);
637
638       init_map_on_search_page(
639         is_reverse_search,
640         [],
641         get_config_value('Map_Default_Lat'),
642         get_config_value('Map_Default_Lon'),
643         get_config_value('Map_Default_Zoom')
644       );
645     }
646
647   } else {
648     api_request_params = {
649       q: search_params.get('q'),
650       street: search_params.get('street'),
651       city: search_params.get('city'),
652       county: search_params.get('county'),
653       state: search_params.get('state'),
654       country: search_params.get('country'),
655       postalcode: search_params.get('postalcode'),
656       polygon_geojson: get_config_value('Search_AreaPolygons', false) ? 1 : 0,
657       viewbox: search_params.get('viewbox'),
658       exclude_place_ids: search_params.get('exclude_place_ids'),
659       format: 'jsonv2'
660     };
661
662     context = {
663       sQuery: api_request_params.q,
664       sViewBox: search_params.get('viewbox'),
665       env: {}
666     };
667
668     if (api_request_params.street || api_request_params.city || api_request_params.county
669       || api_request_params.state || api_request_params.country || api_request_params.postalcode) {
670       context.hStructured = {
671         street: api_request_params.street,
672         city: api_request_params.city,
673         county: api_request_params.county,
674         state: api_request_params.state,
675         country: api_request_params.country,
676         postalcode: api_request_params.postalcode
677       };
678     }
679
680     if (api_request_params.q || context.hStructured) {
681
682       fetch_from_api('search', api_request_params, function (aResults) {
683
684         context.aSearchResults = aResults;
685
686         if (aResults.length >= 10) {
687           var aExcludePlaceIds = [];
688           if (search_params.has('exclude_place_ids')) {
689             aExcludePlaceIds.search_params.get('exclude_place_ids').split(',');
690           }
691           for (var i = 0; i < aResults.length; i += 1) {
692             aExcludePlaceIds.push(aResults[i].place_id);
693           }
694
695           var parsed_url = new URLSearchParams(window.location.search);
696           parsed_url.set('exclude_place_ids', aExcludePlaceIds.join(','));
697           context.sMoreURL = '?' + parsed_url.toString();
698         }
699
700         render_template($('main'), 'searchpage-template', context);
701         update_html_title('Result for ' + api_request_params.q);
702
703         init_map_on_search_page(
704           is_reverse_search,
705           aResults,
706           get_config_value('Map_Default_Lat'),
707           get_config_value('Map_Default_Lon'),
708           get_config_value('Map_Default_Zoom')
709         );
710
711         $('#q').focus();
712
713         update_data_date();
714       });
715     } else {
716       render_template($('main'), 'searchpage-template', context);
717
718       init_map_on_search_page(
719         is_reverse_search,
720         [],
721         get_config_value('Map_Default_Lat'),
722         get_config_value('Map_Default_Lon'),
723         get_config_value('Map_Default_Zoom')
724       );
725     }
726   }
727 });
728 // *********************************************************
729 // DELETABLE PAGE
730 // *********************************************************
731
732 jQuery(document).ready(function () {
733   if (!$('#deletable-page').length) { return; }
734
735   var api_request_params = {
736     format: 'json'
737   };
738
739   fetch_from_api('deletable', api_request_params, function (aPolygons) {
740     var context = { aPolygons: aPolygons };
741
742     render_template($('main'), 'deletable-template', context);
743     update_html_title('Deletable objects');
744
745     update_data_date();
746   });
747 });
748 // *********************************************************
749 // BROKEN POLYGON PAGE
750 // *********************************************************
751
752 jQuery(document).ready(function () {
753   if (!$('#polygons-page').length) { return; }
754
755   var api_request_params = {
756     format: 'json'
757   };
758
759   fetch_from_api('polygons', api_request_params, function (aPolygons) {
760     var context = { aPolygons: aPolygons };
761
762     render_template($('main'), 'polygons-template', context);
763     update_html_title('Broken polygons');
764
765     update_data_date();
766   });
767 });