]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/query.js
Merge branch 'master' into overpass
[rails.git] / app / assets / javascripts / index / query.js
1 //= require jquery.simulate
2
3 OSM.Query = function(map) {
4   var protocol = document.location.protocol === "https:" ? "https:" : "http:",
5     url = protocol + OSM.OVERPASS_URL,
6     queryButton = $(".control-query .control-button"),
7     uninterestingTags = ['source', 'source_ref', 'source:ref', 'history', 'attribution', 'created_by', 'tiger:county', 'tiger:tlid', 'tiger:upload_uuid'],
8     marker;
9
10   var featureStyle = {
11     color: "#FF6200",
12     weight: 4,
13     opacity: 1,
14     fillOpacity: 0.5,
15     clickable: false
16   };
17
18   queryButton.on("click", function (e) {
19     e.preventDefault();
20     e.stopPropagation();
21
22     if (queryButton.hasClass("disabled")) return;
23
24     if (queryButton.hasClass("active")) {
25       if ($("#content").hasClass("overlay-sidebar")) {
26         disableQueryMode();
27       }
28     } else {
29       enableQueryMode();
30     }
31   }).on("disabled", function (e) {
32     if (queryButton.hasClass("active")) {
33       map.off("click", clickHandler);
34       $(map.getContainer()).removeClass("query-active").addClass("query-disabled");
35       $(this).tooltip("show");
36     }
37   }).on("enabled", function (e) {
38     if (queryButton.hasClass("active")) {
39       map.on("click", clickHandler);
40       $(map.getContainer()).removeClass("query-disabled").addClass("query-active");
41       $(this).tooltip("hide");
42     }
43   });
44
45   $("#sidebar_content")
46     .on("mouseover", ".query-results li.query-result", function () {
47       var geometry = $(this).data("geometry")
48       if (geometry) map.addLayer(geometry);
49       $(this).addClass("selected");
50     })
51     .on("mouseout", ".query-results li.query-result", function () {
52       var geometry = $(this).data("geometry")
53       if (geometry) map.removeLayer(geometry);
54       $(this).removeClass("selected");
55     })
56     .on("mousedown", ".query-results li.query-result", function (e) {
57       var moved = false;
58       $(this).one("click", function (e) {
59         if (!moved) {
60           var geometry = $(this).data("geometry")
61           if (geometry) map.removeLayer(geometry);
62
63           if (!$(e.target).is('a')) {
64             $(this).find("a").simulate("click", e);
65           }
66         }
67       }).one("mousemove", function () {
68         moved = true;
69       });
70     });
71
72   function interestingFeature(feature, origin, radius) {
73     if (feature.tags) {
74       if (feature.type === "node" &&
75           OSM.distance(origin, L.latLng(feature.lat, feature.lon)) > radius) {
76         return false;
77       }
78
79       for (var key in feature.tags) {
80         if (uninterestingTags.indexOf(key) < 0) {
81           return true;
82         }
83       }
84     }
85
86     return false;
87   }
88
89   function featurePrefix(feature) {
90     var tags = feature.tags;
91     var prefix = "";
92
93     if (tags.boundary === "administrative") {
94       prefix = I18n.t("geocoder.search_osm_nominatim.admin_levels.level" + tags.admin_level)
95     } else {
96       var prefixes = I18n.t("geocoder.search_osm_nominatim.prefix");
97
98       for (var key in tags) {
99         var value = tags[key];
100
101         if (prefixes[key]) {
102           if (prefixes[key][value]) {
103             return prefixes[key][value];
104           } else {
105             var first = value.substr(0, 1).toUpperCase(),
106               rest = value.substr(1).replace(/_/g, " ");
107
108             return first + rest;
109           }
110         }
111       }
112     }
113
114     if (!prefix) {
115       prefix = I18n.t("javascripts.query." + feature.type);
116     }
117
118     return prefix;
119   }
120
121   function featureName(feature) {
122     var tags = feature.tags;
123
124     if (tags["name"]) {
125       return tags["name"];
126     } else if (tags["ref"]) {
127       return tags["ref"];
128     } else if (tags["addr:housename"]) {
129       return tags["addr:housename"];
130     } else if (tags["addr:housenumber"] && tags["addr:street"]) {
131       return tags["addr:housenumber"] + " " + tags["addr:street"];
132     } else {
133       return "#" + feature.id;
134     }
135   }
136
137   function featureGeometry(feature, features) {
138     var geometry;
139
140     if (feature.type === "node") {
141       geometry = L.circleMarker([feature.lat, feature.lon], featureStyle);
142     } else if (feature.type === "way") {
143       geometry = L.polyline(feature.nodes.map(function (node) {
144         return features["node" + node].getLatLng();
145       }), featureStyle);
146     } else if (feature.type === "relation") {
147       geometry = L.featureGroup();
148
149       feature.members.forEach(function (member) {
150         if (features[member.type + member.ref]) {
151           geometry.addLayer(features[member.type + member.ref]);
152         }
153       });
154     }
155
156     if (geometry) {
157       features[feature.type + feature.id] = geometry;
158     }
159
160     return geometry;
161   }
162
163   function runQuery(latlng, radius, query, $section) {
164     var $ul = $section.find("ul");
165
166     $ul.empty();
167     $section.show();
168
169     $section.find(".loader").oneTime(1000, "loading", function () {
170       $(this).show();
171     });
172
173     if ($section.data("ajax")) {
174       $section.data("ajax").abort();
175     }
176
177     $section.data("ajax", $.ajax({
178       url: url,
179       method: "POST",
180       data: {
181         data: "[timeout:5][out:json];" + query,
182       },
183       success: function(results) {
184         var features = {};
185
186         $section.find(".loader").stopTime("loading").hide();
187
188         for (var i = 0; i < results.elements.length; i++) {
189           var element = results.elements[i],
190             geometry = featureGeometry(element, features);
191
192           if (interestingFeature(element, latlng, radius)) {
193             var $li = $("<li>")
194               .addClass("query-result")
195               .data("geometry", geometry)
196               .appendTo($ul);
197             var $p = $("<p>")
198               .text(featurePrefix(element) + " ")
199               .appendTo($li);
200
201             $("<a>")
202               .attr("href", "/" + element.type + "/" + element.id)
203               .text(featureName(element))
204               .appendTo($p);
205           }
206         }
207
208         if ($ul.find("li").length == 0) {
209           $("<li>")
210             .text(I18n.t("javascripts.query.nothing_found"))
211             .appendTo($ul);
212         }
213       },
214       error: function(xhr, status, error) {
215         $section.find(".loader").stopTime("loading").hide();
216
217         $("<li>")
218           .text(I18n.t("javascripts.query." + status, { server: url, error: error }))
219           .appendTo($ul);
220       }
221     }));
222   }
223
224   /*
225    * To find nearby objects we ask overpass for the union of the
226    * following sets:
227    *
228    *   node(around:<radius>,<lat>,lng>)
229    *   way(around:<radius>,<lat>,lng>)
230    *   node(w)
231    *   relation(around:<radius>,<lat>,lng>)
232    *
233    * to find enclosing objects we first find all the enclosing areas:
234    *
235    *   is_in(<lat>,<lng>)->.a
236    *
237    * and then return the union of the following sets:
238    *
239    *   relation(pivot.a)
240    *   way(pivot.a)
241    *   node(w)
242    *
243    * In order to avoid overly large responses we don't currently
244    * attempt to complete any relations and instead just show those
245    * ways and nodes which are returned for other reasons.
246    */
247   function queryOverpass(lat, lng) {
248     var latlng = L.latLng(lat, lng),
249       radius = 10 * Math.pow(1.5, 19 - map.getZoom()),
250       around = "around:" + radius + "," + lat + "," + lng,
251       nodes = "node(" + around + ")",
252       ways = "way(" + around + ");node(w)",
253       relations = "relation(" + around + ")",
254       nearby = "(" + nodes + ";" + ways + ";" + relations + ");out;",
255       isin = "is_in(" + lat + "," + lng + ")->.a;(relation(pivot.a);way(pivot.a);node(w));out;";
256
257     $("#sidebar_content .query-intro")
258       .hide();
259
260     if (marker) map.removeLayer(marker);
261     marker = L.circle(latlng, radius, featureStyle).addTo(map);
262
263     $(document).everyTime(75, "fadeQueryMarker", function (i) {
264       if (i == 10) {
265         map.removeLayer(marker);
266       } else {
267         marker.setStyle({
268           opacity: 1 - i * 0.1,
269           fillOpacity: 0.5 - i * 0.05
270         });
271       }
272     }, 10);
273
274     runQuery(latlng, radius, nearby, $("#query-nearby"));
275     runQuery(latlng, radius, isin, $("#query-isin"));
276   }
277
278   function clickHandler(e) {
279     var precision = OSM.zoomPrecision(map.getZoom()),
280       lat = e.latlng.lat.toFixed(precision),
281       lng = e.latlng.lng.toFixed(precision);
282
283     OSM.router.route("/query?lat=" + lat + "&lon=" + lng);
284   }
285
286   function enableQueryMode() {
287     queryButton.addClass("active");
288     map.on("click", clickHandler);
289     $(map.getContainer()).addClass("query-active");
290   }
291
292   function disableQueryMode() {
293     if (marker) map.removeLayer(marker);
294     $(map.getContainer()).removeClass("query-active").removeClass("query-disabled");
295     map.off("click", clickHandler);
296     queryButton.removeClass("active");
297   }
298
299   var page = {};
300
301   page.pushstate = page.popstate = function(path) {
302     OSM.loadSidebarContent(path, function () {
303       page.load(path, true);
304     });
305   };
306
307   page.load = function(path, noCentre) {
308     var params = querystring.parse(path.substring(path.indexOf('?') + 1)),
309       latlng = L.latLng(params.lat, params.lon);
310
311     if (!window.location.hash &&
312         (!noCentre || !map.getBounds().contains(latlng))) {
313       OSM.router.withoutMoveListener(function () {
314         map.setView(latlng, 15);
315       });
316     }
317
318     queryOverpass(params.lat, params.lon);
319     enableQueryMode();
320   };
321
322   page.unload = function() {
323     disableQueryMode();
324   };
325
326   return page;
327 };