]> git.openstreetmap.org Git - nominatim-ui.git/blob - src/assets/js/searchpage.js
1061712a6cf0afe8ca9f82f34905cf6cd4d31cb3
[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#use_viewbox').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[name='query-selector']").click(function () {
174     var query_val = $("input[name='query-selector']:checked").val();
175     if (query_val === 'simple') {
176       $('div.form-group-simple').removeClass('hidden');
177       $('div.form-group-structured').addClass('hidden');
178       $('.form-group-structured').find('input:text').val('');
179     } else if (query_val === 'structured') {
180       console.log('here');
181       $('div.form-group-simple').addClass('hidden');
182       $('div.form-group-structured').removeClass('hidden');
183       $('.form-group-simple').find('input:text').val('');
184     }
185   });
186
187   function get_result_element(position) {
188     return $('.result').eq(position);
189   }
190   // function marker_for_result(result) {
191   //   return L.marker([result.lat, result.lon], { riseOnHover: true, title: result.name });
192   // }
193   function circle_for_result(result) {
194     var cm_style = {
195       radius: 10,
196       weight: 2,
197       fillColor: '#ff7800',
198       color: 'blue',
199       opacity: 0.75,
200       clickable: !is_reverse_search
201     };
202     return L.circleMarker([result.lat, result.lon], cm_style);
203   }
204
205   var layerGroup = (new L.layerGroup()).addTo(map);
206
207   function highlight_result(position, bool_focus) {
208     var result = nominatim_results[position];
209     if (!result) { return; }
210     var result_el = get_result_element(position);
211
212     $('.result').removeClass('highlight');
213     result_el.addClass('highlight');
214
215     layerGroup.clearLayers();
216
217     if (result.lat) {
218       var circle = circle_for_result(result);
219       circle.on('click', function () {
220         highlight_result(position);
221       });
222       layerGroup.addLayer(circle);
223     }
224
225     if (result.boundingbox) {
226       var bbox = [
227         [result.boundingbox[0] * 1, result.boundingbox[2] * 1],
228         [result.boundingbox[1] * 1, result.boundingbox[3] * 1]
229       ];
230       map.fitBounds(bbox);
231
232       if (result.geojson && result.geojson.type.match(/(Polygon)|(Line)/)) {
233         //
234         var geojson_layer = L.geoJson(
235           parse_and_normalize_geojson_string(result.geojson),
236           {
237             // https://leafletjs.com/reference-1.0.3.html#path-option
238             style: function (/* feature */) {
239               return { interactive: false, color: 'blue' };
240             }
241           }
242         );
243         layerGroup.addLayer(geojson_layer);
244       }
245       // else {
246       //     var layer = L.rectangle(bounds, {color: "#ff7800", weight: 1} );
247       //     layerGroup.addLayer(layer);
248       // }
249     } else {
250       var result_coord = L.latLng(result.lat, result.lon);
251       if (result_coord) {
252         if (is_reverse_search) {
253           // console.dir([result_coord, [request_lat, request_lon]]);
254           // make sure the search coordinates are in the map view as well
255           map.fitBounds(
256             [result_coord, [request_lat, request_lon]],
257             {
258               padding: [50, 50],
259               maxZoom: map.getZoom()
260             }
261           );
262         } else {
263           map.panTo(result_coord, result.zoom || get_config_value('Map_Default_Zoom'));
264         }
265       }
266     }
267     if (bool_focus) {
268       $('#map').focus();
269     }
270   }
271
272
273   $('.result').on('click', function () {
274     highlight_result($(this).data('position'), true);
275   });
276
277   if (is_reverse_search) {
278     map.on('click', function (e) {
279       $('form input[name=lat]').val(e.latlng.lat);
280       $('form input[name=lon]').val(e.latlng.wrap().lng);
281       $('form').submit();
282     });
283
284     $('#switch-coords').on('click', function (e) {
285       e.preventDefault();
286       e.stopPropagation();
287       var lat = $('form input[name=lat]').val();
288       var lon = $('form input[name=lon]').val();
289       $('form input[name=lat]').val(lon);
290       $('form input[name=lon]').val(lat);
291       $('form').submit();
292     });
293   }
294
295   highlight_result(0, false);
296
297   // common mistake is to copy&paste latitude and longitude into the 'lat' search box
298   $('form input[name=lat]').on('change', function () {
299     var coords_split = $(this).val().split(',');
300     if (coords_split.length === 2) {
301       $(this).val(L.Util.trim(coords_split[0]));
302       $(this).siblings('input[name=lon]').val(L.Util.trim(coords_split[1]));
303     }
304   });
305 }
306
307
308
309
310 jQuery(document).ready(function () {
311   //
312   if (!$('#search-page,#reverse-page').length) { return; }
313
314   var is_reverse_search = !!($('#reverse-page').length);
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.aPlace = aPlace;
360
361         render_template($('main'), 'reversepage-template', context);
362         update_html_title('Reverse result for '
363                             + api_request_params.lat
364                             + ','
365                             + api_request_params.lon);
366
367         init_map_on_search_page(
368           is_reverse_search,
369           [aPlace],
370           api_request_params.lat,
371           api_request_params.lon,
372           api_request_params.zoom
373         );
374
375         update_data_date();
376       });
377     } else {
378       render_template($('main'), 'reversepage-template', context);
379
380       init_map_on_search_page(
381         is_reverse_search,
382         [],
383         get_config_value('Map_Default_Lat'),
384         get_config_value('Map_Default_Lon'),
385         get_config_value('Map_Default_Zoom')
386       );
387     }
388
389   } else {
390     api_request_params = {
391       q: search_params.get('q'),
392       street: search_params.get('street'),
393       city: search_params.get('city'),
394       county: search_params.get('county'),
395       state: search_params.get('state'),
396       country: search_params.get('country'),
397       postalcode: search_params.get('postalcode'),
398       polygon_geojson: search_params.get('polygon_geojson') ? 1 : 0,
399       viewbox: search_params.get('viewbox'),
400       exclude_place_ids: search_params.get('exclude_place_ids'),
401       format: 'jsonv2'
402     };
403
404     context = {
405       sQuery: api_request_params.q,
406       sViewBox: search_params.get('viewbox'),
407       env: {}
408     };
409
410     if (api_request_params.street || api_request_params.city || api_request_params.county
411       || api_request_params.state || api_request_params.country || api_request_params.postalcode) {
412       context.hStructured = {
413         street: api_request_params.street,
414         city: api_request_params.city,
415         county: api_request_params.county,
416         state: api_request_params.state,
417         country: api_request_params.country,
418         postalcode: api_request_params.postalcode
419       };
420     }
421
422     if (api_request_params.q || context.hStructured) {
423
424       fetch_from_api('search', api_request_params, function (aResults) {
425
426         context.aSearchResults = aResults;
427
428         if (aResults.length >= 10) {
429           var aExcludePlaceIds = [];
430           if (search_params.has('exclude_place_ids')) {
431             aExcludePlaceIds.search_params.get('exclude_place_ids').split(',');
432           }
433           for (var i = 0; i < aResults.length; i += 1) {
434             aExcludePlaceIds.push(aResults[i].place_id);
435           }
436
437           var parsed_url = new URLSearchParams(window.location.search);
438           parsed_url.set('exclude_place_ids', aExcludePlaceIds.join(','));
439           context.sMoreURL = '?' + parsed_url.toString();
440         }
441
442         render_template($('main'), 'searchpage-template', context);
443         update_html_title('Result for ' + api_request_params.q);
444
445         init_map_on_search_page(
446           is_reverse_search,
447           aResults,
448           get_config_value('Map_Default_Lat'),
449           get_config_value('Map_Default_Lon'),
450           get_config_value('Map_Default_Zoom')
451         );
452
453         $('#q').focus();
454
455         update_data_date();
456       });
457     } else {
458       render_template($('main'), 'searchpage-template', context);
459
460       init_map_on_search_page(
461         is_reverse_search,
462         [],
463         get_config_value('Map_Default_Lat'),
464         get_config_value('Map_Default_Lon'),
465         get_config_value('Map_Default_Zoom')
466       );
467     }
468   }
469 });