]> git.openstreetmap.org Git - nominatim-ui.git/blob - dist/assets/js/nominatim-ui.js
3e651561294e9e5216d9c63ec9a26b0314fefd4f
[nominatim-ui.git] / dist / assets / js / nominatim-ui.js
1 'use strict';
2
3 var map;
4 var last_click_latlng;
5
6
7 // *********************************************************
8 // HELPERS
9 // *********************************************************
10
11 function get_config_value(str, default_val) {
12   return (typeof Nominatim_Config[str] !== 'undefined' ? Nominatim_Config[str] : default_val);
13 }
14
15 function parse_and_normalize_geojson_string(part) {
16   // normalize places the geometry into a featurecollection, similar to
17   // https://github.com/mapbox/geojson-normalize
18   var parsed_geojson = {
19     type: 'FeatureCollection',
20     features: [
21       {
22         type: 'Feature',
23         geometry: part,
24         properties: {}
25       }
26     ]
27   };
28   return parsed_geojson;
29 }
30
31 function map_link_to_osm() {
32   var zoom = map.getZoom();
33   var lat = map.getCenter().lat;
34   var lng = map.getCenter().lng;
35   return 'https://openstreetmap.org/#map=' + zoom + '/' + lat + '/' + lng;
36 }
37
38 function map_viewbox_as_string() {
39   var bounds = map.getBounds();
40   var west = bounds.getWest();
41   var east = bounds.getEast();
42
43   if ((east - west) >= 360) { // covers more than whole planet
44     west = map.getCenter().lng - 179.999;
45     east = map.getCenter().lng + 179.999;
46   }
47   east = L.latLng(77, east).wrap().lng;
48   west = L.latLng(77, west).wrap().lng;
49
50   return [
51     west.toFixed(5), // left
52     bounds.getNorth().toFixed(5), // top
53     east.toFixed(5), // right
54     bounds.getSouth().toFixed(5) // bottom
55   ].join(',');
56 }
57
58
59 // *********************************************************
60 // PAGE HELPERS
61 // *********************************************************
62
63 function fetch_from_api(endpoint_name, params, callback) {
64   // `&a=&b=&c=1` => '&c='
65   for (var k in params) {
66     if (typeof (params[k]) === 'undefined' || params[k] === '' || params[k] === null) {
67       delete params[k];
68     }
69   }
70
71   var api_url = get_config_value('Nominatim_API_Endpoint') + endpoint_name + '.php?'
72                   + $.param(params);
73   if (endpoint_name !== 'status') {
74     $('#api-request-link').attr('href', api_url);
75   }
76   $.get(api_url, function (data) {
77     callback(data);
78   });
79 }
80
81 function update_data_date() {
82   fetch_from_api('status', { format: 'json' }, function (data) {
83     $('#data-date').text(data.data_updated);
84   });
85 }
86
87 function render_template(el, template_name, page_context) {
88   var template_source = $('#' + template_name).text();
89   var template = Handlebars.compile(template_source);
90   var html = template(page_context);
91   el.html(html);
92 }
93
94 function update_html_title(title) {
95   var prefix = '';
96   if (title && title.length > 1) {
97     prefix = title + ' | ';
98   }
99   $('head title').text(prefix + 'OpenStreetMap Nominatim');
100 }
101
102 function show_error(html) {
103   $('#error-overlay').html(html).show();
104 }
105
106 function hide_error() {
107   $('#error-overlay').empty().hide();
108 }
109
110
111 $(document).ajaxError(function (event, jqXHR, ajaxSettings/* , thrownError */) {
112   // console.log(thrownError);
113   // console.log(ajaxSettings);
114   var url = ajaxSettings.url;
115   show_error('Error fetching results from <a href="' + url + '">' + url + '</a>');
116 });
117
118
119 jQuery(document).ready(function () {
120   hide_error();
121 });
122 // *********************************************************
123 // DETAILS PAGE
124 // *********************************************************
125
126
127 function init_map_on_detail_page(lat, lon, geojson) {
128   var attribution = get_config_value('Map_Tile_Attribution') || null;
129   map = new L.map('map', {
130     // center: [nominatim_map_init.lat, nominatim_map_init.lon],
131     // zoom:   nominatim_map_init.zoom,
132     attributionControl: (attribution && attribution.length),
133     scrollWheelZoom: true, // !L.Browser.touch,
134     touchZoom: false
135   });
136
137   L.tileLayer(get_config_value('Map_Tile_URL'), {
138     // moved to footer
139     // '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
140     attribution: attribution
141   }).addTo(map);
142
143   // var layerGroup = new L.layerGroup().addTo(map);
144
145   var circle = L.circleMarker([lat, lon], {
146     radius: 10, weight: 2, fillColor: '#ff7800', color: 'blue', opacity: 0.75
147   });
148   map.addLayer(circle);
149
150   if (geojson) {
151     var geojson_layer = L.geoJson(
152       // https://leafletjs.com/reference-1.0.3.html#path-option
153       parse_and_normalize_geojson_string(geojson),
154       {
155         style: function () {
156           return { interactive: false, color: 'blue' };
157         }
158       }
159     );
160     map.addLayer(geojson_layer);
161     map.fitBounds(geojson_layer.getBounds());
162   } else {
163     map.setView([lat, lon], 10);
164   }
165
166   var osm2 = new L.TileLayer(
167     get_config_value('Map_Tile_URL'),
168     {
169       minZoom: 0,
170       maxZoom: 13,
171       attribution: (get_config_value('Map_Tile_Attribution') || null)
172     }
173   );
174   (new L.Control.MiniMap(osm2, { toggleDisplay: true })).addTo(map);
175 }
176
177
178 jQuery(document).ready(function () {
179   if (!$('#details-page').length) { return; }
180
181   var search_params = new URLSearchParams(window.location.search);
182   // var place_id = search_params.get('place_id');
183
184   var api_request_params = {
185     place_id: search_params.get('place_id'),
186     osmtype: search_params.get('osmtype'),
187     osmid: search_params.get('osmid'),
188     keywords: search_params.get('keywords'),
189     addressdetails: 1,
190     hierarchy: (search_params.get('hierarchy') === '1' ? 1 : 0),
191     group_hierarchy: 1,
192     polygon_geojson: 1,
193     format: 'json'
194   };
195
196   if (api_request_params.place_id || (api_request_params.osmtype && api_request_params.osmid)) {
197     fetch_from_api('details', api_request_params, function (aFeature) {
198       var context = { aPlace: aFeature, base_url: window.location.search };
199
200       render_template($('main'), 'detailspage-template', context);
201       if (api_request_params.place_id) {
202         update_html_title('Details for ' + api_request_params.place_id);
203       } else {
204         update_html_title('Details for ' + api_request_params.osmtype + api_request_params.osmid);
205       }
206
207       update_data_date();
208
209       var lat = aFeature.centroid.coordinates[1];
210       var lon = aFeature.centroid.coordinates[0];
211       init_map_on_detail_page(lat, lon, aFeature.geometry);
212     });
213   } else {
214     render_template($('main'), 'detailspage-index-template');
215   }
216
217   $('#form-by-type-and-id,#form-by-osm-url').on('submit', function (e) {
218     e.preventDefault();
219
220     var val = $(this).find('input[type=edit]').val();
221     var matches = val.match(/^\s*([NWR])(\d+)\s*$/i);
222
223     if (!matches) {
224       matches = val.match(/\/(relation|way|node)\/(\d+)\s*$/);
225     }
226
227     if (matches) {
228       $(this).find('input[name=osmtype]').val(matches[1].charAt(0).toUpperCase());
229       $(this).find('input[name=osmid]').val(matches[2]);
230       $(this).get(0).submit();
231     } else {
232       alert('invalid input');
233     }
234   });
235 });
236
237 // *********************************************************
238 // FORWARD/REVERSE SEARCH PAGE
239 // *********************************************************
240
241
242 function display_map_position(mouse_lat_lng) {
243   //
244   if (mouse_lat_lng) {
245     mouse_lat_lng = map.wrapLatLng(mouse_lat_lng);
246   }
247
248   var html_mouse = 'mouse position: -';
249   if (mouse_lat_lng) {
250     html_mouse = 'mouse position: '
251                   + [mouse_lat_lng.lat.toFixed(5), mouse_lat_lng.lng.toFixed(5)].join(',');
252   }
253   var html_click = 'last click: -';
254   if (last_click_latlng) {
255     html_click = 'last click: '
256                   + [last_click_latlng.lat.toFixed(5), last_click_latlng.lng.toFixed(5)].join(',');
257   }
258
259   var html_center = 'map center: '
260     + map.getCenter().lat.toFixed(5) + ',' + map.getCenter().lng.toFixed(5)
261     + ' <a target="_blank" href="' + map_link_to_osm() + '">view on osm.org</a>';
262
263   var html_zoom = 'map zoom: ' + map.getZoom();
264   var html_viewbox = 'viewbox: ' + map_viewbox_as_string();
265
266   $('#map-position-inner').html([
267     html_center,
268     html_zoom,
269     html_viewbox,
270     html_click,
271     html_mouse
272   ].join('<br/>'));
273
274   var center_lat_lng = map.wrapLatLng(map.getCenter());
275   var reverse_params = {
276     lat: center_lat_lng.lat.toFixed(5),
277     lon: center_lat_lng.lng.toFixed(5)
278     // zoom: 2,
279     // format: 'html'
280   };
281   $('#switch-to-reverse').attr('href', 'reverse.html?' + $.param(reverse_params));
282
283   $('input#use_viewbox').trigger('change');
284 }
285
286 function init_map_on_search_page(is_reverse_search, nominatim_results, request_lat,
287   request_lon, init_zoom) {
288
289   var attribution = get_config_value('Map_Tile_Attribution') || null;
290   map = new L.map('map', {
291     // center: [nominatim_map_init.lat, nominatim_map_init.lon],
292     // zoom:   nominatim_map_init.zoom,
293     attributionControl: (attribution && attribution.length),
294     scrollWheelZoom: true, // !L.Browser.touch,
295     touchZoom: false
296   });
297
298
299   L.tileLayer(get_config_value('Map_Tile_URL'), {
300     // moved to footer
301     // '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
302     attribution: attribution
303   }).addTo(map);
304
305   // console.log(Nominatim_Config);
306
307   map.setView([request_lat, request_lon], init_zoom);
308
309   var osm2 = new L.TileLayer(get_config_value('Map_Tile_URL'), {
310     minZoom: 0,
311     maxZoom: 13,
312     attribution: attribution
313   });
314   new L.Control.MiniMap(osm2, { toggleDisplay: true }).addTo(map);
315
316   if (is_reverse_search) {
317     // We don't need a marker, but an L.circle instance changes radius once you zoom in/out
318     var cm = L.circleMarker(
319       [request_lat, request_lon],
320       {
321         radius: 5,
322         weight: 2,
323         fillColor: '#ff7800',
324         color: 'red',
325         opacity: 0.75,
326         zIndexOffset: 100,
327         clickable: false
328       }
329     );
330     cm.addTo(map);
331   } else {
332     var search_params = new URLSearchParams(window.location.search);
333     var viewbox = search_params.get('viewbox');
334     if (viewbox) {
335       var coords = viewbox.split(','); // <x1>,<y1>,<x2>,<y2>
336       var bounds = L.latLngBounds([coords[1], coords[0]], [coords[3], coords[2]]);
337       L.rectangle(bounds, {
338         color: '#69d53e',
339         weight: 3,
340         dashArray: '5 5',
341         opacity: 0.8,
342         fill: false
343       }).addTo(map);
344     }
345   }
346
347   var MapPositionControl = L.Control.extend({
348     options: {
349       position: 'topright'
350     },
351     onAdd: function (/* map */) {
352       var container = L.DomUtil.create('div', 'my-custom-control');
353
354       $(container).text('show map bounds')
355         .addClass('leaflet-bar btn btn-sm btn-default')
356         .on('click', function (e) {
357           e.preventDefault();
358           e.stopPropagation();
359           $('#map-position').show();
360           $(container).hide();
361         });
362       $('#map-position-close a').on('click', function (e) {
363         e.preventDefault();
364         e.stopPropagation();
365         $('#map-position').hide();
366         $(container).show();
367       });
368
369       return container;
370     }
371   });
372
373   map.addControl(new MapPositionControl());
374
375
376
377
378
379   function update_viewbox_field() {
380     // hidden HTML field
381     $('input[name=viewbox]')
382       .val($('input#use_viewbox')
383         .prop('checked') ? map_viewbox_as_string() : '');
384   }
385
386   map.on('move', function () {
387     display_map_position();
388     update_viewbox_field();
389   });
390
391   map.on('mousemove', function (e) {
392     display_map_position(e.latlng);
393   });
394
395   map.on('click', function (e) {
396     last_click_latlng = e.latlng;
397     display_map_position();
398   });
399
400   map.on('load', function () {
401     display_map_position();
402   });
403
404   $('input#use_viewbox').on('change', function () {
405     update_viewbox_field();
406   });
407
408
409
410
411   function get_result_element(position) {
412     return $('.result').eq(position);
413   }
414   // function marker_for_result(result) {
415   //   return L.marker([result.lat, result.lon], { riseOnHover: true, title: result.name });
416   // }
417   function circle_for_result(result) {
418     var cm_style = {
419       radius: 10,
420       weight: 2,
421       fillColor: '#ff7800',
422       color: 'blue',
423       opacity: 0.75,
424       clickable: !is_reverse_search
425     };
426     return L.circleMarker([result.lat, result.lon], cm_style);
427   }
428
429   var layerGroup = (new L.layerGroup()).addTo(map);
430
431   function highlight_result(position, bool_focus) {
432     var result = nominatim_results[position];
433     if (!result) { return; }
434     var result_el = get_result_element(position);
435
436     $('.result').removeClass('highlight');
437     result_el.addClass('highlight');
438
439     layerGroup.clearLayers();
440
441     if (result.lat) {
442       var circle = circle_for_result(result);
443       circle.on('click', function () {
444         highlight_result(position);
445       });
446       layerGroup.addLayer(circle);
447     }
448
449     if (result.boundingbox) {
450       var bbox = [
451         [result.boundingbox[0] * 1, result.boundingbox[2] * 1],
452         [result.boundingbox[1] * 1, result.boundingbox[3] * 1]
453       ];
454       map.fitBounds(bbox);
455
456       if (result.geojson && result.geojson.type.match(/(Polygon)|(Line)/)) {
457         //
458         var geojson_layer = L.geoJson(
459           parse_and_normalize_geojson_string(result.geojson),
460           {
461             // https://leafletjs.com/reference-1.0.3.html#path-option
462             style: function (/* feature */) {
463               return { interactive: false, color: 'blue' };
464             }
465           }
466         );
467         layerGroup.addLayer(geojson_layer);
468       }
469       // else {
470       //     var layer = L.rectangle(bounds, {color: "#ff7800", weight: 1} );
471       //     layerGroup.addLayer(layer);
472       // }
473     } else {
474       var result_coord = L.latLng(result.lat, result.lon);
475       if (result_coord) {
476         if (is_reverse_search) {
477           // console.dir([result_coord, [request_lat, request_lon]]);
478           // make sure the search coordinates are in the map view as well
479           map.fitBounds(
480             [result_coord, [request_lat, request_lon]],
481             {
482               padding: [50, 50],
483               maxZoom: map.getZoom()
484             }
485           );
486         } else {
487           map.panTo(result_coord, result.zoom || get_config_value('Map_Default_Zoom'));
488         }
489       }
490     }
491     if (bool_focus) {
492       $('#map').focus();
493     }
494   }
495
496
497   $('.result').on('click', function () {
498     highlight_result($(this).data('position'), true);
499   });
500
501   if (is_reverse_search) {
502     map.on('click', function (e) {
503       $('form input[name=lat]').val(e.latlng.lat);
504       $('form input[name=lon]').val(e.latlng.wrap().lng);
505       $('form').submit();
506     });
507
508     $('#switch-coords').on('click', function (e) {
509       e.preventDefault();
510       e.stopPropagation();
511       var lat = $('form input[name=lat]').val();
512       var lon = $('form input[name=lon]').val();
513       $('form input[name=lat]').val(lon);
514       $('form input[name=lon]').val(lat);
515       $('form').submit();
516     });
517   }
518
519   highlight_result(0, false);
520
521   // common mistake is to copy&paste latitude and longitude into the 'lat' search box
522   $('form input[name=lat]').on('change', function () {
523     var coords_split = $(this).val().split(',');
524     if (coords_split.length === 2) {
525       $(this).val(L.Util.trim(coords_split[0]));
526       $(this).siblings('input[name=lon]').val(L.Util.trim(coords_split[1]));
527     }
528   });
529 }
530
531
532
533
534
535
536
537 jQuery(document).ready(function () {
538   //
539   if (!$('#search-page,#reverse-page').length) { return; }
540
541   var is_reverse_search = !!($('#reverse-page').length);
542
543   var search_params = new URLSearchParams(window.location.search);
544
545   // return view('search', [
546   //     'sQuery' => $sQuery,
547   //     'bAsText' => '',
548   //     'sViewBox' => '',
549   //     'aSearchResults' => $aSearchResults,
550   //     'sMoreURL' => 'example.com',
551   //     'sDataDate' => $this->fetch_status_date(),
552   //     'sApiURL' => $url
553   // ]);
554
555   var api_request_params;
556   var context;
557
558   if (is_reverse_search) {
559     api_request_params = {
560       lat: search_params.get('lat'),
561       lon: search_params.get('lon'),
562       zoom: (search_params.get('zoom') > 1
563         ? search_params.get('zoom')
564         : get_config_value('Reverse_Default_Search_Zoom')),
565       format: 'jsonv2'
566     };
567
568     context = {
569       // aPlace: aPlace,
570       fLat: api_request_params.lat,
571       fLon: api_request_params.lon,
572       iZoom: (search_params.get('zoom') > 1
573         ? api_request_params.zoom
574         : get_config_value('Reverse_Default_Search_Zoom'))
575     };
576
577     update_html_title();
578     if (api_request_params.lat && api_request_params.lon) {
579
580       fetch_from_api('reverse', api_request_params, function (aPlace) {
581
582         if (aPlace.error) {
583           aPlace = null;
584         }
585
586         context.aPlace = aPlace;
587
588         render_template($('main'), 'reversepage-template', context);
589         update_html_title('Reverse result for '
590                             + api_request_params.lat
591                             + ','
592                             + api_request_params.lon);
593
594         init_map_on_search_page(
595           is_reverse_search,
596           [aPlace],
597           api_request_params.lat,
598           api_request_params.lon,
599           api_request_params.zoom
600         );
601
602         update_data_date();
603       });
604     } else {
605       render_template($('main'), 'reversepage-template', context);
606
607       init_map_on_search_page(
608         is_reverse_search,
609         [],
610         get_config_value('Map_Default_Lat'),
611         get_config_value('Map_Default_Lon'),
612         get_config_value('Map_Default_Zoom')
613       );
614     }
615
616   } else {
617     api_request_params = {
618       q: search_params.get('q'),
619       polygon_geojson: search_params.get('polygon_geojson') ? 1 : 0,
620       viewbox: search_params.get('viewbox'),
621       format: 'jsonv2'
622     };
623
624     context = {
625       // aSearchResults: aResults,
626       sQuery: api_request_params.q,
627       sViewBox: search_params.get('viewbox'),
628       env: Nominatim_Config,
629       sMoreURL: ''
630     };
631
632     if (api_request_params.q) {
633
634       fetch_from_api('search', api_request_params, function (aResults) {
635
636         context.aSearchResults = aResults;
637
638         render_template($('main'), 'searchpage-template', context);
639         update_html_title('Result for ' + api_request_params.q);
640
641         init_map_on_search_page(
642           is_reverse_search,
643           aResults,
644           get_config_value('Map_Default_Lat'),
645           get_config_value('Map_Default_Lon'),
646           get_config_value('Map_Default_Zoom')
647         );
648
649         $('#q').focus();
650
651         update_data_date();
652       });
653     } else {
654       render_template($('main'), 'searchpage-template', context);
655
656       init_map_on_search_page(
657         is_reverse_search,
658         [],
659         get_config_value('Map_Default_Lat'),
660         get_config_value('Map_Default_Lon'),
661         get_config_value('Map_Default_Zoom')
662       );
663     }
664   }
665 });