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