1 OSM.Query = function (map) {
2 const control = $(".control-query"),
3 queryButton = control.find(".control-button"),
4 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"];
15 queryButton.on("click", function (e) {
19 if (control.hasClass("active")) {
21 } else if (!queryButton.hasClass("disabled")) {
24 }).on("disabled", function () {
25 if (control.hasClass("active")) {
26 map.off("click", clickHandler);
27 $(map.getContainer()).removeClass("query-active").addClass("query-disabled");
28 $(this).tooltip("show");
30 }).on("enabled", function () {
31 if (control.hasClass("active")) {
32 map.on("click", clickHandler);
33 $(map.getContainer()).removeClass("query-disabled").addClass("query-active");
34 $(this).tooltip("hide");
38 function showResultGeometry() {
39 const geometry = $(this).data("geometry");
40 if (geometry) map.addLayer(geometry);
41 $(this).addClass("selected");
44 function hideResultGeometry() {
45 const geometry = $(this).data("geometry");
46 if (geometry) map.removeLayer(geometry);
47 $(this).removeClass("selected");
51 .on("mouseover", ".query-results a", showResultGeometry)
52 .on("mouseout", ".query-results a", hideResultGeometry);
54 function interestingFeature(feature) {
56 for (const key in feature.tags) {
57 if (uninterestingTags.indexOf(key) < 0) {
66 function featurePrefix(feature) {
67 const tags = feature.tags;
70 if (tags.boundary === "administrative" && (tags.border_type || tags.admin_level)) {
71 prefix = OSM.i18n.t("geocoder.search_osm_nominatim.border_types." + tags.border_type, {
72 defaultValue: OSM.i18n.t("geocoder.search_osm_nominatim.admin_levels.level" + tags.admin_level, {
73 defaultValue: OSM.i18n.t("geocoder.search_osm_nominatim.prefix.boundary.administrative")
77 const prefixes = OSM.i18n.t("geocoder.search_osm_nominatim.prefix");
79 for (const key in tags) {
80 const value = tags[key];
83 if (prefixes[key][value]) {
84 return prefixes[key][value];
89 for (const key in tags) {
90 const value = tags[key];
93 const first = value.slice(0, 1).toUpperCase(),
94 rest = value.slice(1).replace(/_/g, " ");
102 prefix = OSM.i18n.t("javascripts.query." + feature.type);
108 function featureName(feature) {
109 const tags = feature.tags,
110 localeKeys = OSM.preferred_languages.map(locale => `name:${locale}`);
112 for (const key of [...localeKeys, "name", "ref", "addr:housename"]) {
113 if (tags[key]) return tags[key];
115 // TODO: Localize format to country of address
116 if (tags["addr:housenumber"] && tags["addr:street"]) return `${tags["addr:housenumber"]} ${tags["addr:street"]}`;
118 return "#" + feature.id;
121 function featureGeometry(feature) {
124 if (feature.type === "node" && feature.lat && feature.lon) {
125 geometry = L.circleMarker([feature.lat, feature.lon], featureStyle);
126 } else if (feature.type === "way" && feature.geometry && feature.geometry.length > 0) {
127 geometry = L.polyline(feature.geometry.filter(function (point) {
128 return point !== null;
129 }).map(function (point) {
130 return [point.lat, point.lon];
132 } else if (feature.type === "relation" && feature.members) {
133 geometry = L.featureGroup(feature.members.map(featureGeometry).filter(function (geometry) {
134 return typeof geometry !== "undefined";
141 function runQuery(latlng, radius, query, $section, merge, compare) {
142 const $ul = $section.find("ul");
147 if ($section.data("ajax")) {
148 $section.data("ajax").abort();
151 $section.data("ajax", new AbortController());
152 fetch(OSM.OVERPASS_URL, {
154 body: new URLSearchParams({
155 data: "[timeout:10][out:json];" + query
157 credentials: OSM.OVERPASS_CREDENTIALS ? "include" : "same-origin",
158 signal: $section.data("ajax").signal
160 .then(response => response.json())
161 .then(function (results) {
164 $section.find(".loader").hide();
167 elements = Object.values(results.elements.reduce(function (hash, element) {
168 const key = element.type + element.id;
169 if ("geometry" in element) {
170 delete element.bounds;
172 hash[key] = $.extend({}, hash[key], element);
176 elements = results.elements;
180 elements = elements.sort(compare);
183 for (const element of elements) {
184 if (!interestingFeature(element)) continue;
186 const $li = $("<li>")
187 .addClass("list-group-item list-group-item-action")
188 .text(featurePrefix(element) + " ")
192 .addClass("stretched-link")
193 .attr("href", "/" + element.type + "/" + element.id)
194 .data("geometry", featureGeometry(element))
195 .text(featureName(element))
199 if (results.remark) {
201 .addClass("list-group-item")
202 .text(OSM.i18n.t("javascripts.query.error", { server: OSM.OVERPASS_URL, error: results.remark }))
206 if ($ul.find("li").length === 0) {
208 .addClass("list-group-item")
209 .text(OSM.i18n.t("javascripts.query.nothing_found"))
213 .catch(function (error) {
214 if (error.name === "AbortError") return;
216 $section.find(".loader").hide();
219 .addClass("list-group-item")
220 .text(OSM.i18n.t("javascripts.query.error", { server: OSM.OVERPASS_URL, error: error.message }))
225 function featureArea({ bounds }) {
226 const height = bounds.maxlat - bounds.minlat;
227 let width = bounds.maxlon - bounds.minlon;
229 if (width < 0) width += 360;
230 return width * height;
234 * To find nearby objects we ask overpass for the union of the
237 * node(around:<radius>,<lat>,<lng>)
238 * way(around:<radius>,<lat>,<lng>)
239 * relation(around:<radius>,<lat>,<lng>)
241 * to find enclosing objects we first find all the enclosing areas:
243 * is_in(<lat>,<lng>)->.a
245 * and then return the union of the following sets:
250 * In both cases we then ask to retrieve tags and the geometry
253 function queryOverpass(lat, lng) {
254 const latlng = L.latLng(lat, lng).wrap(),
255 bounds = map.getBounds().wrap(),
256 zoom = map.getZoom(),
257 bbox = [bounds.getSouthWest(), bounds.getNorthEast()]
258 .map(c => OSM.cropLocation(c, zoom))
260 geombbox = "geom(" + bbox + ");",
261 radius = 10 * Math.pow(1.5, 19 - zoom),
262 around = "(around:" + radius + "," + lat + "," + lng + ")",
263 nodes = "node" + around,
264 ways = "way" + around,
265 relations = "relation" + around,
266 nearby = "(" + nodes + ";" + ways + ";);out tags " + geombbox + relations + ";out " + geombbox,
267 isin = "is_in(" + lat + "," + lng + ")->.a;way(pivot.a);out tags bb;out ids " + geombbox + "relation(pivot.a);out tags bb;";
269 $("#sidebar_content .query-intro")
272 if (marker) map.removeLayer(marker);
273 marker = L.circle(latlng, {
275 className: "query-marker",
279 runQuery(latlng, radius, nearby, $("#query-nearby"), false);
280 runQuery(latlng, radius, isin, $("#query-isin"), true, (feature1, feature2) => featureArea(feature1) - featureArea(feature2));
283 function clickHandler(e) {
284 const [lat, lon] = OSM.cropLocation(e.latlng, map.getZoom());
286 OSM.router.route("/query?" + new URLSearchParams({ lat, lon }));
289 function enableQueryMode() {
290 control.addClass("active");
291 map.on("click", clickHandler);
292 $(map.getContainer()).addClass("query-active");
295 function disableQueryMode() {
296 if (marker) map.removeLayer(marker);
297 $(map.getContainer()).removeClass("query-active").removeClass("query-disabled");
298 map.off("click", clickHandler);
299 control.removeClass("active");
304 page.pushstate = page.popstate = function (path) {
305 OSM.loadSidebarContent(path, function () {
306 page.load(path, true);
310 page.load = function (path, noCentre) {
311 const params = new URLSearchParams(path.substring(path.indexOf("?"))),
312 latlng = L.latLng(params.get("lat"), params.get("lon"));
314 if (!location.hash && !noCentre && !map.getBounds().contains(latlng)) {
315 OSM.router.withoutMoveListener(function () {
316 map.setView(latlng, 15);
320 queryOverpass(params.get("lat"), params.get("lon"));
323 page.unload = function (sameController) {
324 if (!sameController) {
326 $("#sidebar_content .query-results a.selected").each(hideResultGeometry);