1 OSM.initializations.push(function (map) {
2 const control = $(".control-query"),
3 queryButton = control.find(".control-button");
5 queryButton.on("click", function (e) {
9 if (control.hasClass("active")) {
11 } else if (!queryButton.hasClass("disabled")) {
14 }).on("disabled", function () {
15 if (control.hasClass("active")) {
16 map.off("click", clickHandler);
17 $(map.getContainer()).removeClass("query-active").addClass("query-disabled");
18 $(this).tooltip("show");
20 }).on("enabled", function () {
21 if (control.hasClass("active")) {
22 map.on("click", clickHandler);
23 $(map.getContainer()).removeClass("query-disabled").addClass("query-active");
24 $(this).tooltip("hide");
28 function clickHandler(e) {
29 const [lat, lon] = OSM.cropLocation(e.latlng, map.getZoom());
31 OSM.router.route("/query?" + new URLSearchParams({ lat, lon }));
34 function enableQueryMode() {
35 $(".control-query").addClass("active");
36 map.on("click", clickHandler);
37 $(map.getContainer()).addClass("query-active");
40 function disableQueryMode() {
41 $(map.getContainer()).removeClass("query-active").removeClass("query-disabled");
42 map.off("click", clickHandler);
43 $(".control-query").removeClass("active");
47 OSM.Query = function (map) {
48 const 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"];
51 const featureStyle = {
59 function showResultGeometry() {
60 const geometry = $(this).data("geometry");
61 if (geometry) map.addLayer(geometry);
62 $(this).addClass("selected");
65 function hideResultGeometry() {
66 const geometry = $(this).data("geometry");
67 if (geometry) map.removeLayer(geometry);
68 $(this).removeClass("selected");
72 .on("mouseover", ".query-results a", showResultGeometry)
73 .on("mouseout", ".query-results a", hideResultGeometry);
75 function interestingFeature(feature) {
77 for (const key in feature.tags) {
78 if (uninterestingTags.indexOf(key) < 0) {
87 function featurePrefix(feature) {
88 const tags = feature.tags;
91 if (tags.boundary === "administrative" && (tags.border_type || tags.admin_level)) {
92 prefix = OSM.i18n.t("geocoder.search_osm_nominatim.border_types." + tags.border_type, {
93 defaultValue: OSM.i18n.t("geocoder.search_osm_nominatim.admin_levels.level" + tags.admin_level, {
94 defaultValue: OSM.i18n.t("geocoder.search_osm_nominatim.prefix.boundary.administrative")
98 const prefixes = OSM.i18n.t("geocoder.search_osm_nominatim.prefix");
100 for (const key in tags) {
101 const value = tags[key];
104 if (prefixes[key][value]) {
105 return prefixes[key][value];
110 for (const key in tags) {
111 const value = tags[key];
114 const first = value.slice(0, 1).toUpperCase(),
115 rest = value.slice(1).replace(/_/g, " ");
123 prefix = OSM.i18n.t("javascripts.query." + feature.type);
129 function featureName(feature) {
130 const tags = feature.tags,
131 localeKeys = OSM.preferred_languages.map(locale => `name:${locale}`);
133 for (const key of [...localeKeys, "name", "ref", "addr:housename"]) {
134 if (tags[key]) return tags[key];
136 if (tags["addr:housenumber"] && tags["addr:street"]) return `${tags["addr:housenumber"]} ${tags["addr:street"]}`;
138 return "#" + feature.id;
141 function featureGeometry(feature) {
142 switch (feature.type) {
144 if (!feature.lat || !feature.lon) return;
145 return L.circleMarker([feature.lat, feature.lon], featureStyle);
147 if (!feature.geometry?.length) return;
148 return L.polyline(feature.geometry.filter(p => p).map(p => [p.lat, p.lon]), featureStyle);
150 if (!feature.members?.length) return;
151 return L.featureGroup(feature.members.map(featureGeometry).filter(g => g));
155 function runQuery(query, $section, merge, compare) {
156 const $ul = $section.find("ul");
161 if ($section.data("ajax")) {
162 $section.data("ajax").abort();
165 $section.data("ajax", new AbortController());
166 fetch(OSM.OVERPASS_URL, {
168 body: new URLSearchParams({
169 data: "[timeout:10][out:json];" + query
171 credentials: OSM.OVERPASS_CREDENTIALS ? "include" : "same-origin",
172 signal: $section.data("ajax").signal
176 return response.json();
178 throw new Error(response.statusText || response.status);
180 .then(function (results) {
181 let elements = results.elements;
183 $section.find(".loader").hide();
185 // Make Overpass-specific bounds to Leaflet compatible
186 for (const element of elements) {
187 if (!element.bounds) continue;
188 if (element.bounds.maxlon >= element.bounds.minlon) continue;
189 element.bounds.maxlon += 360;
193 elements = Object.values(elements.reduce(function (hash, element) {
194 const key = element.type + element.id;
195 if ("geometry" in element) delete element.bounds;
196 hash[key] = { ...hash[key], ...element };
202 elements = elements.sort(compare);
205 for (const element of elements) {
206 if (!interestingFeature(element)) continue;
208 const $li = $("<li>")
209 .addClass("list-group-item list-group-item-action")
210 .text(featurePrefix(element) + " ")
214 .addClass("stretched-link")
215 .attr("href", "/" + element.type + "/" + element.id)
216 .data("geometry", featureGeometry(element))
217 .text(featureName(element))
221 if (results.remark) renderError($ul, results.remark);
223 if ($ul.find("li").length === 0) {
225 .addClass("list-group-item")
226 .text(OSM.i18n.t("javascripts.query.nothing_found"))
230 .catch(function (error) {
231 if (error.name === "AbortError") return;
233 $section.find(".loader").hide();
235 renderError($ul, error.message);
239 function renderError($ul, errorMessage) {
241 .addClass("list-group-item")
242 .text(OSM.i18n.t("javascripts.query.error", { server: OSM.OVERPASS_URL, error: errorMessage }))
246 function size({ maxlon, minlon, maxlat, minlat }) {
247 return (maxlon - minlon) * (maxlat - minlat);
251 * To find nearby objects we ask overpass for the union of the
254 * node(around:<radius>,<lat>,<lng>)
255 * way(around:<radius>,<lat>,<lng>)
256 * relation(around:<radius>,<lat>,<lng>)
258 * to find enclosing objects we first find all the enclosing areas:
260 * is_in(<lat>,<lng>)->.a
262 * and then return the union of the following sets:
267 * In both cases we then ask to retrieve tags and the geometry
270 function queryOverpass(latlng) {
271 const bounds = map.getBounds(),
272 zoom = map.getZoom(),
273 bbox = [bounds.getSouthWest(), bounds.getNorthEast()]
274 .map(c => OSM.cropLocation(c, zoom))
276 geom = `geom(${bbox})`,
277 radius = 10 * Math.pow(1.5, 19 - zoom),
278 here = `(around:${radius},${latlng})`,
279 enclosed = "(pivot.a);out tags bb",
280 nearby = `(node${here};way${here};);out tags ${geom};relation${here};out ${geom};`,
281 isin = `is_in(${latlng})->.a;way${enclosed};out ids ${geom};relation${enclosed};`;
283 $("#sidebar_content .query-intro")
286 if (marker) map.removeLayer(marker);
287 marker = L.circle(L.latLng(latlng).wrap(), {
289 className: "query-marker",
293 runQuery(nearby, $("#query-nearby"), false);
294 runQuery(isin, $("#query-isin"), true, (feature1, feature2) => size(feature1.bounds) - size(feature2.bounds));
299 page.pushstate = page.popstate = function (path) {
300 OSM.loadSidebarContent(path, function () {
301 page.load(path, true);
305 page.load = function (path, noCentre) {
306 const params = new URLSearchParams(path.substring(path.indexOf("?"))),
307 latlng = L.latLng(params.get("lat"), params.get("lon"));
309 if (!location.hash && !noCentre && !map.getBounds().contains(latlng)) {
310 OSM.router.withoutMoveListener(function () {
311 map.setView(latlng, 15);
315 queryOverpass([params.get("lat"), params.get("lon")]);
318 page.unload = function (sameController) {
319 if (!sameController) {
320 $("#sidebar_content .query-results a.selected").each(hideResultGeometry);