]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/query.js
12261abb823b4c99ea3015be63b696be62a5e07d
[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       for (var key in feature.tags) {
75         if (uninterestingTags.indexOf(key) < 0) {
76           return true;
77         }
78       }
79     }
80
81     return false;
82   }
83
84   function featurePrefix(feature) {
85     var tags = feature.tags;
86     var prefix = "";
87
88     if (tags.boundary === "administrative") {
89       prefix = I18n.t("geocoder.search_osm_nominatim.admin_levels.level" + tags.admin_level)
90     } else {
91       var prefixes = I18n.t("geocoder.search_osm_nominatim.prefix");
92
93       for (var key in tags) {
94         var value = tags[key];
95
96         if (prefixes[key]) {
97           if (prefixes[key][value]) {
98             return prefixes[key][value];
99           } else {
100             var first = value.substr(0, 1).toUpperCase(),
101               rest = value.substr(1).replace(/_/g, " ");
102
103             return first + rest;
104           }
105         }
106       }
107     }
108
109     if (!prefix) {
110       prefix = I18n.t("javascripts.query." + feature.type);
111     }
112
113     return prefix;
114   }
115
116   function featureName(feature) {
117     var tags = feature.tags;
118
119     if (tags["name"]) {
120       return tags["name"];
121     } else if (tags["ref"]) {
122       return tags["ref"];
123     } else if (tags["addr:housename"]) {
124       return tags["addr:housename"];
125     } else if (tags["addr:housenumber"] && tags["addr:street"]) {
126       return tags["addr:housenumber"] + " " + tags["addr:street"];
127     } else {
128       return "#" + feature.id;
129     }
130   }
131
132   function featureGeometry(feature) {
133     var 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) {
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 geometry !== undefined;
146       }));
147     }
148
149     return geometry;
150   }
151
152   function runQuery(latlng, radius, query, $section) {
153     var $ul = $section.find("ul");
154
155     $ul.empty();
156     $section.show();
157
158     $section.find(".loader").oneTime(1000, "loading", function () {
159       $(this).show();
160     });
161
162     if ($section.data("ajax")) {
163       $section.data("ajax").abort();
164     }
165
166     $section.data("ajax", $.ajax({
167       url: url,
168       method: "POST",
169       data: {
170         data: "[timeout:5][out:json];" + query,
171       },
172       success: function(results) {
173         $section.find(".loader").stopTime("loading").hide();
174
175         for (var i = 0; i < results.elements.length; i++) {
176           var element = results.elements[i];
177
178           if (interestingFeature(element, latlng, radius)) {
179             var $li = $("<li>")
180               .addClass("query-result")
181               .data("geometry", featureGeometry(element))
182               .appendTo($ul);
183             var $p = $("<p>")
184               .text(featurePrefix(element) + " ")
185               .appendTo($li);
186
187             $("<a>")
188               .attr("href", "/" + element.type + "/" + element.id)
189               .text(featureName(element))
190               .appendTo($p);
191           }
192         }
193
194         if ($ul.find("li").length == 0) {
195           $("<li>")
196             .text(I18n.t("javascripts.query.nothing_found"))
197             .appendTo($ul);
198         }
199       },
200       error: function(xhr, status, error) {
201         $section.find(".loader").stopTime("loading").hide();
202
203         $("<li>")
204           .text(I18n.t("javascripts.query." + status, { server: url, error: error }))
205           .appendTo($ul);
206       }
207     }));
208   }
209
210   /*
211    * To find nearby objects we ask overpass for the union of the
212    * following sets:
213    *
214    *   node(around:<radius>,<lat>,lng>)
215    *   way(around:<radius>,<lat>,lng>)
216    *   relation(around:<radius>,<lat>,lng>)
217    *
218    * to find enclosing objects we first find all the enclosing areas:
219    *
220    *   is_in(<lat>,<lng>)->.a
221    *
222    * and then return the union of the following sets:
223    *
224    *   relation(pivot.a)
225    *   way(pivot.a)
226    *
227    * In both cases we then ask to retrieve tags and the geometry
228    * for each object.
229    */
230   function queryOverpass(lat, lng) {
231     var latlng = L.latLng(lat, lng),
232       bounds = map.getBounds(),
233       bbox = bounds.getSouth() + "," + bounds.getWest() + "," + bounds.getNorth() + "," + bounds.getEast(),
234       radius = 10 * Math.pow(1.5, 19 - map.getZoom()),
235       around = "around:" + radius + "," + lat + "," + lng,
236       nodes = "node(" + around + ")",
237       ways = "way(" + around + ")",
238       relations = "relation(" + around + ")",
239       nearby = "(" + nodes + ";" + ways + ");out tags geom(" + bbox + ");" + relations + ";out geom(" + bbox + ");",
240       isin = "is_in(" + lat + "," + lng + ")->.a;(relation(pivot.a);way(pivot.a));out geom(" + bbox + ");";
241
242     $("#sidebar_content .query-intro")
243       .hide();
244
245     if (marker) map.removeLayer(marker);
246     marker = L.circle(latlng, radius, featureStyle).addTo(map);
247
248     $(document).everyTime(75, "fadeQueryMarker", function (i) {
249       if (i == 10) {
250         map.removeLayer(marker);
251       } else {
252         marker.setStyle({
253           opacity: 1 - i * 0.1,
254           fillOpacity: 0.5 - i * 0.05
255         });
256       }
257     }, 10);
258
259     runQuery(latlng, radius, nearby, $("#query-nearby"));
260     runQuery(latlng, radius, isin, $("#query-isin"));
261   }
262
263   function clickHandler(e) {
264     var precision = OSM.zoomPrecision(map.getZoom()),
265       lat = e.latlng.lat.toFixed(precision),
266       lng = e.latlng.lng.toFixed(precision);
267
268     OSM.router.route("/query?lat=" + lat + "&lon=" + lng);
269   }
270
271   function enableQueryMode() {
272     queryButton.addClass("active");
273     map.on("click", clickHandler);
274     $(map.getContainer()).addClass("query-active");
275   }
276
277   function disableQueryMode() {
278     if (marker) map.removeLayer(marker);
279     $(map.getContainer()).removeClass("query-active").removeClass("query-disabled");
280     map.off("click", clickHandler);
281     queryButton.removeClass("active");
282   }
283
284   var page = {};
285
286   page.pushstate = page.popstate = function(path) {
287     OSM.loadSidebarContent(path, function () {
288       page.load(path, true);
289     });
290   };
291
292   page.load = function(path, noCentre) {
293     var params = querystring.parse(path.substring(path.indexOf('?') + 1)),
294       latlng = L.latLng(params.lat, params.lon);
295
296     if (!window.location.hash && !noCentre && !map.getBounds().contains(latlng)) {
297       OSM.router.withoutMoveListener(function () {
298         map.setView(latlng, 15);
299       });
300     }
301
302     queryOverpass(params.lat, params.lon);
303     enableQueryMode();
304   };
305
306   page.unload = function() {
307     disableQueryMode();
308   };
309
310   return page;
311 };