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