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