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