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