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