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