]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/query.js
Merge remote-tracking branch 'upstream/pull/4717'
[rails.git] / app / assets / javascripts / index / query.js
1 //= require jquery-simulate/jquery.simulate
2 //= require qs/dist/qs
3
4 OSM.Query = function (map) {
5   var url = OSM.OVERPASS_URL,
6       credentials = OSM.OVERPASS_CREDENTIALS,
7       queryButton = $(".control-query .control-button"),
8       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"],
9       marker;
10
11   var featureStyle = {
12     color: "#FF6200",
13     weight: 4,
14     opacity: 1,
15     fillOpacity: 0.5,
16     interactive: false
17   };
18
19   queryButton.on("click", function (e) {
20     e.preventDefault();
21     e.stopPropagation();
22
23     if (queryButton.hasClass("active")) {
24       disableQueryMode();
25     } else if (!queryButton.hasClass("disabled")) {
26       enableQueryMode();
27     }
28   }).on("disabled", function () {
29     if (queryButton.hasClass("active")) {
30       map.off("click", clickHandler);
31       $(map.getContainer()).removeClass("query-active").addClass("query-disabled");
32       $(this).tooltip("show");
33     }
34   }).on("enabled", function () {
35     if (queryButton.hasClass("active")) {
36       map.on("click", clickHandler);
37       $(map.getContainer()).removeClass("query-disabled").addClass("query-active");
38       $(this).tooltip("hide");
39     }
40   });
41
42   function showResultGeometry() {
43     var geometry = $(this).data("geometry");
44     if (geometry) map.addLayer(geometry);
45     $(this).addClass("selected");
46   }
47
48   function hideResultGeometry() {
49     var geometry = $(this).data("geometry");
50     if (geometry) map.removeLayer(geometry);
51     $(this).removeClass("selected");
52   }
53
54   $("#sidebar_content")
55     .on("mouseover", ".query-results li.query-result", showResultGeometry)
56     .on("mouseout", ".query-results li.query-result", hideResultGeometry)
57     .on("mousedown", ".query-results li.query-result", function () {
58       var moved = false;
59       $(this).one("click", function (e) {
60         if (!moved) {
61           var geometry = $(this).data("geometry");
62           if (geometry) map.removeLayer(geometry);
63
64           if (!$(e.target).is("a")) {
65             $(this).find("a").simulate("click", e);
66           }
67         }
68       }).one("mousemove", function () {
69         moved = true;
70       });
71     });
72
73   function interestingFeature(feature) {
74     if (feature.tags) {
75       for (var key in feature.tags) {
76         if (uninterestingTags.indexOf(key) < 0) {
77           return true;
78         }
79       }
80     }
81
82     return false;
83   }
84
85   function featurePrefix(feature) {
86     var tags = feature.tags;
87     var prefix = "";
88
89     if (tags.boundary === "administrative" && tags.admin_level) {
90       prefix = I18n.t("geocoder.search_osm_nominatim.admin_levels.level" + tags.admin_level, {
91         defaultValue: I18n.t("geocoder.search_osm_nominatim.prefix.boundary.administrative")
92       });
93     } else {
94       var prefixes = I18n.t("geocoder.search_osm_nominatim.prefix");
95       var key, value;
96
97       for (key in tags) {
98         value = tags[key];
99
100         if (prefixes[key]) {
101           if (prefixes[key][value]) {
102             return prefixes[key][value];
103           }
104         }
105       }
106
107       for (key in tags) {
108         value = tags[key];
109
110         if (prefixes[key]) {
111           var first = value.slice(0, 1).toUpperCase(),
112               rest = value.slice(1).replace(/_/g, " ");
113
114           return first + rest;
115         }
116       }
117     }
118
119     if (!prefix) {
120       prefix = I18n.t("javascripts.query." + feature.type);
121     }
122
123     return prefix;
124   }
125
126   function featureName(feature) {
127     var tags = feature.tags,
128         locales = OSM.preferred_languages;
129
130     for (var i = 0; i < locales.length; i++) {
131       if (tags["name:" + locales[i]]) {
132         return tags["name:" + locales[i]];
133       }
134     }
135
136     if (tags.name) {
137       return tags.name;
138     } else if (tags.ref) {
139       return tags.ref;
140     } else if (tags["addr:housename"]) {
141       return tags["addr:housename"];
142     } else if (tags["addr:housenumber"] && tags["addr:street"]) {
143       return tags["addr:housenumber"] + " " + tags["addr:street"];
144     } else {
145       return "#" + feature.id;
146     }
147   }
148
149   function featureGeometry(feature) {
150     var geometry;
151
152     if (feature.type === "node" && feature.lat && feature.lon) {
153       geometry = L.circleMarker([feature.lat, feature.lon], featureStyle);
154     } else if (feature.type === "way" && feature.geometry && feature.geometry.length > 0) {
155       geometry = L.polyline(feature.geometry.filter(function (point) {
156         return point !== null;
157       }).map(function (point) {
158         return [point.lat, point.lon];
159       }), featureStyle);
160     } else if (feature.type === "relation" && feature.members) {
161       geometry = L.featureGroup(feature.members.map(featureGeometry).filter(function (geometry) {
162         return typeof geometry !== "undefined";
163       }));
164     }
165
166     return geometry;
167   }
168
169   function runQuery(latlng, radius, query, $section, merge, compare) {
170     var $ul = $section.find("ul");
171
172     $ul.empty();
173     $section.show();
174
175     if ($section.data("ajax")) {
176       $section.data("ajax").abort();
177     }
178
179     $section.data("ajax", $.ajax({
180       url: url,
181       method: "POST",
182       data: {
183         data: "[timeout:10][out:json];" + query
184       },
185       xhrFields: {
186         withCredentials: credentials
187       },
188       success: function (results) {
189         var elements;
190
191         $section.find(".loader").hide();
192
193         if (merge) {
194           elements = results.elements.reduce(function (hash, element) {
195             var key = element.type + element.id;
196             if ("geometry" in element) {
197               delete element.bounds;
198             }
199             hash[key] = $.extend({}, hash[key], element);
200             return hash;
201           }, {});
202
203           elements = Object.keys(elements).map(function (key) {
204             return elements[key];
205           });
206         } else {
207           elements = results.elements;
208         }
209
210         if (compare) {
211           elements = elements.sort(compare);
212         }
213
214         for (var i = 0; i < elements.length; i++) {
215           var element = elements[i];
216
217           if (interestingFeature(element)) {
218             var $li = $("<li>")
219               .addClass("query-result list-group-item list-group-item-action")
220               .data("geometry", featureGeometry(element))
221               .text(featurePrefix(element) + " ")
222               .appendTo($ul);
223
224             $("<a>")
225               .attr("href", "/" + element.type + "/" + element.id)
226               .text(featureName(element))
227               .appendTo($li);
228           }
229         }
230
231         if (results.remark) {
232           $("<li>")
233             .addClass("query-result list-group-item list-group-item-action")
234             .text(I18n.t("javascripts.query.error", { server: url, error: results.remark }))
235             .appendTo($ul);
236         }
237
238         if ($ul.find("li").length === 0) {
239           $("<li>")
240             .addClass("query-result list-group-item list-group-item-action")
241             .text(I18n.t("javascripts.query.nothing_found"))
242             .appendTo($ul);
243         }
244       },
245       error: function (xhr, status, error) {
246         $section.find(".loader").hide();
247
248         $("<li>")
249           .addClass("query-result list-group-item list-group-item-action")
250           .text(I18n.t("javascripts.query." + status, { server: url, error: error }))
251           .appendTo($ul);
252       }
253     }));
254   }
255
256   function compareSize(feature1, feature2) {
257     var width1 = feature1.bounds.maxlon - feature1.bounds.minlon,
258         height1 = feature1.bounds.maxlat - feature1.bounds.minlat,
259         area1 = width1 * height1,
260         width2 = feature2.bounds.maxlat - feature2.bounds.minlat,
261         height2 = feature2.bounds.maxlat - feature2.bounds.minlat,
262         area2 = width2 * height2;
263
264     return area1 - area2;
265   }
266
267   /*
268    * To find nearby objects we ask overpass for the union of the
269    * following sets:
270    *
271    *   node(around:<radius>,<lat>,lng>)
272    *   way(around:<radius>,<lat>,lng>)
273    *   relation(around:<radius>,<lat>,lng>)
274    *
275    * to find enclosing objects we first find all the enclosing areas:
276    *
277    *   is_in(<lat>,<lng>)->.a
278    *
279    * and then return the union of the following sets:
280    *
281    *   relation(pivot.a)
282    *   way(pivot.a)
283    *
284    * In both cases we then ask to retrieve tags and the geometry
285    * for each object.
286    */
287   function queryOverpass(lat, lng) {
288     var latlng = L.latLng(lat, lng).wrap(),
289         bounds = map.getBounds().wrap(),
290         precision = OSM.zoomPrecision(map.getZoom()),
291         bbox = bounds.getSouth().toFixed(precision) + "," +
292                bounds.getWest().toFixed(precision) + "," +
293                bounds.getNorth().toFixed(precision) + "," +
294                bounds.getEast().toFixed(precision),
295         radius = 10 * Math.pow(1.5, 19 - map.getZoom()),
296         around = "around:" + radius + "," + lat + "," + lng,
297         nodes = "node(" + around + ")",
298         ways = "way(" + around + ")",
299         relations = "relation(" + around + ")",
300         nearby = "(" + nodes + ";" + ways + ";);out tags geom(" + bbox + ");" + relations + ";out geom(" + bbox + ");",
301         isin = "is_in(" + lat + "," + lng + ")->.a;way(pivot.a);out tags bb;out ids geom(" + bbox + ");relation(pivot.a);out tags bb;";
302
303     $("#sidebar_content .query-intro")
304       .hide();
305
306     if (marker) map.removeLayer(marker);
307     marker = L.circle(latlng, radius, featureStyle).addTo(map);
308
309     $(document).everyTime(75, "fadeQueryMarker", function (i) {
310       if (i === 10) {
311         map.removeLayer(marker);
312       } else {
313         marker.setStyle({
314           opacity: 1 - (i * 0.1),
315           fillOpacity: 0.5 - (i * 0.05)
316         });
317       }
318     }, 10);
319
320     runQuery(latlng, radius, nearby, $("#query-nearby"), false);
321     runQuery(latlng, radius, isin, $("#query-isin"), true, compareSize);
322   }
323
324   function clickHandler(e) {
325     var precision = OSM.zoomPrecision(map.getZoom()),
326         latlng = e.latlng.wrap(),
327         lat = latlng.lat.toFixed(precision),
328         lng = latlng.lng.toFixed(precision);
329
330     OSM.router.route("/query?lat=" + lat + "&lon=" + lng);
331   }
332
333   function enableQueryMode() {
334     queryButton.addClass("active");
335     map.on("click", clickHandler);
336     $(map.getContainer()).addClass("query-active");
337   }
338
339   function disableQueryMode() {
340     if (marker) map.removeLayer(marker);
341     $(map.getContainer()).removeClass("query-active").removeClass("query-disabled");
342     map.off("click", clickHandler);
343     queryButton.removeClass("active");
344   }
345
346   var page = {};
347
348   page.pushstate = page.popstate = function (path) {
349     OSM.loadSidebarContent(path, function () {
350       page.load(path, true);
351     });
352   };
353
354   page.load = function (path, noCentre) {
355     var params = Qs.parse(path.substring(path.indexOf("?") + 1)),
356         latlng = L.latLng(params.lat, params.lon);
357
358     if (!window.location.hash && !noCentre && !map.getBounds().contains(latlng)) {
359       OSM.router.withoutMoveListener(function () {
360         map.setView(latlng, 15);
361       });
362     }
363
364     queryOverpass(params.lat, params.lon);
365   };
366
367   page.unload = function (sameController) {
368     if (!sameController) {
369       disableQueryMode();
370       $("#sidebar_content .query-results li.query-result.selected").each(hideResultGeometry);
371     }
372   };
373
374   return page;
375 };