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