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