]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/query.js
Merge remote-tracking branch 'upstream/pull/2381'
[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             .addClass("query-result list-group-item")
232             .text(I18n.t("javascripts.query.error", { server: url, error: results.remark }))
233             .appendTo($ul);
234         }
235
236         if ($ul.find("li").length === 0) {
237           $("<li>")
238             .addClass("query-result list-group-item")
239             .text(I18n.t("javascripts.query.nothing_found"))
240             .appendTo($ul);
241         }
242       },
243       error: function (xhr, status, error) {
244         $section.find(".loader").stopTime("loading").hide();
245
246         $("<li>")
247           .addClass("query-result list-group-item")
248           .text(I18n.t("javascripts.query." + status, { server: url, error: error }))
249           .appendTo($ul);
250       }
251     }));
252   }
253
254   function compareSize(feature1, feature2) {
255     var width1 = feature1.bounds.maxlon - feature1.bounds.minlon,
256         height1 = feature1.bounds.maxlat - feature1.bounds.minlat,
257         area1 = width1 * height1,
258         width2 = feature2.bounds.maxlat - feature2.bounds.minlat,
259         height2 = feature2.bounds.maxlat - feature2.bounds.minlat,
260         area2 = width2 * height2;
261
262     return area1 - area2;
263   }
264
265   /*
266    * To find nearby objects we ask overpass for the union of the
267    * following sets:
268    *
269    *   node(around:<radius>,<lat>,lng>)
270    *   way(around:<radius>,<lat>,lng>)
271    *   relation(around:<radius>,<lat>,lng>)
272    *
273    * to find enclosing objects we first find all the enclosing areas:
274    *
275    *   is_in(<lat>,<lng>)->.a
276    *
277    * and then return the union of the following sets:
278    *
279    *   relation(pivot.a)
280    *   way(pivot.a)
281    *
282    * In both cases we then ask to retrieve tags and the geometry
283    * for each object.
284    */
285   function queryOverpass(lat, lng) {
286     var latlng = L.latLng(lat, lng).wrap(),
287         bounds = map.getBounds().wrap(),
288         precision = OSM.zoomPrecision(map.getZoom()),
289         bbox = bounds.getSouth().toFixed(precision) + "," +
290                bounds.getWest().toFixed(precision) + "," +
291                bounds.getNorth().toFixed(precision) + "," +
292                bounds.getEast().toFixed(precision),
293         radius = 10 * Math.pow(1.5, 19 - map.getZoom()),
294         around = "around:" + radius + "," + lat + "," + lng,
295         nodes = "node(" + around + ")",
296         ways = "way(" + around + ")",
297         relations = "relation(" + around + ")",
298         nearby = "(" + nodes + ";" + ways + ";);out tags geom(" + bbox + ");" + relations + ";out geom(" + bbox + ");",
299         isin = "is_in(" + lat + "," + lng + ")->.a;way(pivot.a);out tags bb;out ids geom(" + bbox + ");relation(pivot.a);out tags bb;";
300
301     $("#sidebar_content .query-intro")
302       .hide();
303
304     if (marker) map.removeLayer(marker);
305     marker = L.circle(latlng, radius, featureStyle).addTo(map);
306
307     $(document).everyTime(75, "fadeQueryMarker", function (i) {
308       if (i === 10) {
309         map.removeLayer(marker);
310       } else {
311         marker.setStyle({
312           opacity: 1 - (i * 0.1),
313           fillOpacity: 0.5 - (i * 0.05)
314         });
315       }
316     }, 10);
317
318     runQuery(latlng, radius, nearby, $("#query-nearby"), false);
319     runQuery(latlng, radius, isin, $("#query-isin"), true, compareSize);
320   }
321
322   function clickHandler(e) {
323     var precision = OSM.zoomPrecision(map.getZoom()),
324         latlng = e.latlng.wrap(),
325         lat = latlng.lat.toFixed(precision),
326         lng = latlng.lng.toFixed(precision);
327
328     OSM.router.route("/query?lat=" + lat + "&lon=" + lng);
329   }
330
331   function enableQueryMode() {
332     queryButton.addClass("active");
333     map.on("click", clickHandler);
334     $(map.getContainer()).addClass("query-active");
335   }
336
337   function disableQueryMode() {
338     if (marker) map.removeLayer(marker);
339     $(map.getContainer()).removeClass("query-active").removeClass("query-disabled");
340     map.off("click", clickHandler);
341     queryButton.removeClass("active");
342   }
343
344   var page = {};
345
346   page.pushstate = page.popstate = function (path) {
347     OSM.loadSidebarContent(path, function () {
348       page.load(path, true);
349     });
350   };
351
352   page.load = function (path, noCentre) {
353     var params = querystring.parse(path.substring(path.indexOf("?") + 1)),
354         latlng = L.latLng(params.lat, params.lon);
355
356     if (!window.location.hash && !noCentre && !map.getBounds().contains(latlng)) {
357       OSM.router.withoutMoveListener(function () {
358         map.setView(latlng, 15);
359       });
360     }
361
362     queryOverpass(params.lat, params.lon);
363   };
364
365   page.unload = function (sameController) {
366     if (!sameController) {
367       disableQueryMode();
368     }
369   };
370
371   return page;
372 };