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