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