]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/query.js
Merge pull request #25 from zerebubuth/routing-ui-tweaks
[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 =
86       I18n.t("geocoder.search_osm_nominatim.admin_levels.level" + tags.admin_level, {
87         defaultValue: I18n.t("geocoder.search_osm_nominatim.prefix.boundary.administrative")
88       })
89     } else {
90       var prefixes = I18n.t("geocoder.search_osm_nominatim.prefix");
91
92       for (var key in tags) {
93         var value = tags[key];
94
95         if (prefixes[key]) {
96           if (prefixes[key][value]) {
97             return prefixes[key][value];
98           } else {
99             var first = value.substr(0, 1).toUpperCase(),
100               rest = value.substr(1).replace(/_/g, " ");
101
102             return first + rest;
103           }
104         }
105       }
106     }
107
108     if (!prefix) {
109       prefix = I18n.t("javascripts.query." + feature.type);
110     }
111
112     return prefix;
113   }
114
115   function featureName(feature) {
116     var tags = feature.tags,
117       locales = I18n.locales.get();
118
119     for (var i = 0; i < locales.length; i++) {
120       if (tags["name:" + locales[i]]) {
121         return tags["name:" + locales[i]];
122       }
123     }
124
125     if (tags["name"]) {
126       return tags["name"];
127     } else if (tags["ref"]) {
128       return tags["ref"];
129     } else if (tags["addr:housename"]) {
130       return tags["addr:housename"];
131     } else if (tags["addr:housenumber"] && tags["addr:street"]) {
132       return tags["addr:housenumber"] + " " + tags["addr:street"];
133     } else {
134       return "#" + feature.id;
135     }
136   }
137
138   function featureGeometry(feature) {
139     var geometry;
140
141     if (feature.type === "node" && feature.lat && feature.lon) {
142       geometry = L.circleMarker([feature.lat, feature.lon], featureStyle);
143     } else if (feature.type === "way" && feature.geometry) {
144       geometry = L.polyline(feature.geometry.filter(function (point) {
145         return point !== null;
146       }).map(function (point) {
147         return [point.lat, point.lon];
148       }), featureStyle);
149     } else if (feature.type === "relation" && feature.members) {
150       geometry = L.featureGroup(feature.members.map(featureGeometry).filter(function (geometry) {
151         return geometry !== undefined;
152       }));
153     }
154
155     return geometry;
156   }
157
158   function runQuery(latlng, radius, query, $section, compare) {
159     var $ul = $section.find("ul");
160
161     $ul.empty();
162     $section.show();
163
164     $section.find(".loader").oneTime(1000, "loading", function () {
165       $(this).show();
166     });
167
168     if ($section.data("ajax")) {
169       $section.data("ajax").abort();
170     }
171
172     $section.data("ajax", $.ajax({
173       url: url,
174       method: "POST",
175       data: {
176         data: "[timeout:5][out:json];" + query,
177       },
178       success: function(results) {
179         var elements;
180
181         $section.find(".loader").stopTime("loading").hide();
182
183         if (compare) {
184           elements = results.elements.sort(compare);
185         } else {
186           elements = results.elements;
187         }
188
189         for (var i = 0; i < elements.length; i++) {
190           var element = elements[i];
191
192           if (interestingFeature(element, latlng, radius)) {
193             var $li = $("<li>")
194               .addClass("query-result")
195               .data("geometry", featureGeometry(element))
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   function compareSize(feature1, feature2) {
225     var width1 = feature1.bounds.maxlon - feature1.bounds.minlon,
226       height1 = feature1.bounds.maxlat - feature1.bounds.minlat,
227       area1 = width1 * height1,
228       width2 = feature2.bounds.maxlat - feature2.bounds.minlat,
229       height2 = feature2.bounds.maxlat - feature2.bounds.minlat,
230       area2 = width2 * height2;
231
232     return area1 - area2;
233   }
234
235   /*
236    * To find nearby objects we ask overpass for the union of the
237    * following sets:
238    *
239    *   node(around:<radius>,<lat>,lng>)
240    *   way(around:<radius>,<lat>,lng>)
241    *   relation(around:<radius>,<lat>,lng>)
242    *
243    * to find enclosing objects we first find all the enclosing areas:
244    *
245    *   is_in(<lat>,<lng>)->.a
246    *
247    * and then return the union of the following sets:
248    *
249    *   relation(pivot.a)
250    *   way(pivot.a)
251    *
252    * In both cases we then ask to retrieve tags and the geometry
253    * for each object.
254    */
255   function queryOverpass(lat, lng) {
256     var latlng = L.latLng(lat, lng),
257       bounds = map.getBounds(),
258       bbox = bounds.getSouth() + "," + bounds.getWest() + "," + bounds.getNorth() + "," + bounds.getEast(),
259       radius = 10 * Math.pow(1.5, 19 - map.getZoom()),
260       around = "around:" + radius + "," + lat + "," + lng,
261       nodes = "node(" + around + ")",
262       ways = "way(" + around + ")",
263       relations = "relation(" + around + ")",
264       nearby = "(" + nodes + ";" + ways + ");out tags geom(" + bbox + ");" + relations + ";out geom(" + bbox + ");",
265       isin = "is_in(" + lat + "," + lng + ")->.a;way(pivot.a);out tags geom(" + bbox + ");relation(pivot.a);out tags bb;";
266
267     $("#sidebar_content .query-intro")
268       .hide();
269
270     if (marker) map.removeLayer(marker);
271     marker = L.circle(latlng, radius, featureStyle).addTo(map);
272
273     $(document).everyTime(75, "fadeQueryMarker", function (i) {
274       if (i == 10) {
275         map.removeLayer(marker);
276       } else {
277         marker.setStyle({
278           opacity: 1 - i * 0.1,
279           fillOpacity: 0.5 - i * 0.05
280         });
281       }
282     }, 10);
283
284     runQuery(latlng, radius, nearby, $("#query-nearby"));
285     runQuery(latlng, radius, isin, $("#query-isin"), compareSize);
286   }
287
288   function clickHandler(e) {
289     var precision = OSM.zoomPrecision(map.getZoom()),
290       lat = e.latlng.lat.toFixed(precision),
291       lng = e.latlng.lng.toFixed(precision);
292
293     OSM.router.route("/query?lat=" + lat + "&lon=" + lng);
294   }
295
296   function enableQueryMode() {
297     queryButton.addClass("active");
298     map.on("click", clickHandler);
299     $(map.getContainer()).addClass("query-active");
300   }
301
302   function disableQueryMode() {
303     if (marker) map.removeLayer(marker);
304     $(map.getContainer()).removeClass("query-active").removeClass("query-disabled");
305     map.off("click", clickHandler);
306     queryButton.removeClass("active");
307   }
308
309   var page = {};
310
311   page.pushstate = page.popstate = function(path) {
312     OSM.loadSidebarContent(path, function () {
313       page.load(path, true);
314     });
315   };
316
317   page.load = function(path, noCentre) {
318     var params = querystring.parse(path.substring(path.indexOf('?') + 1)),
319       latlng = L.latLng(params.lat, params.lon);
320
321     if (!window.location.hash && !noCentre && !map.getBounds().contains(latlng)) {
322       OSM.router.withoutMoveListener(function () {
323         map.setView(latlng, 15);
324       });
325     }
326
327     queryOverpass(params.lat, params.lon);
328   };
329
330   page.unload = function(sameController) {
331     if (!sameController) {
332       disableQueryMode();
333     }
334   };
335
336   return page;
337 };