]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/query.js
Use double quotes consistently in javascript code
[rails.git] / app / assets / javascripts / index / query.js
1 //= require jquery.simulate
2
3 OSM.Query = function(map) {
4   var url = OSM.OVERPASS_URL,
5     queryButton = $(".control-query .control-button"),
6     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"],
7     marker;
8
9   var featureStyle = {
10     color: "#FF6200",
11     weight: 4,
12     opacity: 1,
13     fillOpacity: 0.5,
14     interactive: false
15   };
16
17   queryButton.on("click", function (e) {
18     e.preventDefault();
19     e.stopPropagation();
20
21     if (queryButton.hasClass("active")) {
22       disableQueryMode();
23     } else if (!queryButton.hasClass("disabled")) {
24       enableQueryMode();
25     }
26   }).on("disabled", function () {
27     if (queryButton.hasClass("active")) {
28       map.off("click", clickHandler);
29       $(map.getContainer()).removeClass("query-active").addClass("query-disabled");
30       $(this).tooltip("show");
31     }
32   }).on("enabled", function () {
33     if (queryButton.hasClass("active")) {
34       map.on("click", clickHandler);
35       $(map.getContainer()).removeClass("query-disabled").addClass("query-active");
36       $(this).tooltip("hide");
37     }
38   });
39
40   $("#sidebar_content")
41     .on("mouseover", ".query-results li.query-result", function () {
42       var geometry = $(this).data("geometry");
43       if (geometry) map.addLayer(geometry);
44       $(this).addClass("selected");
45     })
46     .on("mouseout", ".query-results li.query-result", function () {
47       var geometry = $(this).data("geometry");
48       if (geometry) map.removeLayer(geometry);
49       $(this).removeClass("selected");
50     })
51     .on("mousedown", ".query-results li.query-result", function () {
52       var moved = false;
53       $(this).one("click", function (e) {
54         if (!moved) {
55           var geometry = $(this).data("geometry");
56           if (geometry) map.removeLayer(geometry);
57
58           if (!$(e.target).is("a")) {
59             $(this).find("a").simulate("click", e);
60           }
61         }
62       }).one("mousemove", function () {
63         moved = true;
64       });
65     });
66
67   function interestingFeature(feature) {
68     if (feature.tags) {
69       for (var key in feature.tags) {
70         if (uninterestingTags.indexOf(key) < 0) {
71           return true;
72         }
73       }
74     }
75
76     return false;
77   }
78
79   function featurePrefix(feature) {
80     var tags = feature.tags;
81     var prefix = "";
82
83     if (tags.boundary === "administrative" && tags.admin_level) {
84       prefix = I18n.t("geocoder.search_osm_nominatim.admin_levels.level" + tags.admin_level, {
85         defaultValue: I18n.t("geocoder.search_osm_nominatim.prefix.boundary.administrative")
86       });
87     } else {
88       var prefixes = I18n.t("geocoder.search_osm_nominatim.prefix");
89       var key, value;
90
91       for (key in tags) {
92         value = tags[key];
93
94         if (prefixes[key]) {
95           if (prefixes[key][value]) {
96             return prefixes[key][value];
97           }
98         }
99       }
100
101       for (key in tags) {
102         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 && feature.geometry.length > 0) {
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, merge, 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:10][out:json];" + query,
182       },
183       success: function(results) {
184         var elements;
185
186         $section.find(".loader").stopTime("loading").hide();
187
188         if (merge) {
189           elements = results.elements.reduce(function (hash, element) {
190             var key = element.type + element.id;
191             if ("geometry" in element) {
192               delete element.bounds;
193             }
194             hash[key] = $.extend({}, hash[key], element);
195             return hash;
196           }, {});
197
198           elements = Object.keys(elements).map(function (key) {
199             return elements[key];
200           });
201         } else {
202           elements = results.elements;
203         }
204
205         if (compare) {
206           elements = elements.sort(compare);
207         }
208
209         for (var i = 0; i < elements.length; i++) {
210           var element = elements[i];
211
212           if (interestingFeature(element)) {
213             var $li = $("<li>")
214               .addClass("query-result")
215               .data("geometry", featureGeometry(element))
216               .appendTo($ul);
217             var $p = $("<p>")
218               .text(featurePrefix(element) + " ")
219               .appendTo($li);
220
221             $("<a>")
222               .attr("href", "/" + element.type + "/" + element.id)
223               .text(featureName(element))
224               .appendTo($p);
225           }
226         }
227
228         if (results.remark) {
229           $("<li>")
230             .text(I18n.t("javascripts.query.error", { server: url, error: results.remark }))
231             .appendTo($ul);
232         }
233
234         if ($ul.find("li").length === 0) {
235           $("<li>")
236             .text(I18n.t("javascripts.query.nothing_found"))
237             .appendTo($ul);
238         }
239       },
240       error: function(xhr, status, error) {
241         $section.find(".loader").stopTime("loading").hide();
242
243         $("<li>")
244           .text(I18n.t("javascripts.query." + status, { server: url, error: error }))
245           .appendTo($ul);
246       }
247     }));
248   }
249
250   function compareSize(feature1, feature2) {
251     var width1 = feature1.bounds.maxlon - feature1.bounds.minlon,
252       height1 = feature1.bounds.maxlat - feature1.bounds.minlat,
253       area1 = width1 * height1,
254       width2 = feature2.bounds.maxlat - feature2.bounds.minlat,
255       height2 = feature2.bounds.maxlat - feature2.bounds.minlat,
256       area2 = width2 * height2;
257
258     return area1 - area2;
259   }
260
261   /*
262    * To find nearby objects we ask overpass for the union of the
263    * following sets:
264    *
265    *   node(around:<radius>,<lat>,lng>)
266    *   way(around:<radius>,<lat>,lng>)
267    *   relation(around:<radius>,<lat>,lng>)
268    *
269    * to find enclosing objects we first find all the enclosing areas:
270    *
271    *   is_in(<lat>,<lng>)->.a
272    *
273    * and then return the union of the following sets:
274    *
275    *   relation(pivot.a)
276    *   way(pivot.a)
277    *
278    * In both cases we then ask to retrieve tags and the geometry
279    * for each object.
280    */
281   function queryOverpass(lat, lng) {
282     var latlng = L.latLng(lat, lng).wrap(),
283       bounds = map.getBounds().wrap(),
284       bbox = bounds.getSouth() + "," + bounds.getWest() + "," + bounds.getNorth() + "," + bounds.getEast(),
285       radius = 10 * Math.pow(1.5, 19 - map.getZoom()),
286       around = "around:" + radius + "," + lat + "," + lng,
287       nodes = "node(" + around + ")",
288       ways = "way(" + around + ")",
289       relations = "relation(" + around + ")",
290       nearby = "(" + nodes + ";" + ways + ";);out tags geom(" + bbox + ");" + relations + ";out geom(" + bbox + ");",
291       isin = "is_in(" + lat + "," + lng + ")->.a;way(pivot.a);out tags bb;out ids geom(" + bbox + ");relation(pivot.a);out tags bb;";
292
293     $("#sidebar_content .query-intro")
294       .hide();
295
296     if (marker) map.removeLayer(marker);
297     marker = L.circle(latlng, radius, featureStyle).addTo(map);
298
299     $(document).everyTime(75, "fadeQueryMarker", function (i) {
300       if (i === 10) {
301         map.removeLayer(marker);
302       } else {
303         marker.setStyle({
304           opacity: 1 - i * 0.1,
305           fillOpacity: 0.5 - i * 0.05
306         });
307       }
308     }, 10);
309
310     runQuery(latlng, radius, nearby, $("#query-nearby"), false);
311     runQuery(latlng, radius, isin, $("#query-isin"), true, compareSize);
312   }
313
314   function clickHandler(e) {
315     var precision = OSM.zoomPrecision(map.getZoom()),
316       latlng = e.latlng.wrap(),
317       lat = latlng.lat.toFixed(precision),
318       lng = latlng.lng.toFixed(precision);
319
320     OSM.router.route("/query?lat=" + lat + "&lon=" + lng);
321   }
322
323   function enableQueryMode() {
324     queryButton.addClass("active");
325     map.on("click", clickHandler);
326     $(map.getContainer()).addClass("query-active");
327   }
328
329   function disableQueryMode() {
330     if (marker) map.removeLayer(marker);
331     $(map.getContainer()).removeClass("query-active").removeClass("query-disabled");
332     map.off("click", clickHandler);
333     queryButton.removeClass("active");
334   }
335
336   var page = {};
337
338   page.pushstate = page.popstate = function(path) {
339     OSM.loadSidebarContent(path, function () {
340       page.load(path, true);
341     });
342   };
343
344   page.load = function(path, noCentre) {
345     var params = querystring.parse(path.substring(path.indexOf("?") + 1)),
346       latlng = L.latLng(params.lat, params.lon);
347
348     if (!window.location.hash && !noCentre && !map.getBounds().contains(latlng)) {
349       OSM.router.withoutMoveListener(function () {
350         map.setView(latlng, 15);
351       });
352     }
353
354     queryOverpass(params.lat, params.lon);
355   };
356
357   page.unload = function(sameController) {
358     if (!sameController) {
359       disableQueryMode();
360     }
361   };
362
363   return page;
364 };