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");
46 OSM.Query = function (map) {
47 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"];
50 const featureStyle = {
58 function showResultGeometry() {
59 const geometry = $(this).data("geometry");
60 if (geometry) map.addLayer(geometry);
61 $(this).addClass("selected");
64 function hideResultGeometry() {
65 const geometry = $(this).data("geometry");
66 if (geometry) map.removeLayer(geometry);
67 $(this).removeClass("selected");
71 .on("mouseover", ".query-results a", showResultGeometry)
72 .on("mouseout", ".query-results a", hideResultGeometry);
74 function interestingFeature(feature) {
76 for (const key in feature.tags) {
77 if (uninterestingTags.indexOf(key) < 0) {
86 function featurePrefix(feature) {
87 const tags = feature.tags;
90 if (tags.boundary === "administrative" && (tags.border_type || tags.admin_level)) {
91 prefix = OSM.i18n.t("geocoder.search_osm_nominatim.border_types." + tags.border_type, {
92 defaultValue: OSM.i18n.t("geocoder.search_osm_nominatim.admin_levels.level" + tags.admin_level, {
93 defaultValue: OSM.i18n.t("geocoder.search_osm_nominatim.prefix.boundary.administrative")
97 const prefixes = OSM.i18n.t("geocoder.search_osm_nominatim.prefix");
99 for (const key in tags) {
100 const value = tags[key];
103 if (prefixes[key][value]) {
104 return prefixes[key][value];
109 for (const key in tags) {
110 const value = tags[key];
113 const first = value.slice(0, 1).toUpperCase(),
114 rest = value.slice(1).replace(/_/g, " ");
122 prefix = OSM.i18n.t("javascripts.query." + feature.type);
128 function featureName(feature) {
129 const tags = feature.tags,
130 localeKeys = OSM.preferred_languages.map(locale => `name:${locale}`);
132 for (const key of [...localeKeys, "name", "ref", "addr:housename"]) {
133 if (tags[key]) return tags[key];
135 if (tags["addr:housenumber"] && tags["addr:street"]) return `${tags["addr:housenumber"]} ${tags["addr:street"]}`;
137 return "#" + feature.id;
140 function featureGeometry(feature) {
141 switch (feature.type) {
143 if (!feature.lat || !feature.lon) return;
144 return L.circleMarker([feature.lat, feature.lon], featureStyle);
146 if (!feature.geometry?.length) return;
147 return L.polyline(feature.geometry.filter(p => p).map(p => [p.lat, p.lon]), featureStyle);
149 if (!feature.members?.length) return;
150 return L.featureGroup(feature.members.map(featureGeometry).filter(g => g));
154 function runQuery(query, $section, merge, compare) {
155 const $ul = $section.find("ul");
160 if ($section.data("ajax")) {
161 $section.data("ajax").abort();
164 $section.data("ajax", new AbortController());
165 fetch(OSM.OVERPASS_URL, {
167 body: new URLSearchParams({
168 data: "[timeout:10][out:json];" + query
170 credentials: OSM.OVERPASS_CREDENTIALS ? "include" : "same-origin",
171 signal: $section.data("ajax").signal
173 .then(response => response.json())
174 .then(function (results) {
175 let elements = results.elements;
177 $section.find(".loader").hide();
179 // Make Overpass-specific bounds to Leaflet compatible
180 for (const element of elements) {
181 if (!element.bounds) continue;
182 if (element.bounds.maxlon >= element.bounds.minlon) continue;
183 element.bounds.maxlon += 360;
187 elements = Object.values(elements.reduce(function (hash, element) {
188 const key = element.type + element.id;
189 if ("geometry" in element) delete element.bounds;
190 hash[key] = { ...hash[key], ...element };
196 elements = elements.sort(compare);
199 for (const element of elements) {
200 if (!interestingFeature(element)) continue;
202 const $li = $("<li>")
203 .addClass("list-group-item list-group-item-action")
204 .text(featurePrefix(element) + " ")
208 .addClass("stretched-link")
209 .attr("href", "/" + element.type + "/" + element.id)
210 .data("geometry", featureGeometry(element))
211 .text(featureName(element))
215 if (results.remark) renderError($ul, results.remark);
217 if ($ul.find("li").length === 0) {
219 .addClass("list-group-item")
220 .text(OSM.i18n.t("javascripts.query.nothing_found"))
224 .catch(function (error) {
225 if (error.name === "AbortError") return;
227 $section.find(".loader").hide();
229 renderError($ul, error.message);
233 function renderError($ul, errorMessage) {
235 .addClass("list-group-item")
236 .text(OSM.i18n.t("javascripts.query.error", { server: OSM.OVERPASS_URL, error: errorMessage }))
240 function size({ maxlon, minlon, maxlat, minlat }) {
241 return (maxlon - minlon) * (maxlat - minlat);
245 * To find nearby objects we ask overpass for the union of the
248 * node(around:<radius>,<lat>,<lng>)
249 * way(around:<radius>,<lat>,<lng>)
250 * relation(around:<radius>,<lat>,<lng>)
252 * to find enclosing objects we first find all the enclosing areas:
254 * is_in(<lat>,<lng>)->.a
256 * and then return the union of the following sets:
261 * In both cases we then ask to retrieve tags and the geometry
264 function queryOverpass(latlng) {
265 const bounds = map.getBounds(),
266 zoom = map.getZoom(),
267 bbox = [bounds.getSouthWest(), bounds.getNorthEast()]
268 .map(c => OSM.cropLocation(c, zoom))
270 geom = `geom(${bbox})`,
271 radius = 10 * Math.pow(1.5, 19 - zoom),
272 here = `(around:${radius},${latlng})`,
273 enclosed = "(pivot.a);out tags bb",
274 nearby = `(node${here};way${here};);out tags ${geom};relation${here};out ${geom};`,
275 isin = `is_in(${latlng})->.a;way${enclosed};out ids ${geom};relation${enclosed};`;
277 $("#sidebar_content .query-intro")
280 if (marker) map.removeLayer(marker);
281 marker = L.circle(L.latLng(latlng).wrap(), {
283 className: "query-marker",
287 runQuery(nearby, $("#query-nearby"), false);
288 runQuery(isin, $("#query-isin"), true, (feature1, feature2) => size(feature1.bounds) - size(feature2.bounds));
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) {
314 $("#sidebar_content .query-results a.selected").each(hideResultGeometry);