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