]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index_modules/query.js
Remove dangling top-level block
[rails.git] / app / assets / javascripts / index_modules / query.js
1 export default function (map) {
2   const uninterestingTags = ["source", "source_ref", "source:ref", "history", "attribution", "created_by", "tiger:county", "tiger:tlid", "tiger:upload_uuid", "KSJ2:curve_id", "KSJ2:lat", "KSJ2:lon", "KSJ2:coordinate", "KSJ2:filename", "note:ja"];
3   let marker;
4
5   const featureStyle = {
6     color: "#FF6200",
7     weight: 4,
8     opacity: 1,
9     fillOpacity: 0.5,
10     interactive: false
11   };
12
13   function showResultGeometry() {
14     const geometry = $(this).data("geometry");
15     if (geometry) map.addLayer(geometry);
16     $(this).addClass("selected");
17   }
18
19   function hideResultGeometry() {
20     const geometry = $(this).data("geometry");
21     if (geometry) map.removeLayer(geometry);
22     $(this).removeClass("selected");
23   }
24
25   $("#sidebar_content")
26     .on("mouseover", ".query-results a", showResultGeometry)
27     .on("mouseout", ".query-results a", hideResultGeometry);
28
29   function interestingFeature(feature) {
30     if (feature.tags) {
31       for (const key in feature.tags) {
32         if (uninterestingTags.indexOf(key) < 0) {
33           return true;
34         }
35       }
36     }
37
38     return false;
39   }
40
41   function featurePrefix(feature) {
42     const tags = feature.tags;
43     let prefix = "";
44
45     if (tags.boundary === "administrative" && (tags.border_type || tags.admin_level)) {
46       prefix = OSM.i18n.t("geocoder.search_osm_nominatim.border_types." + tags.border_type, {
47         defaultValue: OSM.i18n.t("geocoder.search_osm_nominatim.admin_levels.level" + tags.admin_level, {
48           defaultValue: OSM.i18n.t("geocoder.search_osm_nominatim.prefix.boundary.administrative")
49         })
50       });
51     } else {
52       const prefixes = OSM.i18n.t("geocoder.search_osm_nominatim.prefix");
53
54       for (const key in tags) {
55         const value = tags[key];
56
57         if (prefixes[key]) {
58           if (prefixes[key][value]) {
59             return prefixes[key][value];
60           }
61         }
62       }
63
64       for (const key in tags) {
65         const value = tags[key];
66
67         if (prefixes[key]) {
68           const first = value.slice(0, 1).toUpperCase(),
69                 rest = value.slice(1).replace(/_/g, " ");
70
71           return first + rest;
72         }
73       }
74     }
75
76     if (!prefix) {
77       prefix = OSM.i18n.t("javascripts.query." + feature.type);
78     }
79
80     return prefix;
81   }
82
83   function featureName(feature) {
84     const tags = feature.tags,
85           localeKeys = OSM.preferred_languages.map(locale => `name:${locale}`);
86
87     for (const key of [...localeKeys, "name", "ref", "addr:housename"]) {
88       if (tags[key]) return tags[key];
89     }
90     if (tags["addr:housenumber"] && tags["addr:street"]) return `${tags["addr:housenumber"]} ${tags["addr:street"]}`;
91
92     return "#" + feature.id;
93   }
94
95   function featureGeometry(feature) {
96     switch (feature.type) {
97       case "node":
98         if (!feature.lat || !feature.lon) return;
99         return L.circleMarker([feature.lat, feature.lon], featureStyle);
100       case "way":
101         if (!feature.geometry?.length) return;
102         return L.polyline(feature.geometry.filter(p => p).map(p => [p.lat, p.lon]), featureStyle);
103       case "relation":
104         if (!feature.members?.length) return;
105         return L.featureGroup(feature.members.map(featureGeometry).filter(g => g));
106     }
107   }
108
109   function runQuery(query, $section, merge, compare) {
110     const $ul = $section.find("ul");
111
112     $ul.empty();
113     $section.show();
114
115     if ($section.data("ajax")) {
116       $section.data("ajax").abort();
117     }
118
119     $section.data("ajax", new AbortController());
120     fetch(OSM.OVERPASS_URL, {
121       method: "POST",
122       body: new URLSearchParams({
123         data: "[timeout:10][out:json];" + query
124       }),
125       credentials: OSM.OVERPASS_CREDENTIALS ? "include" : "same-origin",
126       signal: $section.data("ajax").signal
127     })
128       .then(response => {
129         if (response.ok) {
130           return response.json();
131         }
132         throw new Error(response.statusText || response.status);
133       })
134       .then(function (results) {
135         let elements = results.elements;
136
137         $section.find(".loader").hide();
138
139         // Make Overpass-specific bounds to Leaflet compatible
140         for (const element of elements) {
141           if (!element.bounds) continue;
142           if (element.bounds.maxlon >= element.bounds.minlon) continue;
143           element.bounds.maxlon += 360;
144         }
145
146         if (merge) {
147           elements = Object.values(elements.reduce(function (hash, element) {
148             const key = element.type + element.id;
149             if ("geometry" in element) delete element.bounds;
150             hash[key] = { ...hash[key], ...element };
151             return hash;
152           }, {}));
153         }
154
155         if (compare) {
156           elements = elements.sort(compare);
157         }
158
159         for (const element of elements) {
160           if (!interestingFeature(element)) continue;
161
162           const $li = $("<li>")
163             .addClass("list-group-item list-group-item-action")
164             .text(featurePrefix(element) + " ")
165             .appendTo($ul);
166
167           $("<a>")
168             .addClass("stretched-link")
169             .attr("href", "/" + element.type + "/" + element.id)
170             .data("geometry", featureGeometry(element))
171             .text(featureName(element))
172             .appendTo($li);
173         }
174
175         if (results.remark) renderError($ul, results.remark);
176
177         if ($ul.find("li").length === 0) {
178           $("<li>")
179             .addClass("list-group-item")
180             .text(OSM.i18n.t("javascripts.query.nothing_found"))
181             .appendTo($ul);
182         }
183       })
184       .catch(function (error) {
185         if (error.name === "AbortError") return;
186
187         $section.find(".loader").hide();
188
189         renderError($ul, error.message);
190       });
191   }
192
193   function renderError($ul, errorMessage) {
194     $("<li>")
195       .addClass("list-group-item")
196       .text(OSM.i18n.t("javascripts.query.error", { server: OSM.OVERPASS_URL, error: errorMessage }))
197       .appendTo($ul);
198   }
199
200   function size({ maxlon, minlon, maxlat, minlat }) {
201     return (maxlon - minlon) * (maxlat - minlat);
202   }
203
204   /*
205    * To find nearby objects we ask overpass for the union of the
206    * following sets:
207    *
208    *   node(around:<radius>,<lat>,<lng>)
209    *   way(around:<radius>,<lat>,<lng>)
210    *   relation(around:<radius>,<lat>,<lng>)
211    *
212    * to find enclosing objects we first find all the enclosing areas:
213    *
214    *   is_in(<lat>,<lng>)->.a
215    *
216    * and then return the union of the following sets:
217    *
218    *   relation(pivot.a)
219    *   way(pivot.a)
220    *
221    * In both cases we then ask to retrieve tags and the geometry
222    * for each object.
223    */
224   function queryOverpass(latlng) {
225     const bounds = map.getBounds(),
226           zoom = map.getZoom(),
227           sw = OSM.cropLocation(bounds.getSouthWest(), zoom),
228           ne = OSM.cropLocation(bounds.getNorthEast(), zoom),
229           bbox = `${sw.lat},${sw.lng},${ne.lat},${ne.lng}`,
230           geom = `geom(${bbox})`,
231           radius = 10 * Math.pow(1.5, 19 - zoom),
232           here = `(around:${radius},${latlng})`,
233           enclosed = "(pivot.a);out tags bb",
234           nearby = `(node${here};way${here};);out tags ${geom};relation${here};out ${geom};`,
235           isin = `is_in(${latlng})->.a;way${enclosed};out ids ${geom};relation${enclosed};`;
236
237     $("#sidebar_content .query-intro")
238       .hide();
239
240     if (marker) map.removeLayer(marker);
241     marker = L.circle(L.latLng(latlng).wrap(), {
242       radius: radius,
243       className: "query-marker",
244       ...featureStyle
245     }).addTo(map);
246
247     runQuery(nearby, $("#query-nearby"), false);
248     runQuery(isin, $("#query-isin"), true, (feature1, feature2) => size(feature1.bounds) - size(feature2.bounds));
249   }
250
251   const page = {};
252
253   page.pushstate = page.popstate = function (path) {
254     OSM.loadSidebarContent(path, function () {
255       page.load(path, true);
256     });
257   };
258
259   page.load = function (path, noCentre) {
260     const params = new URLSearchParams(path.substring(path.indexOf("?"))),
261           latlng = L.latLng(params.get("lat"), params.get("lon"));
262
263     if (!location.hash && !noCentre && !map.getBounds().contains(latlng)) {
264       OSM.router.withoutMoveListener(function () {
265         map.setView(latlng, 15);
266       });
267     }
268
269     queryOverpass([params.get("lat"), params.get("lon")]);
270   };
271
272   page.unload = function (sameController) {
273     if (!sameController) {
274       $("#sidebar_content .query-results a.selected").each(hideResultGeometry);
275     }
276   };
277
278   return page;
279 }