]> git.openstreetmap.org Git - nominatim-ui.git/blob - src/assets/js/nominatim-ui.js
display error when server returns error
[nominatim-ui.git] / src / 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(raw_string){
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: JSON.parse(raw_string),
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     // since .toBBoxString() doesn't round numbers
35     return [
36         map.getBounds().getSouthWest().lng.toFixed(5), // left
37         map.getBounds().getNorthEast().lat.toFixed(5), // top
38         map.getBounds().getNorthEast().lng.toFixed(5), // right
39         map.getBounds().getSouthWest().lat.toFixed(5)  // bottom
40     ].join(',');
41 }
42
43
44 /*********************************************************
45 * PAGE HELPERS
46 *********************************************************/
47
48 function fetch_from_api(endpoint_name, params, callback) {
49     var api_url = get_config_value('Nominatim_API_Endpoint') + endpoint_name + '.php?' + $.param(params);
50     if (endpoint_name !== 'status') {
51         $('#api-request-link').attr('href', api_url);
52     }
53     $.get(api_url, function(data){
54         callback(data);
55     });
56 }
57
58 function update_data_date() {
59     fetch_from_api('status', {format: 'json'}, function(data){
60         $('#data-date').text(data.data_last_updated.formatted);
61     });
62 }
63
64 function render_template(el, template_name, page_context) {
65     var template_source = $('#' + template_name).text();
66     var template = Handlebars.compile(template_source);
67     var html    = template(page_context);
68     el.html(html);
69 }
70
71 function show_error(html) {
72     $('#error-overlay').html(html).show();   
73 }
74
75 function hide_error() {
76     $('#error-overlay').empty().hide();    
77 }
78
79
80 $(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
81     // console.log(thrownError);
82     // console.log(ajaxSettings);
83     show_error('Error fetching results from <a href="' + ajaxSettings.url + '">' + ajaxSettings.url + '</a>');
84 });
85
86 /*********************************************************
87 * FORWARD/REVERSE SEARCH PAGE
88 *********************************************************/
89
90
91 function display_map_position(mouse_lat_lng){
92
93     html_mouse = "mouse position " + (mouse_lat_lng ? [mouse_lat_lng.lat.toFixed(5), mouse_lat_lng.lng.toFixed(5)].join(',') : '-');
94     html_click = "last click: " + (last_click_latlng ? [last_click_latlng.lat.toFixed(5),last_click_latlng.lng.toFixed(5)].join(',') : '-');
95
96     html_center = 
97         "map center: " + 
98         map.getCenter().lat.toFixed(5) + ',' + map.getCenter().lng.toFixed(5) +
99         " <a target='_blank' href='" + map_link_to_osm() + "'>view on osm.org</a>";
100
101     html_zoom = "map zoom: " + map.getZoom();
102
103     html_viewbox = "viewbox: " + map_viewbox_as_string();
104
105     $('#map-position-inner').html([html_center,html_zoom,html_viewbox,html_click,html_mouse].join('<br/>'));
106
107     var reverse_params = {
108         // lat: map.getCenter().lat.toFixed(5),
109         // lon: map.getCenter().lng.toFixed(5),
110         // zoom: 2,
111         // format: 'html'
112     }
113     $('#switch-to-reverse').attr('href', 'reverse.html?' + $.param(reverse_params));
114
115     $('input#use_viewbox').trigger('change');
116 }
117
118
119
120
121 function init_map_on_search_page(is_reverse_search, nominatim_results, request_lat, request_lon, init_zoom) {
122
123     map = new L.map('map', {
124         // center: [nominatim_map_init.lat, nominatim_map_init.lon],
125         // zoom:   nominatim_map_init.zoom,
126         attributionControl: (get_config_value('Map_Tile_Attribution') && get_config_value('Map_Tile_Attribution').length),
127         scrollWheelZoom:    true, // !L.Browser.touch,
128         touchZoom:          false,
129     });
130
131
132     L.tileLayer(get_config_value('Map_Tile_URL'), {
133         noWrap: true, // otherwise we end up with click coordinates like latitude -728
134         // moved to footer
135         attribution: (get_config_value('Map_Tile_Attribution') || null ) //'&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
136     }).addTo(map);
137
138     // console.log(Nominatim_Config);
139
140     map.setView([request_lat, request_lon], init_zoom);
141
142     var osm2 = new L.TileLayer(get_config_value('Map_Tile_URL'), {minZoom: 0, maxZoom: 13, attribution: (get_config_value('Map_Tile_Attribution') || null )});
143     var miniMap = new L.Control.MiniMap(osm2, {toggleDisplay: true}).addTo(map);
144
145     if (is_reverse_search) {
146         // We don't need a marker, but an L.circle instance changes radius once you zoom in/out
147         var cm = L.circleMarker([request_lat, request_lon], { radius: 5, weight: 2, fillColor: '#ff7800', color: 'red', opacity: 0.75, clickable: false});
148         cm.addTo(map);
149     }
150
151     var MapPositionControl = L.Control.extend({
152         options: {
153             position: 'topright'
154         },
155         onAdd: function (map) {
156             var container = L.DomUtil.create('div', 'my-custom-control');
157
158             $(container).text('show map bounds').addClass('leaflet-bar btn btn-sm btn-default').on('click', function(e){
159                 e.preventDefault();
160                 e.stopPropagation();
161                 $('#map-position').show();
162                 $(container).hide();
163             });
164             $('#map-position-close a').on('click', function(e){
165                 e.preventDefault();
166                 e.stopPropagation();
167                 $('#map-position').hide();
168                 $(container).show();
169             });
170
171             return container;
172         }
173     });
174
175     map.addControl(new MapPositionControl());
176
177
178
179
180
181     function update_viewbox_field(){
182         // hidden HTML field
183         $('input[name=viewbox]').val( $('input#use_viewbox').prop('checked') ? map_viewbox_as_string() : '');
184     }
185
186     map.on('move', function(e) {
187         display_map_position();
188         update_viewbox_field();
189     });
190
191     map.on('mousemove', function(e) {
192         display_map_position(e.latlng);
193     });
194
195     map.on('click', function(e) {
196         last_click_latlng = e.latlng;
197         display_map_position();
198     });
199
200     map.on('load', function(e){
201         display_map_position();
202     });
203
204
205     $('input#use_viewbox').on('change', function(){
206         update_viewbox_field();
207     });
208
209
210
211
212     function get_result_element(position){
213         return $('.result').eq(position);
214     }
215     function marker_for_result(result){
216         return L.marker([result.lat,result.lon], {riseOnHover:true,title:result.name });
217     }
218     function circle_for_result(result){
219         return L.circleMarker([result.lat,result.lon], { radius: 10, weight: 2, fillColor: '#ff7800', color: 'blue', opacity: 0.75, clickable: !is_reverse_search});
220     }
221
222     var layerGroup = new L.layerGroup().addTo(map);
223     function highlight_result(position, bool_focus){
224         var result = nominatim_results[position];
225         if (!result){ return }
226         var result_el = get_result_element(position);
227
228         $('.result').removeClass('highlight');
229         result_el.addClass('highlight');
230
231         layerGroup.clearLayers();
232
233         if (result.lat){
234             var circle = circle_for_result(result);
235             circle.on('click', function(){
236                 highlight_result(position);
237             });
238             layerGroup.addLayer(circle);            
239         }
240         if (result.aBoundingBox){
241
242             var bounds = [[result.aBoundingBox[0]*1,result.aBoundingBox[2]*1], [result.aBoundingBox[1]*1,result.aBoundingBox[3]*1]];
243             map.fitBounds(bounds);
244
245             if (result.asgeojson && result.asgeojson.match(/(Polygon)|(Line)/) ){
246
247                 var geojson_layer = L.geoJson(
248                     parse_and_normalize_geojson_string(result.asgeojson),
249                     {
250                         // http://leafletjs.com/reference-1.0.3.html#path-option
251                         style: function(feature) {
252                             return { interactive: false, color: 'blue' }; 
253                         }
254                     }
255                 );
256                 layerGroup.addLayer(geojson_layer);
257             }
258             // else {
259             //     var layer = L.rectangle(bounds, {color: "#ff7800", weight: 1} );
260             //     layerGroup.addLayer(layer);
261             // }
262         }
263         else {
264             var result_coord = L.latLng(result.lat, result.lon);
265             if ( result_coord ){
266                 if ( is_reverse_search ){
267                     // console.dir([result_coord, [request_lat, request_lon]]);
268                     // make sure the search coordinates are in the map view as well
269                     map.fitBounds([result_coord, [request_lat, request_lon]], {padding: [50,50], maxZoom: map.getZoom()});
270
271                     // better, but causes a leaflet warning
272                     // map.panInsideBounds([[result.lat,result.lon], [nominatim_map_init.lat,nominatim_map_init.lon]], {animate: false});
273                 }
274                 else {
275                     map.panTo(result_coord, result.zoom || get_config_value('Map_Default_Zoom'));
276                 }
277             }
278         }
279         if (bool_focus){
280             $('#map').focus();
281         }
282     }
283
284
285     $('.result').on('click', function(e){
286         highlight_result($(this).data('position'), true);
287     });
288
289     if ( is_reverse_search ){
290         map.on('click', function(e){
291             $('form input[name=lat]').val( e.latlng.lat);
292             $('form input[name=lon]').val( e.latlng.lng);
293             $('form').submit();
294         });
295
296         $('#switch-coords').on('click', function(e){
297             e.preventDefault();
298             e.stopPropagation();
299             var lat = $('form input[name=lat]').val();
300             var lon = $('form input[name=lon]').val();
301             $('form input[name=lat]').val(lon);
302             $('form input[name=lon]').val(lat);
303             $('form').submit();
304         });
305     }
306
307     highlight_result(0, false);
308
309     // common mistake is to copy&paste latitude and longitude into the 'lat' search box
310     $('form input[name=lat]').on('change', function(){
311         var coords = $(this).val().split(',');
312         if (coords.length == 2) {
313             $(this).val(L.Util.trim(coords[0]));
314             $(this).siblings('input[name=lon]').val(L.Util.trim(coords[1]));
315         }
316     });
317 };
318
319
320
321
322
323 jQuery(document).ready(function(){
324     hide_error();
325 });
326
327
328
329
330 jQuery(document).ready(function(){
331
332     if ( !$('#search-page,#reverse-page').length ){ return; }
333     
334     var is_reverse_search = !!( $('#reverse-page').length );
335     var endpoint = is_reverse_search ? 'reverse' : 'search';
336
337
338     var search_params = new URLSearchParams(location.search);
339
340
341     // return view('search', [
342     //     'sQuery' => $sQuery,
343     //     'bAsText' => '',
344     //     'sViewBox' => '',
345     //     'aSearchResults' => $aSearchResults,
346     //     'sMoreURL' => 'example.com',
347     //     'sDataDate' => $this->fetch_status_date(),
348     //     'sApiURL' => $url
349     // ]);
350
351
352     if (is_reverse_search) {
353         var api_request_params = {
354             lat: typeof(search_params.get('lat') !== 'undefined') ? search_params.get('lat') : get_config_value('Map_Default_Lat'),
355             lon: typeof(search_params.get('lon') !== 'undefined') ? search_params.get('lon') : get_config_value('Map_Default_Lon'),
356             zoom: (search_params.get('zoom') !== '' ? search_params.get('zoom') : get_config_value('Map_Default_Zoom')),
357             format: 'jsonv2'
358         }
359
360         fetch_from_api('reverse', api_request_params, function(aPlace){
361
362             if (aPlace.error) {
363                 aPlace = null;
364             }
365
366             var context = {
367                 aPlace: aPlace,
368                 fLat: api_request_params.lat,
369                 fLon: api_request_params.lon,
370                 iZoom: (search_params.get('zoom') !== '' ? api_request_params.zoom : undefined)
371             };
372
373             render_template($('main'), 'reversepage-template', context);
374
375             init_map_on_search_page(is_reverse_search, [aPlace], api_request_params.lat, api_request_params.lon, api_request_params.zoom);
376
377             update_data_date();
378         });
379     } else {
380         var api_request_params = {
381             q: search_params.get('q'),
382             polygon_geojson: search_params.get('polygon_geojson') ? 1 : 0,
383             polygon: search_params.get('polygon'),
384             format: 'jsonv2'
385         };
386
387         fetch_from_api('search', api_request_params, function(aResults){
388
389             var context = {
390                 aSearchResults: aResults,
391                 sQuery: api_request_params.q,
392                 sViewBox: '',
393                 env: Nominatim_Config,
394                 sMoreURL: ''
395             };
396
397             render_template($('main'), 'searchpage-template', context);
398
399             init_map_on_search_page(is_reverse_search, aResults);
400
401             $('#q').focus();
402
403             update_data_date();
404         });
405     }
406 });
407
408
409 /*********************************************************
410 * DETAILS PAGE
411 *********************************************************/
412
413
414
415 function init_map_on_detail_page(lat, lon, geojson) {
416     map = new L.map('map', {
417         // center: [nominatim_map_init.lat, nominatim_map_init.lon],
418         // zoom:   nominatim_map_init.zoom,
419         attributionControl: (get_config_value('Map_Tile_Attribution') && get_config_value('Map_Tile_Attribution').length),
420         scrollWheelZoom:    true, // !L.Browser.touch,
421         touchZoom:          false,
422     });
423
424     L.tileLayer(get_config_value('Map_Tile_URL'), {
425         // moved to footer
426         attribution: (get_config_value('Map_Tile_Attribution') || null ) //'&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
427     }).addTo(map);
428
429     var layerGroup = new L.layerGroup().addTo(map);
430
431     var circle = L.circleMarker([lat,lon], { radius: 10, weight: 2, fillColor: '#ff7800', color: 'blue', opacity: 0.75});
432     map.addLayer(circle);
433
434     if (geojson) {
435         var geojson_layer = L.geoJson(
436             // http://leafletjs.com/reference-1.0.3.html#path-option
437             parse_and_normalize_geojson_string(geojson),
438             {
439                 style: function(feature) {
440                     return { interactive: false, color: 'blue' }; 
441                 }
442             }
443         );
444         map.addLayer(geojson_layer);
445         map.fitBounds(geojson_layer.getBounds());
446     } else {
447         map.setView([lat,lon],10);
448     }
449
450     var osm2 = new L.TileLayer(get_config_value('Map_Tile_URL'), {minZoom: 0, maxZoom: 13, attribution: (get_config_value('Map_Tile_Attribution') || null )});
451     var miniMap = new L.Control.MiniMap(osm2, {toggleDisplay: true}).addTo(map);
452 }
453
454 jQuery(document).ready(function(){
455
456     if ( !$('#details-page').length ){ return; }
457
458     var search_params = new URLSearchParams(location.search);
459     // var place_id = search_params.get('place_id');
460
461     var api_request_params = {
462         place_id: search_params.get('place_id'),
463         place_id: search_params.get('osmtype'),
464         place_id: search_params.get('osmid'),
465         group_parents: 1,
466         format: 'json'
467     };
468
469     fetch_from_api('details', api_request_params, function(aFeature){
470
471         var context = { aPlace: aFeature };
472
473         render_template($('main'), 'detailspage-template', context);
474
475         update_data_date();
476
477         init_map_on_detail_page(aFeature.lat, aFeature.lon, aFeature.asgeojson);
478     });
479 });
480