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