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