]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/query.js
Restructure featureGeometry for clarity
[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     // TODO: Localize format to country of address
116     if (tags["addr:housenumber"] && tags["addr:street"]) return `${tags["addr:housenumber"]} ${tags["addr:street"]}`;
117
118     return "#" + feature.id;
119   }
120
121   function featureGeometry(feature) {
122     switch (feature.type) {
123       case "node":
124         if (!feature.lat || !feature.lon) return;
125         return L.circleMarker([feature.lat, feature.lon], featureStyle);
126       case "way":
127         if (!feature.geometry?.length) return;
128         return L.polyline(feature.geometry.filter(p => p).map(p => [p.lat, p.lon]), featureStyle);
129       case "relation":
130         if (!feature.members?.length) return;
131         return L.featureGroup(feature.members.map(featureGeometry).filter(g => g));
132     }
133   }
134
135   function runQuery(latlng, radius, query, $section, merge, compare) {
136     const $ul = $section.find("ul");
137
138     $ul.empty();
139     $section.show();
140
141     if ($section.data("ajax")) {
142       $section.data("ajax").abort();
143     }
144
145     $section.data("ajax", new AbortController());
146     fetch(OSM.OVERPASS_URL, {
147       method: "POST",
148       body: new URLSearchParams({
149         data: "[timeout:10][out:json];" + query
150       }),
151       credentials: OSM.OVERPASS_CREDENTIALS ? "include" : "same-origin",
152       signal: $section.data("ajax").signal
153     })
154       .then(response => response.json())
155       .then(function (results) {
156         let elements;
157
158         $section.find(".loader").hide();
159
160         if (merge) {
161           elements = Object.values(results.elements.reduce(function (hash, element) {
162             const key = element.type + element.id;
163             if ("geometry" in element) {
164               delete element.bounds;
165             }
166             hash[key] = $.extend({}, hash[key], element);
167             return hash;
168           }, {}));
169         } else {
170           elements = results.elements;
171         }
172
173         if (compare) {
174           elements = elements.sort(compare);
175         }
176
177         for (const element of elements) {
178           if (!interestingFeature(element)) continue;
179
180           const $li = $("<li>")
181             .addClass("list-group-item list-group-item-action")
182             .text(featurePrefix(element) + " ")
183             .appendTo($ul);
184
185           $("<a>")
186             .addClass("stretched-link")
187             .attr("href", "/" + element.type + "/" + element.id)
188             .data("geometry", featureGeometry(element))
189             .text(featureName(element))
190             .appendTo($li);
191         }
192
193         if (results.remark) renderError($ul, results.remark);
194
195         if ($ul.find("li").length === 0) {
196           $("<li>")
197             .addClass("list-group-item")
198             .text(OSM.i18n.t("javascripts.query.nothing_found"))
199             .appendTo($ul);
200         }
201       })
202       .catch(function (error) {
203         if (error.name === "AbortError") return;
204
205         $section.find(".loader").hide();
206
207         renderError($ul, error.message);
208       });
209   }
210
211   function renderError($ul, errorMessage) {
212     $("<li>")
213       .addClass("list-group-item")
214       .text(OSM.i18n.t("javascripts.query.error", { server: OSM.OVERPASS_URL, error: errorMessage }))
215       .appendTo($ul);
216   }
217
218   function featureArea({ bounds }) {
219     const height = bounds.maxlat - bounds.minlat;
220     let width = bounds.maxlon - bounds.minlon;
221
222     if (width < 0) width += 360;
223     return width * height;
224   }
225
226   /*
227    * To find nearby objects we ask overpass for the union of the
228    * following sets:
229    *
230    *   node(around:<radius>,<lat>,<lng>)
231    *   way(around:<radius>,<lat>,<lng>)
232    *   relation(around:<radius>,<lat>,<lng>)
233    *
234    * to find enclosing objects we first find all the enclosing areas:
235    *
236    *   is_in(<lat>,<lng>)->.a
237    *
238    * and then return the union of the following sets:
239    *
240    *   relation(pivot.a)
241    *   way(pivot.a)
242    *
243    * In both cases we then ask to retrieve tags and the geometry
244    * for each object.
245    */
246   function queryOverpass(lat, lng) {
247     const latlng = L.latLng(lat, lng).wrap(),
248           bounds = map.getBounds(),
249           zoom = map.getZoom(),
250           bbox = [bounds.getSouthWest(), bounds.getNorthEast()]
251             .map(c => OSM.cropLocation(c, zoom))
252             .join(),
253           geombbox = "geom(" + bbox + ");",
254           radius = 10 * Math.pow(1.5, 19 - zoom),
255           around = "(around:" + radius + "," + lat + "," + lng + ")",
256           nodes = "node" + around,
257           ways = "way" + around,
258           relations = "relation" + around,
259           nearby = "(" + nodes + ";" + ways + ";);out tags " + geombbox + relations + ";out " + geombbox,
260           isin = "is_in(" + lat + "," + lng + ")->.a;way(pivot.a);out tags bb;out ids " + geombbox + "relation(pivot.a);out tags bb;";
261
262     $("#sidebar_content .query-intro")
263       .hide();
264
265     if (marker) map.removeLayer(marker);
266     marker = L.circle(latlng, {
267       radius: radius,
268       className: "query-marker",
269       ...featureStyle
270     }).addTo(map);
271
272     runQuery(latlng, radius, nearby, $("#query-nearby"), false);
273     runQuery(latlng, radius, isin, $("#query-isin"), true, (feature1, feature2) => featureArea(feature1) - featureArea(feature2));
274   }
275
276   function clickHandler(e) {
277     const [lat, lon] = OSM.cropLocation(e.latlng, map.getZoom());
278
279     OSM.router.route("/query?" + new URLSearchParams({ lat, lon }));
280   }
281
282   function enableQueryMode() {
283     control.addClass("active");
284     map.on("click", clickHandler);
285     $(map.getContainer()).addClass("query-active");
286   }
287
288   function disableQueryMode() {
289     if (marker) map.removeLayer(marker);
290     $(map.getContainer()).removeClass("query-active").removeClass("query-disabled");
291     map.off("click", clickHandler);
292     control.removeClass("active");
293   }
294
295   const page = {};
296
297   page.pushstate = page.popstate = function (path) {
298     OSM.loadSidebarContent(path, function () {
299       page.load(path, true);
300     });
301   };
302
303   page.load = function (path, noCentre) {
304     const params = new URLSearchParams(path.substring(path.indexOf("?"))),
305           latlng = L.latLng(params.get("lat"), params.get("lon"));
306
307     if (!location.hash && !noCentre && !map.getBounds().contains(latlng)) {
308       OSM.router.withoutMoveListener(function () {
309         map.setView(latlng, 15);
310       });
311     }
312
313     queryOverpass(params.get("lat"), params.get("lon"));
314   };
315
316   page.unload = function (sameController) {
317     if (!sameController) {
318       disableQueryMode();
319       $("#sidebar_content .query-results a.selected").each(hideResultGeometry);
320     }
321   };
322
323   return page;
324 };