]> git.openstreetmap.org Git - nominatim-ui.git/blob - src/assets/js/searchpage.js
/reverse.html should be reverse.html to app works in subdirectory
[nominatim-ui.git] / src / assets / js / searchpage.js
1
2 // *********************************************************
3 // FORWARD/REVERSE SEARCH PAGE
4 // *********************************************************
5
6
7 function display_map_position(mouse_lat_lng) {
8   //
9   if (mouse_lat_lng) {
10     mouse_lat_lng = map.wrapLatLng(mouse_lat_lng);
11   }
12
13   var html_mouse = 'mouse position: -';
14   if (mouse_lat_lng) {
15     html_mouse = 'mouse position: '
16                   + [mouse_lat_lng.lat.toFixed(5), mouse_lat_lng.lng.toFixed(5)].join(',');
17   }
18   var html_click = 'last click: -';
19   if (last_click_latlng) {
20     html_click = 'last click: '
21                   + [last_click_latlng.lat.toFixed(5), last_click_latlng.lng.toFixed(5)].join(',');
22   }
23
24   var html_center = 'map center: '
25     + map.getCenter().lat.toFixed(5) + ',' + map.getCenter().lng.toFixed(5)
26     + ' <a target="_blank" href="' + map_link_to_osm() + '">view on osm.org</a>';
27
28   var html_zoom = 'map zoom: ' + map.getZoom();
29   var html_viewbox = 'viewbox: ' + map_viewbox_as_string();
30
31   $('#map-position-inner').html([
32     html_center,
33     html_zoom,
34     html_viewbox,
35     html_click,
36     html_mouse
37   ].join('<br/>'));
38
39   var center_lat_lng = map.wrapLatLng(map.getCenter());
40   var reverse_params = {
41     lat: center_lat_lng.lat.toFixed(5),
42     lon: center_lat_lng.lng.toFixed(5)
43     // zoom: 2,
44     // format: 'html'
45   };
46   $('#switch-to-reverse').attr('href', 'reverse.html?' + $.param(reverse_params));
47
48   $('input.api-param-setting').trigger('change');
49 }
50
51 function init_map_on_search_page(is_reverse_search, nominatim_results, request_lat,
52   request_lon, init_zoom) {
53
54   var attribution = get_config_value('Map_Tile_Attribution') || null;
55   map = new L.map('map', {
56     // center: [nominatim_map_init.lat, nominatim_map_init.lon],
57     // zoom:   nominatim_map_init.zoom,
58     attributionControl: (attribution && attribution.length),
59     scrollWheelZoom: true, // !L.Browser.touch,
60     touchZoom: false
61   });
62
63
64   L.tileLayer(get_config_value('Map_Tile_URL'), {
65     // moved to footer
66     // '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
67     attribution: attribution
68   }).addTo(map);
69
70   // console.log(Nominatim_Config);
71
72   map.setView([request_lat, request_lon], init_zoom);
73
74   var osm2 = new L.TileLayer(get_config_value('Map_Tile_URL'), {
75     minZoom: 0,
76     maxZoom: 13,
77     attribution: attribution
78   });
79   new L.Control.MiniMap(osm2, { toggleDisplay: true }).addTo(map);
80
81   if (is_reverse_search) {
82     // We don't need a marker, but an L.circle instance changes radius once you zoom in/out
83     var cm = L.circleMarker(
84       [request_lat, request_lon],
85       {
86         radius: 5,
87         weight: 2,
88         fillColor: '#ff7800',
89         color: 'red',
90         opacity: 0.75,
91         zIndexOffset: 100,
92         clickable: false
93       }
94     );
95     cm.addTo(map);
96   } else {
97     var search_params = new URLSearchParams(window.location.search);
98     var viewbox = search_params.get('viewbox');
99     if (viewbox) {
100       var coords = viewbox.split(','); // <x1>,<y1>,<x2>,<y2>
101       var bounds = L.latLngBounds([coords[1], coords[0]], [coords[3], coords[2]]);
102       L.rectangle(bounds, {
103         color: '#69d53e',
104         weight: 3,
105         dashArray: '5 5',
106         opacity: 0.8,
107         fill: false
108       }).addTo(map);
109     }
110   }
111
112   var MapPositionControl = L.Control.extend({
113     options: {
114       position: 'topright'
115     },
116     onAdd: function (/* map */) {
117       var container = L.DomUtil.create('div', 'my-custom-control');
118
119       $(container).text('show map bounds')
120         .addClass('leaflet-bar btn btn-sm btn-outline-secondary')
121         .on('click', function (e) {
122           e.preventDefault();
123           e.stopPropagation();
124           $('#map-position').show();
125           $(container).hide();
126         });
127       $('#map-position-close a').on('click', function (e) {
128         e.preventDefault();
129         e.stopPropagation();
130         $('#map-position').hide();
131         $(container).show();
132       });
133
134       return container;
135     }
136   });
137
138   map.addControl(new MapPositionControl());
139
140
141
142
143
144   function update_viewbox_field() {
145     // hidden HTML field
146     $('input[name=viewbox]')
147       .val($('input#use_viewbox')
148         .prop('checked') ? map_viewbox_as_string() : '');
149   }
150
151   map.on('move', function () {
152     display_map_position();
153     update_viewbox_field();
154   });
155
156   map.on('mousemove', function (e) {
157     display_map_position(e.latlng);
158   });
159
160   map.on('click', function (e) {
161     last_click_latlng = e.latlng;
162     display_map_position();
163   });
164
165   map.on('load', function () {
166     display_map_position();
167   });
168
169   $('input#use_viewbox').on('change', function () {
170     update_viewbox_field();
171   });
172
173   $('input#option_bounded').on('change', function () {
174     $('input[name=bounded]')
175       .val($('input#option_bounded')
176         .prop('checked') ? '1' : '');
177   });
178
179   $('input#option_dedupe').on('change', function () {
180     $('input[name=dedupe]')
181       .val($('input#option_dedupe')
182         .prop('checked') ? '' : '0');
183   });
184
185   $('input[data-api-param]').on('change', function (e) {
186     $('input[name=' + $(e.target).data('api-param') + ']').val(e.target.value);
187   });
188
189
190   function get_result_element(position) {
191     return $('.result').eq(position);
192   }
193   // function marker_for_result(result) {
194   //   return L.marker([result.lat, result.lon], { riseOnHover: true, title: result.name });
195   // }
196   function circle_for_result(result) {
197     var cm_style = {
198       radius: 10,
199       weight: 2,
200       fillColor: '#ff7800',
201       color: 'blue',
202       opacity: 0.75,
203       clickable: !is_reverse_search
204     };
205     return L.circleMarker([result.lat, result.lon], cm_style);
206   }
207
208   var layerGroup = (new L.layerGroup()).addTo(map);
209
210   function highlight_result(position, bool_focus) {
211     var result = nominatim_results[position];
212     if (!result) { return; }
213     var result_el = get_result_element(position);
214
215     $('.result').removeClass('highlight');
216     result_el.addClass('highlight');
217
218     layerGroup.clearLayers();
219
220     if (result.lat) {
221       var circle = circle_for_result(result);
222       circle.on('click', function () {
223         highlight_result(position);
224       });
225       layerGroup.addLayer(circle);
226     }
227
228     if (result.boundingbox) {
229       var bbox = [
230         [result.boundingbox[0] * 1, result.boundingbox[2] * 1],
231         [result.boundingbox[1] * 1, result.boundingbox[3] * 1]
232       ];
233       map.fitBounds(bbox);
234
235       if (result.geojson && result.geojson.type.match(/(Polygon)|(Line)/)) {
236         //
237         var geojson_layer = L.geoJson(
238           parse_and_normalize_geojson_string(result.geojson),
239           {
240             // https://leafletjs.com/reference-1.0.3.html#path-option
241             style: function (/* feature */) {
242               return { interactive: false, color: 'blue' };
243             }
244           }
245         );
246         layerGroup.addLayer(geojson_layer);
247       }
248       // else {
249       //     var layer = L.rectangle(bounds, {color: "#ff7800", weight: 1} );
250       //     layerGroup.addLayer(layer);
251       // }
252     } else {
253       var result_coord = L.latLng(result.lat, result.lon);
254       if (result_coord) {
255         if (is_reverse_search) {
256           // console.dir([result_coord, [request_lat, request_lon]]);
257           // make sure the search coordinates are in the map view as well
258           map.fitBounds(
259             [result_coord, [request_lat, request_lon]],
260             {
261               padding: [50, 50],
262               maxZoom: map.getZoom()
263             }
264           );
265         } else {
266           map.panTo(result_coord, result.zoom || get_config_value('Map_Default_Zoom'));
267         }
268       }
269     }
270     if (bool_focus) {
271       $('#map').focus();
272     }
273   }
274
275
276   $('.result').on('click', function () {
277     highlight_result($(this).data('position'), true);
278   });
279
280   if (is_reverse_search) {
281     map.on('click', function (e) {
282       $('form input[name=lat]').val(e.latlng.lat);
283       $('form input[name=lon]').val(e.latlng.wrap().lng);
284       $('form').submit();
285     });
286
287     $('#switch-coords').on('click', function (e) {
288       e.preventDefault();
289       e.stopPropagation();
290       var lat = $('form input[name=lat]').val();
291       var lon = $('form input[name=lon]').val();
292       $('form input[name=lat]').val(lon);
293       $('form input[name=lon]').val(lat);
294       $('form').submit();
295     });
296   }
297
298   highlight_result(0, false);
299
300   // common mistake is to copy&paste latitude and longitude into the 'lat' search box
301   $('form input[name=lat]').on('change', function () {
302     var coords_split = $(this).val().split(',');
303     if (coords_split.length === 2) {
304       $(this).val(L.Util.trim(coords_split[0]));
305       $(this).siblings('input[name=lon]').val(L.Util.trim(coords_split[1]));
306     }
307   });
308 }
309
310
311
312 function search_page_load() {
313
314   var is_reverse_search = window.location.pathname.match(/reverse/);
315
316   var search_params = new URLSearchParams(window.location.search);
317
318   // return view('search', [
319   //     'sQuery' => $sQuery,
320   //     'bAsText' => '',
321   //     'sViewBox' => '',
322   //     'aSearchResults' => $aSearchResults,
323   //     'sMoreURL' => 'example.com',
324   //     'sDataDate' => $this->fetch_status_date(),
325   //     'sApiURL' => $url
326   // ]);
327
328   var api_request_params;
329   var context;
330
331   if (is_reverse_search) {
332     api_request_params = {
333       lat: search_params.get('lat'),
334       lon: search_params.get('lon'),
335       zoom: (search_params.get('zoom') > 1
336         ? search_params.get('zoom')
337         : get_config_value('Reverse_Default_Search_Zoom')),
338       format: 'jsonv2'
339     };
340
341     context = {
342       // aPlace: aPlace,
343       fLat: api_request_params.lat,
344       fLon: api_request_params.lon,
345       iZoom: (search_params.get('zoom') > 1
346         ? api_request_params.zoom
347         : get_config_value('Reverse_Default_Search_Zoom'))
348     };
349
350     update_html_title();
351     if (api_request_params.lat && api_request_params.lon) {
352
353       fetch_from_api('reverse', api_request_params, function (aPlace) {
354
355         if (aPlace.error) {
356           aPlace = null;
357         }
358
359         context.bSearchRan = true;
360         context.aPlace = aPlace;
361
362         render_template($('main'), 'reversepage-template', context);
363         update_html_title('Reverse result for '
364                             + api_request_params.lat
365                             + ','
366                             + api_request_params.lon);
367
368         init_map_on_search_page(
369           is_reverse_search,
370           [aPlace],
371           api_request_params.lat,
372           api_request_params.lon,
373           api_request_params.zoom
374         );
375
376         update_data_date();
377       });
378     } else {
379       render_template($('main'), 'reversepage-template', context);
380
381       init_map_on_search_page(
382         is_reverse_search,
383         [],
384         get_config_value('Map_Default_Lat'),
385         get_config_value('Map_Default_Lon'),
386         get_config_value('Map_Default_Zoom')
387       );
388     }
389
390   } else {
391     api_request_params = {
392       q: search_params.get('q'),
393       street: search_params.get('street'),
394       city: search_params.get('city'),
395       county: search_params.get('county'),
396       state: search_params.get('state'),
397       country: search_params.get('country'),
398       postalcode: search_params.get('postalcode'),
399       polygon_geojson: get_config_value('Search_AreaPolygons', false) ? 1 : 0,
400       viewbox: search_params.get('viewbox'),
401       bounded: search_params.get('bounded'),
402       dedupe: search_params.get('dedupe'),
403       'accept-language': search_params.get('accept-language'),
404       countrycodes: search_params.get('countrycodes'),
405       limit: search_params.get('limit'),
406       polygon_threshold: search_params.get('polygon_threshold'),
407       exclude_place_ids: search_params.get('exclude_place_ids'),
408       format: 'jsonv2'
409     };
410
411     context = {
412       sQuery: api_request_params.q,
413       sViewBox: search_params.get('viewbox'),
414       sBounded: search_params.get('bounded'),
415       sDedupe: search_params.get('dedupe'),
416       sLang: search_params.get('accept-language'),
417       sCCode: search_params.get('countrycodes'),
418       sLimit: search_params.get('limit'),
419       sPolyThreshold: search_params.get('polygon_threshold'),
420       env: {}
421     };
422
423     if (api_request_params.street || api_request_params.city || api_request_params.county
424       || api_request_params.state || api_request_params.country || api_request_params.postalcode) {
425       context.hStructured = {
426         street: api_request_params.street,
427         city: api_request_params.city,
428         county: api_request_params.county,
429         state: api_request_params.state,
430         country: api_request_params.country,
431         postalcode: api_request_params.postalcode
432       };
433     }
434
435     if (api_request_params.q || context.hStructured) {
436
437       fetch_from_api('search', api_request_params, function (aResults) {
438
439         context.bSearchRan = true;
440         context.aSearchResults = aResults;
441
442         // lonvia wrote: https://github.com/osm-search/nominatim-ui/issues/24
443         // I would suggest to remove the guessing and always show the link. Nominatim only returns
444         // one or two results when it believes the result to be a good enough match.
445         // if (aResults.length >= 10) {
446         var aExcludePlaceIds = [];
447         if (search_params.has('exclude_place_ids')) {
448           aExcludePlaceIds = search_params.get('exclude_place_ids').split(',');
449         }
450         for (var i = 0; i < aResults.length; i += 1) {
451           aExcludePlaceIds.push(aResults[i].place_id);
452         }
453         var parsed_url = new URLSearchParams(window.location.search);
454         parsed_url.set('exclude_place_ids', aExcludePlaceIds.join(','));
455         context.sMoreURL = '?' + parsed_url.toString();
456
457         render_template($('main'), 'searchpage-template', context);
458         update_html_title('Result for ' + api_request_params.q);
459
460         init_map_on_search_page(
461           is_reverse_search,
462           aResults,
463           get_config_value('Map_Default_Lat'),
464           get_config_value('Map_Default_Lon'),
465           get_config_value('Map_Default_Zoom')
466         );
467
468         $('#q').focus();
469
470         update_data_date();
471       });
472     } else {
473       render_template($('main'), 'searchpage-template', context);
474
475       init_map_on_search_page(
476         is_reverse_search,
477         [],
478         get_config_value('Map_Default_Lat'),
479         get_config_value('Map_Default_Lon'),
480         get_config_value('Map_Default_Zoom')
481       );
482     }
483   }
484 }
485
486