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