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