]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/query.js
Use Object.values in overpass query element merge
[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 compareSize(feature1, feature2) {
228     const width1 = feature1.bounds.maxlon - feature1.bounds.minlon,
229           height1 = feature1.bounds.maxlat - feature1.bounds.minlat,
230           area1 = width1 * height1,
231           width2 = feature2.bounds.maxlat - feature2.bounds.minlat,
232           height2 = feature2.bounds.maxlat - feature2.bounds.minlat,
233           area2 = width2 * height2;
234
235     return area1 - area2;
236   }
237
238   /*
239    * To find nearby objects we ask overpass for the union of the
240    * following sets:
241    *
242    *   node(around:<radius>,<lat>,<lng>)
243    *   way(around:<radius>,<lat>,<lng>)
244    *   relation(around:<radius>,<lat>,<lng>)
245    *
246    * to find enclosing objects we first find all the enclosing areas:
247    *
248    *   is_in(<lat>,<lng>)->.a
249    *
250    * and then return the union of the following sets:
251    *
252    *   relation(pivot.a)
253    *   way(pivot.a)
254    *
255    * In both cases we then ask to retrieve tags and the geometry
256    * for each object.
257    */
258   function queryOverpass(lat, lng) {
259     const latlng = L.latLng(lat, lng).wrap(),
260           bounds = map.getBounds().wrap(),
261           zoom = map.getZoom(),
262           bbox = [bounds.getSouthWest(), bounds.getNorthEast()]
263             .map(c => OSM.cropLocation(c, zoom))
264             .join(),
265           geombbox = "geom(" + bbox + ");",
266           radius = 10 * Math.pow(1.5, 19 - zoom),
267           around = "(around:" + radius + "," + lat + "," + lng + ")",
268           nodes = "node" + around,
269           ways = "way" + around,
270           relations = "relation" + around,
271           nearby = "(" + nodes + ";" + ways + ";);out tags " + geombbox + relations + ";out " + geombbox,
272           isin = "is_in(" + lat + "," + lng + ")->.a;way(pivot.a);out tags bb;out ids " + geombbox + "relation(pivot.a);out tags bb;";
273
274     $("#sidebar_content .query-intro")
275       .hide();
276
277     if (marker) map.removeLayer(marker);
278     marker = L.circle(latlng, {
279       radius: radius,
280       className: "query-marker",
281       ...featureStyle
282     }).addTo(map);
283
284     runQuery(latlng, radius, nearby, $("#query-nearby"), false);
285     runQuery(latlng, radius, isin, $("#query-isin"), true, compareSize);
286   }
287
288   function clickHandler(e) {
289     const [lat, lon] = OSM.cropLocation(e.latlng, map.getZoom());
290
291     OSM.router.route("/query?" + new URLSearchParams({ lat, lon }));
292   }
293
294   function enableQueryMode() {
295     control.addClass("active");
296     map.on("click", clickHandler);
297     $(map.getContainer()).addClass("query-active");
298   }
299
300   function disableQueryMode() {
301     if (marker) map.removeLayer(marker);
302     $(map.getContainer()).removeClass("query-active").removeClass("query-disabled");
303     map.off("click", clickHandler);
304     control.removeClass("active");
305   }
306
307   const page = {};
308
309   page.pushstate = page.popstate = function (path) {
310     OSM.loadSidebarContent(path, function () {
311       page.load(path, true);
312     });
313   };
314
315   page.load = function (path, noCentre) {
316     const params = new URLSearchParams(path.substring(path.indexOf("?"))),
317           latlng = L.latLng(params.get("lat"), params.get("lon"));
318
319     if (!location.hash && !noCentre && !map.getBounds().contains(latlng)) {
320       OSM.router.withoutMoveListener(function () {
321         map.setView(latlng, 15);
322       });
323     }
324
325     queryOverpass(params.get("lat"), params.get("lon"));
326   };
327
328   page.unload = function (sameController) {
329     if (!sameController) {
330       disableQueryMode();
331       $("#sidebar_content .query-results a.selected").each(hideResultGeometry);
332     }
333   };
334
335   return page;
336 };