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