]> git.openstreetmap.org Git - nominatim-ui.git/blob - dist/assets/js/nominatim-ui.js
add dist/ directory for first time
[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: 1,
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 };
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         clickable: false
276       }
277     );
278     cm.addTo(map);
279   }
280
281   var MapPositionControl = L.Control.extend({
282     options: {
283       position: 'topright'
284     },
285     onAdd: function (/* map */) {
286       var container = L.DomUtil.create('div', 'my-custom-control');
287
288       $(container).text('show map bounds').addClass('leaflet-bar btn btn-sm btn-default').on('click', function (e) {
289         e.preventDefault();
290         e.stopPropagation();
291         $('#map-position').show();
292         $(container).hide();
293       });
294       $('#map-position-close a').on('click', function (e) {
295         e.preventDefault();
296         e.stopPropagation();
297         $('#map-position').hide();
298         $(container).show();
299       });
300
301       return container;
302     }
303   });
304
305   map.addControl(new MapPositionControl());
306
307
308
309
310
311   function update_viewbox_field() {
312     // hidden HTML field
313     $('input[name=viewbox]').val($('input#use_viewbox').prop('checked') ? map_viewbox_as_string() : '');
314   }
315
316   map.on('move', function () {
317     display_map_position();
318     update_viewbox_field();
319   });
320
321   map.on('mousemove', function (e) {
322     display_map_position(e.latlng);
323   });
324
325   map.on('click', function (e) {
326     last_click_latlng = e.latlng;
327     display_map_position();
328   });
329
330   map.on('load', function () {
331     display_map_position();
332   });
333
334   $('input#use_viewbox').on('change', function () {
335     update_viewbox_field();
336   });
337
338
339
340
341   function get_result_element(position) {
342     return $('.result').eq(position);
343   }
344   function marker_for_result(result) {
345     return L.marker([result.lat, result.lon], { riseOnHover: true, title: result.name });
346   }
347   function circle_for_result(result) {
348     var cm_style = {
349       radius: 10,
350       weight: 2,
351       fillColor: '#ff7800',
352       color: 'blue',
353       opacity: 0.75,
354       clickable: !is_reverse_search
355     };
356     return L.circleMarker([result.lat, result.lon], cm_style);
357   }
358
359   var layerGroup = new L.layerGroup().addTo(map);
360
361   function highlight_result(position, bool_focus) {
362     var result = nominatim_results[position];
363     if (!result) { return; }
364     var result_el = get_result_element(position);
365
366     $('.result').removeClass('highlight');
367     result_el.addClass('highlight');
368
369     layerGroup.clearLayers();
370
371     if (result.lat) {
372       var circle = circle_for_result(result);
373       circle.on('click', function () {
374         highlight_result(position);
375       });
376       layerGroup.addLayer(circle);
377     }
378
379     if (result.boundingbox) {
380       var bounds = [
381         [result.boundingbox[0] * 1, result.boundingbox[2] * 1],
382         [result.boundingbox[1] * 1, result.boundingbox[3] * 1]
383       ];
384       map.fitBounds(bounds);
385
386       if (result.geojson && result.geojson.type.match(/(Polygon)|(Line)/)) {
387         //
388         var geojson_layer = L.geoJson(
389           parse_and_normalize_geojson_string(result.geojson),
390           {
391             // https://leafletjs.com/reference-1.0.3.html#path-option
392             style: function (feature) {
393               return { interactive: false, color: 'blue' };
394             }
395           }
396         );
397         layerGroup.addLayer(geojson_layer);
398       }
399       // else {
400       //     var layer = L.rectangle(bounds, {color: "#ff7800", weight: 1} );
401       //     layerGroup.addLayer(layer);
402       // }
403     } else {
404       var result_coord = L.latLng(result.lat, result.lon);
405       if (result_coord) {
406         if (is_reverse_search) {
407           // console.dir([result_coord, [request_lat, request_lon]]);
408           // make sure the search coordinates are in the map view as well
409           map.fitBounds(
410             [result_coord, [request_lat, request_lon]],
411             {
412               padding: [50, 50],
413               maxZoom: map.getZoom()
414             }
415           );
416         } else {
417           map.panTo(result_coord, result.zoom || get_config_value('Map_Default_Zoom'));
418         }
419       }
420     }
421     if (bool_focus) {
422       $('#map').focus();
423     }
424   }
425
426
427   $('.result').on('click', function () {
428     highlight_result($(this).data('position'), true);
429   });
430
431   if (is_reverse_search) {
432     map.on('click', function (e) {
433       $('form input[name=lat]').val(e.latlng.lat);
434       $('form input[name=lon]').val(e.latlng.wrap().lng);
435       $('form').submit();
436     });
437
438     $('#switch-coords').on('click', function (e) {
439       e.preventDefault();
440       e.stopPropagation();
441       var lat = $('form input[name=lat]').val();
442       var lon = $('form input[name=lon]').val();
443       $('form input[name=lat]').val(lon);
444       $('form input[name=lon]').val(lat);
445       $('form').submit();
446     });
447   }
448
449   highlight_result(0, false);
450
451   // common mistake is to copy&paste latitude and longitude into the 'lat' search box
452   $('form input[name=lat]').on('change', function () {
453     var coords = $(this).val().split(',');
454     if (coords.length === 2) {
455       $(this).val(L.Util.trim(coords[0]));
456       $(this).siblings('input[name=lon]').val(L.Util.trim(coords[1]));
457     }
458   });
459 }
460
461
462
463
464
465
466
467 jQuery(document).ready(function () {
468   //
469   if (!$('#search-page,#reverse-page').length) { return; }
470
471   var is_reverse_search = !!($('#reverse-page').length);
472   var endpoint = is_reverse_search ? 'reverse' : 'search';
473
474
475   var search_params = new URLSearchParams(location.search);
476
477   // return view('search', [
478   //     'sQuery' => $sQuery,
479   //     'bAsText' => '',
480   //     'sViewBox' => '',
481   //     'aSearchResults' => $aSearchResults,
482   //     'sMoreURL' => 'example.com',
483   //     'sDataDate' => $this->fetch_status_date(),
484   //     'sApiURL' => $url
485   // ]);
486
487
488   if (is_reverse_search) {
489     var api_request_params = {
490       lat: search_params.get('lat'),
491       lon: search_params.get('lon'),
492       zoom: (search_params.get('zoom') !== null ? search_params.get('zoom') : get_config_value('Reverse_Default_Search_Zoom')),
493       format: 'jsonv2'
494     };
495
496     var context = {
497       // aPlace: aPlace,
498       fLat: api_request_params.lat,
499       fLon: api_request_params.lon,
500       iZoom: (search_params.get('zoom') !== null ? api_request_params.zoom : get_config_value('Reverse_Default_Search_Zoom'))
501     };
502
503
504     if (api_request_params.lat && api_request_params.lon) {
505
506       fetch_from_api('reverse', api_request_params, function (aPlace) {
507
508         if (aPlace.error) {
509           aPlace = null;
510         }
511
512         context.aPlace = aPlace;
513
514         render_template($('main'), 'reversepage-template', context);
515
516         init_map_on_search_page(
517           is_reverse_search,
518           [aPlace],
519           api_request_params.lat,
520           api_request_params.lon,
521           api_request_params.zoom
522         );
523
524         update_data_date();
525       });
526     } else {
527       render_template($('main'), 'reversepage-template', context);
528
529       init_map_on_search_page(
530         is_reverse_search,
531         [],
532         get_config_value('Map_Default_Lat'),
533         get_config_value('Map_Default_Lon'),
534         get_config_value('Map_Default_Zoom')
535       );
536     }
537
538   } else {
539     var api_request_params = {
540       q: search_params.get('q'),
541       polygon_geojson: search_params.get('polygon_geojson') ? 1 : 0,
542       viewbox: search_params.get('viewbox'),
543       format: 'jsonv2'
544     };
545
546     var context = {
547       // aSearchResults: aResults,
548       sQuery: api_request_params.q,
549       sViewBox: '',
550       env: Nominatim_Config,
551       sMoreURL: ''
552     };
553
554     if (api_request_params.q) {
555
556       fetch_from_api('search', api_request_params, function (aResults) {
557
558         context.aSearchResults = aResults;
559
560         render_template($('main'), 'searchpage-template', context);
561
562         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'));
563
564         $('#q').focus();
565
566         update_data_date();
567       });
568     } else {
569       render_template($('main'), 'searchpage-template', context);
570
571       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'));
572     }
573   }
574 });