]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/search.js
Refactor search JS
[rails.git] / app / assets / javascripts / index / search.js
1 function initializeSearch(map) {
2   $("#search_form").submit(submitSearch);
3
4   if ($("#query").val()) {
5     $("#search_form").submit();
6   }
7
8   // Focus the search field for browsers that don't support
9   // the HTML5 'autofocus' attribute
10   if (!("autofocus" in document.createElement("input"))) {
11     $("#query").focus();
12   }
13
14   $("#sidebar_content").on("click", ".search_results_entry a.set_position", clickSearchResult);
15
16   var marker = L.marker([0, 0], {icon: getUserIcon()});
17
18   function submitSearch(e) {
19     e.preventDefault();
20
21     var bounds = map.getBounds();
22
23     $("#sidebar_title").html(I18n.t('site.sidebar.search_results'));
24     $("#sidebar_content").load($(this).attr("action"), {
25       query: $("#query").val(),
26       minlon: bounds.getWest(),
27       minlat: bounds.getSouth(),
28       maxlon: bounds.getEast(),
29       maxlat: bounds.getNorth()
30     });
31
32     openSidebar();
33   }
34
35   function clickSearchResult(e) {
36     e.preventDefault();
37
38     var data = $(this).data(),
39       center = L.latLng(data.lat, data.lon);
40
41     if (data.minLon && data.minLat && data.maxLon && data.maxLat) {
42       map.fitBounds([[data.minLat, data.minLon],
43                      [data.maxLat, data.maxLon]]);
44     } else {
45       map.setView(center, data.zoom);
46     }
47
48     marker
49       .setLatLng(center)
50       .addTo(map);
51
52     if (data.type && data.id) {
53       map.addObject(data, { zoom: false, style: { opacity: 0.2, fill: false } });
54     }
55   }
56 }