]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/query.js
Add https support for overpass
[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'],
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
27       OSM.router.route("/");
28     } else {
29       enableQueryMode();
30     }
31   }).on("disabled", function (e) {
32     if (queryButton.hasClass("active")) {
33       map.off("click", clickHandler);
34       $(map.getContainer()).removeClass("query-active").addClass("query-disabled");
35       $(this).tooltip("show");
36     }
37   }).on("enabled", function (e) {
38     if (queryButton.hasClass("active")) {
39       map.on("click", clickHandler);
40       $(map.getContainer()).removeClass("query-disabled").addClass("query-active");
41       $(this).tooltip("hide");
42     }
43   });
44
45   $("#sidebar_content")
46     .on("mouseover", ".query-results li.query-result", function () {
47       var geometry = $(this).data("geometry")
48       if (geometry) map.addLayer(geometry);
49       $(this).addClass("selected");
50     })
51     .on("mouseout", ".query-results li.query-result", function () {
52       var geometry = $(this).data("geometry")
53       if (geometry) map.removeLayer(geometry);
54       $(this).removeClass("selected");
55     })
56     .on("click", ".query-results li.query-result", function (e) {
57       if (!$(e.target).is('a')) {
58         $(this).find("a").simulate("click", e);
59       }
60     });
61
62   function interestingFeature(feature, origin, radius) {
63     if (feature.tags) {
64       if (feature.type === "node" &&
65           OSM.distance(origin, L.latLng(feature.lat, feature.lon)) > radius) {
66         return false;
67       }
68
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") {
84       prefix = I18n.t("geocoder.search_osm_nominatim.admin_levels.level" + tags.admin_level)
85     } else {
86       var prefixes = I18n.t("geocoder.search_osm_nominatim.prefix");
87
88       for (var key in tags) {
89         var value = tags[key];
90
91         if (prefixes[key]) {
92           if (prefixes[key][value]) {
93             return prefixes[key][value];
94           } else {
95             var first = value.substr(0, 1).toUpperCase(),
96               rest = value.substr(1).replace(/_/g, " ");
97
98             return first + rest;
99           }
100         }
101       }
102     }
103
104     if (!prefix) {
105       prefix = I18n.t("javascripts.query." + feature.type);
106     }
107
108     return prefix;
109   }
110
111   function featureName(feature) {
112     var tags = feature.tags;
113
114     if (tags["name"]) {
115       return tags["name"];
116     } else if (tags["ref"]) {
117       return tags["ref"];
118     } else if (tags["addr:housename"]) {
119       return tags["addr:housename"];
120     } else if (tags["addr:housenumber"] && tags["addr:street"]) {
121       return tags["addr:housenumber"] + " " + tags["addr:street"];
122     } else {
123       return "#" + feature.id;
124     }
125   }
126
127   function featureGeometry(feature, features) {
128     var geometry;
129
130     if (feature.type === "node") {
131       geometry = L.circleMarker([feature.lat, feature.lon], featureStyle);
132     } else if (feature.type === "way") {
133       geometry = L.polyline(feature.nodes.map(function (node) {
134         return features["node" + node].getLatLng();
135       }), featureStyle);
136     } else if (feature.type === "relation") {
137       geometry = L.featureGroup();
138
139       feature.members.forEach(function (member) {
140         if (features[member.type + member.ref]) {
141           geometry.addLayer(features[member.type + member.ref]);
142         }
143       });
144     }
145
146     if (geometry) {
147       features[feature.type + feature.id] = geometry;
148     }
149
150     return geometry;
151   }
152
153   function runQuery(latlng, radius, query, $section) {
154     var $ul = $section.find("ul");
155
156     $ul.empty();
157     $section.show();
158
159     $section.find(".loader").oneTime(1000, "loading", function () {
160       $(this).show();
161     });
162
163     if ($section.data("ajax")) {
164       $section.data("ajax").abort();
165     }
166
167     $section.data("ajax", $.ajax({
168       url: url,
169       method: "POST",
170       data: {
171         data: "[timeout:5][out:json];" + query,
172       },
173       success: function(results) {
174         var features = {};
175
176         $section.find(".loader").stopTime("loading").hide();
177
178         for (var i = 0; i < results.elements.length; i++) {
179           var element = results.elements[i],
180             geometry = featureGeometry(element, features);
181
182           if (interestingFeature(element, latlng, radius)) {
183             var $li = $("<li>")
184               .addClass("query-result")
185               .data("geometry", geometry)
186               .appendTo($ul);
187             var $p = $("<p>")
188               .text(featurePrefix(element) + " ")
189               .appendTo($li);
190
191             $("<a>")
192               .attr("href", "/" + element.type + "/" + element.id)
193               .text(featureName(element))
194               .appendTo($p);
195           }
196         }
197
198         if ($ul.find("li").length == 0) {
199           $("<li>")
200             .text(I18n.t("javascripts.query.nothing_found"))
201             .appendTo($ul);
202         }
203       },
204       error: function(xhr, status, error) {
205         $section.find(".loader").stopTime("loading").hide();
206
207         $("<li>")
208           .text(I18n.t("javascripts.query." + status, { server: url, error: error }))
209           .appendTo($ul);
210       }
211     }));
212   }
213
214   /*
215    * To find nearby objects we ask overpass for the union of the
216    * following sets:
217    *
218    *   node(around:<radius>,<lat>,lng>)
219    *   way(around:<radius>,<lat>,lng>)
220    *   node(w)
221    *   relation(around:<radius>,<lat>,lng>)
222    *
223    * to find enclosing objects we first find all the enclosing areas:
224    *
225    *   is_in(<lat>,<lng>)->.a
226    *
227    * and then return the union of the following sets:
228    *
229    *   relation(pivot.a)
230    *   way(pivot.a)
231    *   node(w)
232    *
233    * In order to avoid overly large responses we don't currently
234    * attempt to complete any relations and instead just show those
235    * ways and nodes which are returned for other reasons.
236    */
237   function queryOverpass(lat, lng) {
238     var latlng = L.latLng(lat, lng),
239       radius = 10 * Math.pow(1.5, 19 - map.getZoom()),
240       around = "around:" + radius + "," + lat + "," + lng,
241       nodes = "node(" + around + ")",
242       ways = "way(" + around + ");node(w)",
243       relations = "relation(" + around + ")",
244       nearby = "(" + nodes + ";" + ways + ";" + relations + ");out;",
245       isin = "is_in(" + lat + "," + lng + ")->.a;(relation(pivot.a);way(pivot.a);node(w));out;";
246
247     $("#sidebar_content .query-intro")
248       .hide();
249
250     if (marker) map.removeLayer(marker);
251     marker = L.circle(latlng, radius, featureStyle).addTo(map);
252
253     $(document).everyTime(75, "fadeQueryMarker", function (i) {
254       if (i == 10) {
255         map.removeLayer(marker);
256       } else {
257         marker.setStyle({
258           opacity: 1 - i * 0.1,
259           fillOpacity: 0.5 - i * 0.05
260         });
261       }
262     }, 10);
263
264     runQuery(latlng, radius, nearby, $("#query-nearby"));
265     runQuery(latlng, radius, isin, $("#query-isin"));
266   }
267
268   function clickHandler(e) {
269     var precision = OSM.zoomPrecision(map.getZoom()),
270       lat = e.latlng.lat.toFixed(precision),
271       lng = e.latlng.lng.toFixed(precision);
272
273     OSM.router.route("/query?lat=" + lat + "&lon=" + lng);
274   }
275
276   function enableQueryMode() {
277     queryButton.addClass("active");
278     map.on("click", clickHandler);
279     $(map.getContainer()).addClass("query-active");
280   }
281
282   function disableQueryMode() {
283     if (marker) map.removeLayer(marker);
284     $(map.getContainer()).removeClass("query-active").removeClass("query-disabled");
285     map.off("click", clickHandler);
286     queryButton.removeClass("active");
287   }
288
289   var page = {};
290
291   page.pushstate = page.popstate = function(path) {
292     OSM.loadSidebarContent(path, function () {
293       page.load(path, true);
294     });
295   };
296
297   page.load = function(path, noCentre) {
298     var params = querystring.parse(path.substring(path.indexOf('?') + 1)),
299       latlng = L.latLng(params.lat, params.lon);
300
301     if (!window.location.hash &&
302         (!noCentre || !map.getBounds().contains(latlng))) {
303       OSM.router.withoutMoveListener(function () {
304         map.setView(latlng, 15);
305       });
306     }
307
308     queryOverpass(params.lat, params.lon);
309     enableQueryMode();
310   };
311
312   page.unload = function() {
313     disableQueryMode();
314   };
315
316   return page;
317 };