]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/query.js
Sort enclosing features by size
[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, compare) {
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         var elements;
174
175         $section.find(".loader").stopTime("loading").hide();
176
177         if (compare) {
178           elements = results.elements.sort(compare);
179         } else {
180           elements = results.elements;
181         }
182
183         for (var i = 0; i < elements.length; i++) {
184           var element = elements[i];
185
186           if (interestingFeature(element, latlng, radius)) {
187             var $li = $("<li>")
188               .addClass("query-result")
189               .data("geometry", featureGeometry(element))
190               .appendTo($ul);
191             var $p = $("<p>")
192               .text(featurePrefix(element) + " ")
193               .appendTo($li);
194
195             $("<a>")
196               .attr("href", "/" + element.type + "/" + element.id)
197               .text(featureName(element))
198               .appendTo($p);
199           }
200         }
201
202         if ($ul.find("li").length == 0) {
203           $("<li>")
204             .text(I18n.t("javascripts.query.nothing_found"))
205             .appendTo($ul);
206         }
207       },
208       error: function(xhr, status, error) {
209         $section.find(".loader").stopTime("loading").hide();
210
211         $("<li>")
212           .text(I18n.t("javascripts.query." + status, { server: url, error: error }))
213           .appendTo($ul);
214       }
215     }));
216   }
217
218   function compareSize(feature1, feature2) {
219     var width1 = feature1.bounds.maxlon - feature1.bounds.minlon,
220       height1 = feature1.bounds.maxlat - feature1.bounds.minlat,
221       area1 = width1 * height1,
222       width2 = feature2.bounds.maxlat - feature2.bounds.minlat,
223       height2 = feature2.bounds.maxlat - feature2.bounds.minlat,
224       area2 = width2 * height2;
225
226     return area1 - area2;
227   }
228
229   /*
230    * To find nearby objects we ask overpass for the union of the
231    * following sets:
232    *
233    *   node(around:<radius>,<lat>,lng>)
234    *   way(around:<radius>,<lat>,lng>)
235    *   relation(around:<radius>,<lat>,lng>)
236    *
237    * to find enclosing objects we first find all the enclosing areas:
238    *
239    *   is_in(<lat>,<lng>)->.a
240    *
241    * and then return the union of the following sets:
242    *
243    *   relation(pivot.a)
244    *   way(pivot.a)
245    *
246    * In both cases we then ask to retrieve tags and the geometry
247    * for each object.
248    */
249   function queryOverpass(lat, lng) {
250     var latlng = L.latLng(lat, lng),
251       bounds = map.getBounds(),
252       bbox = bounds.getSouth() + "," + bounds.getWest() + "," + bounds.getNorth() + "," + bounds.getEast(),
253       radius = 10 * Math.pow(1.5, 19 - map.getZoom()),
254       around = "around:" + radius + "," + lat + "," + lng,
255       nodes = "node(" + around + ")",
256       ways = "way(" + around + ")",
257       relations = "relation(" + around + ")",
258       nearby = "(" + nodes + ";" + ways + ");out tags geom(" + bbox + ");" + relations + ";out geom(" + bbox + ");",
259       isin = "is_in(" + lat + "," + lng + ")->.a;way(pivot.a);out tags geom(" + bbox + ");relation(pivot.a);out tags bb;";
260
261     $("#sidebar_content .query-intro")
262       .hide();
263
264     if (marker) map.removeLayer(marker);
265     marker = L.circle(latlng, radius, featureStyle).addTo(map);
266
267     $(document).everyTime(75, "fadeQueryMarker", function (i) {
268       if (i == 10) {
269         map.removeLayer(marker);
270       } else {
271         marker.setStyle({
272           opacity: 1 - i * 0.1,
273           fillOpacity: 0.5 - i * 0.05
274         });
275       }
276     }, 10);
277
278     runQuery(latlng, radius, nearby, $("#query-nearby"));
279     runQuery(latlng, radius, isin, $("#query-isin"), compareSize);
280   }
281
282   function clickHandler(e) {
283     var precision = OSM.zoomPrecision(map.getZoom()),
284       lat = e.latlng.lat.toFixed(precision),
285       lng = e.latlng.lng.toFixed(precision);
286
287     OSM.router.route("/query?lat=" + lat + "&lon=" + lng);
288   }
289
290   function enableQueryMode() {
291     queryButton.addClass("active");
292     map.on("click", clickHandler);
293     $(map.getContainer()).addClass("query-active");
294   }
295
296   function disableQueryMode() {
297     if (marker) map.removeLayer(marker);
298     $(map.getContainer()).removeClass("query-active").removeClass("query-disabled");
299     map.off("click", clickHandler);
300     queryButton.removeClass("active");
301   }
302
303   var page = {};
304
305   page.pushstate = page.popstate = function(path) {
306     OSM.loadSidebarContent(path, function () {
307       page.load(path, true);
308     });
309   };
310
311   page.load = function(path, noCentre) {
312     var params = querystring.parse(path.substring(path.indexOf('?') + 1)),
313       latlng = L.latLng(params.lat, params.lon);
314
315     if (!window.location.hash && !noCentre && !map.getBounds().contains(latlng)) {
316       OSM.router.withoutMoveListener(function () {
317         map.setView(latlng, 15);
318       });
319     }
320
321     queryOverpass(params.lat, params.lon);
322     enableQueryMode();
323   };
324
325   page.unload = function() {
326     disableQueryMode();
327   };
328
329   return page;
330 };