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