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) {
122 switch (feature.type) {
124 if (!feature.lat || !feature.lon) return;
125 return L.circleMarker([feature.lat, feature.lon], featureStyle);
127 if (!feature.geometry?.length) return;
128 return L.polyline(feature.geometry.filter(p => p).map(p => [p.lat, p.lon]), featureStyle);
130 if (!feature.members?.length) return;
131 return L.featureGroup(feature.members.map(featureGeometry).filter(g => g));
135 function runQuery(query, $section, merge, compare) {
136 const $ul = $section.find("ul");
141 if ($section.data("ajax")) {
142 $section.data("ajax").abort();
145 $section.data("ajax", new AbortController());
146 fetch(OSM.OVERPASS_URL, {
148 body: new URLSearchParams({
149 data: "[timeout:10][out:json];" + query
151 credentials: OSM.OVERPASS_CREDENTIALS ? "include" : "same-origin",
152 signal: $section.data("ajax").signal
154 .then(response => response.json())
155 .then(function (results) {
156 let elements = results.elements;
158 $section.find(".loader").hide();
160 // Make Overpass-specific bounds to Leaflet compatible
161 for (const element of elements) {
162 if (!element.bounds) continue;
163 if (element.bounds.maxlon >= element.bounds.minlon) continue;
164 element.bounds.maxlon += 360;
168 elements = Object.values(elements.reduce(function (hash, element) {
169 const key = element.type + element.id;
170 if ("geometry" in element) delete element.bounds;
171 hash[key] = { ...hash[key], ...element };
177 elements = elements.sort(compare);
180 for (const element of elements) {
181 if (!interestingFeature(element)) continue;
183 const $li = $("<li>")
184 .addClass("list-group-item list-group-item-action")
185 .text(featurePrefix(element) + " ")
189 .addClass("stretched-link")
190 .attr("href", "/" + element.type + "/" + element.id)
191 .data("geometry", featureGeometry(element))
192 .text(featureName(element))
196 if (results.remark) renderError($ul, results.remark);
198 if ($ul.find("li").length === 0) {
200 .addClass("list-group-item")
201 .text(OSM.i18n.t("javascripts.query.nothing_found"))
205 .catch(function (error) {
206 if (error.name === "AbortError") return;
208 $section.find(".loader").hide();
210 renderError($ul, error.message);
214 function renderError($ul, errorMessage) {
216 .addClass("list-group-item")
217 .text(OSM.i18n.t("javascripts.query.error", { server: OSM.OVERPASS_URL, error: errorMessage }))
221 function size({ maxlon, minlon, maxlat, minlat }) {
222 return (maxlon - minlon) * (maxlat - minlat);
226 * To find nearby objects we ask overpass for the union of the
229 * node(around:<radius>,<lat>,<lng>)
230 * way(around:<radius>,<lat>,<lng>)
231 * relation(around:<radius>,<lat>,<lng>)
233 * to find enclosing objects we first find all the enclosing areas:
235 * is_in(<lat>,<lng>)->.a
237 * and then return the union of the following sets:
242 * In both cases we then ask to retrieve tags and the geometry
245 function queryOverpass(latlng) {
246 const bounds = map.getBounds(),
247 zoom = map.getZoom(),
248 bbox = [bounds.getSouthWest(), bounds.getNorthEast()]
249 .map(c => OSM.cropLocation(c, zoom))
251 geom = `geom(${bbox})`,
252 radius = 10 * Math.pow(1.5, 19 - zoom),
253 here = `(around:${radius},${latlng})`,
254 enclosed = "(pivot.a);out tags bb",
255 nearby = `(node${here};way${here};);out tags ${geom};relation${here};out ${geom};`,
256 isin = `is_in(${latlng})->.a;way${enclosed};out ids ${geom};relation${enclosed};`;
258 $("#sidebar_content .query-intro")
261 if (marker) map.removeLayer(marker);
262 marker = L.circle(L.latLng(latlng).wrap(), {
264 className: "query-marker",
268 runQuery(nearby, $("#query-nearby"), false);
269 runQuery(isin, $("#query-isin"), true, (feature1, feature2) => size(feature1.bounds) - size(feature2.bounds));
272 function clickHandler(e) {
273 const [lat, lon] = OSM.cropLocation(e.latlng, map.getZoom());
275 OSM.router.route("/query?" + new URLSearchParams({ lat, lon }));
278 function enableQueryMode() {
279 control.addClass("active");
280 map.on("click", clickHandler);
281 $(map.getContainer()).addClass("query-active");
284 function disableQueryMode() {
285 if (marker) map.removeLayer(marker);
286 $(map.getContainer()).removeClass("query-active").removeClass("query-disabled");
287 map.off("click", clickHandler);
288 control.removeClass("active");
293 page.pushstate = page.popstate = function (path) {
294 OSM.loadSidebarContent(path, function () {
295 page.load(path, true);
299 page.load = function (path, noCentre) {
300 const params = new URLSearchParams(path.substring(path.indexOf("?"))),
301 latlng = L.latLng(params.get("lat"), params.get("lon"));
303 if (!location.hash && !noCentre && !map.getBounds().contains(latlng)) {
304 OSM.router.withoutMoveListener(function () {
305 map.setView(latlng, 15);
309 queryOverpass([params.get("lat"), params.get("lon")]);
312 page.unload = function (sameController) {
313 if (!sameController) {
315 $("#sidebar_content .query-results a.selected").each(hideResultGeometry);