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