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