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