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