6 // *********************************************************
8 // *********************************************************
10 var Nominatim_Config_Defaults = {
11 Nominatim_API_Endpoint: 'http://localhost/nominatim/',
12 Images_Base_Url: '/mapicons/',
13 Search_AreaPolygons: 1,
14 Reverse_Default_Search_Zoom: 18,
15 Map_Default_Lat: 20.0,
18 Map_Tile_URL: 'https://{s}.tile.osm.org/{z}/{x}/{y}.png',
19 Map_Tile_Attribution: '<a href="https://osm.org/copyright">OpenStreetMap contributors</a>'
22 // *********************************************************
24 // *********************************************************
27 function get_config_value(str, default_val) {
28 var value = ((typeof Nominatim_Config !== 'undefined')
29 && (typeof Nominatim_Config[str] !== 'undefined'))
30 ? Nominatim_Config[str]
31 : Nominatim_Config_Defaults[str];
32 return (typeof value !== 'undefined' ? value : default_val);
35 function parse_and_normalize_geojson_string(part) {
36 // normalize places the geometry into a featurecollection, similar to
37 // https://github.com/mapbox/geojson-normalize
38 var parsed_geojson = {
39 type: 'FeatureCollection',
48 return parsed_geojson;
51 function map_link_to_osm() {
52 var zoom = map.getZoom();
53 var lat = map.getCenter().lat;
54 var lng = map.getCenter().lng;
55 return 'https://openstreetmap.org/#map=' + zoom + '/' + lat + '/' + lng;
58 function map_viewbox_as_string() {
59 var bounds = map.getBounds();
60 var west = bounds.getWest();
61 var east = bounds.getEast();
63 if ((east - west) >= 360) { // covers more than whole planet
64 west = map.getCenter().lng - 179.999;
65 east = map.getCenter().lng + 179.999;
67 east = L.latLng(77, east).wrap().lng;
68 west = L.latLng(77, west).wrap().lng;
71 west.toFixed(5), // left
72 bounds.getNorth().toFixed(5), // top
73 east.toFixed(5), // right
74 bounds.getSouth().toFixed(5) // bottom
79 // *********************************************************
81 // *********************************************************
83 function generate_full_api_url(endpoint_name, params) {
85 // `&a=&b=&c=1` => '&c=1'
86 var param_names = Object.keys(params);
87 for (var i = 0; i < param_names.length; i += 1) {
88 var val = params[param_names[i]];
89 if (typeof (val) === 'undefined' || val === '' || val === null) {
90 delete params[param_names[i]];
94 var api_url = get_config_value('Nominatim_API_Endpoint') + endpoint_name + '.php?'
99 function update_last_updated(endpoint_name, params) {
100 if (endpoint_name === 'status') return;
102 var api_url = generate_full_api_url(endpoint_name, params);
103 $('#last-updated').show();
105 $('#api-request a').attr('href', api_url);
106 $('#api-request').show();
108 if (endpoint_name === 'search' || endpoint_name === 'reverse') {
109 $('#api-request-debug a').attr('href', api_url + '&debug=1');
110 $('#api-request-debug').show();
112 $('#api-request-debug').hide();
116 function fetch_from_api(endpoint_name, params, callback) {
117 var api_url = generate_full_api_url(endpoint_name, params);
118 $.get(api_url, function (data) {
119 if (endpoint_name !== 'status') {
120 update_last_updated(endpoint_name, params);
126 function update_data_date() {
127 fetch_from_api('status', { format: 'json' }, function (data) {
128 $('#last-updated').show();
129 $('#data-date').text(data.data_updated);
133 function render_template(el, template_name, page_context) {
134 var template_source = $('#' + template_name).text();
135 var template = Handlebars.compile(template_source);
136 var html = template(page_context);
140 function update_html_title(title) {
142 if (title && title.length > 1) {
143 prefix = title + ' | ';
145 $('head title').text(prefix + 'OpenStreetMap Nominatim');
148 function show_error(html) {
149 $('#error-overlay').html(html).show();
152 function hide_error() {
153 $('#error-overlay').empty().hide();
157 jQuery(document).ready(function () {
160 $(document).ajaxStart(function () {
161 $('#loading').fadeIn('fast');
162 }).ajaxComplete(function () {
163 $('#loading').fadeOut('fast');
164 }).ajaxError(function (event, jqXHR, ajaxSettings/* , thrownError */) {
165 // console.log(thrownError);
166 // console.log(ajaxSettings);
167 var url = ajaxSettings.url;
168 show_error('Error fetching results from <a href="' + url + '">' + url + '</a>');
171 // *********************************************************
173 // *********************************************************
176 function init_map_on_detail_page(lat, lon, geojson) {
177 var attribution = get_config_value('Map_Tile_Attribution') || null;
178 map = new L.map('map', {
179 // center: [nominatim_map_init.lat, nominatim_map_init.lon],
180 // zoom: nominatim_map_init.zoom,
181 attributionControl: (attribution && attribution.length),
182 scrollWheelZoom: true, // !L.Browser.touch,
186 L.tileLayer(get_config_value('Map_Tile_URL'), {
188 // '© <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
189 attribution: attribution
192 // var layerGroup = new L.layerGroup().addTo(map);
194 var circle = L.circleMarker([lat, lon], {
195 radius: 10, weight: 2, fillColor: '#ff7800', color: 'blue', opacity: 0.75
197 map.addLayer(circle);
200 var geojson_layer = L.geoJson(
201 // https://leafletjs.com/reference-1.0.3.html#path-option
202 parse_and_normalize_geojson_string(geojson),
205 return { interactive: false, color: 'blue' };
209 map.addLayer(geojson_layer);
210 map.fitBounds(geojson_layer.getBounds());
212 map.setView([lat, lon], 10);
215 var osm2 = new L.TileLayer(
216 get_config_value('Map_Tile_URL'),
220 attribution: (get_config_value('Map_Tile_Attribution') || null)
223 (new L.Control.MiniMap(osm2, { toggleDisplay: true })).addTo(map);
227 function details_page_load() {
229 var search_params = new URLSearchParams(window.location.search);
230 // var place_id = search_params.get('place_id');
232 var api_request_params = {
233 place_id: search_params.get('place_id'),
234 osmtype: search_params.get('osmtype'),
235 osmid: search_params.get('osmid'),
236 keywords: search_params.get('keywords'),
238 hierarchy: (search_params.get('hierarchy') === '1' ? 1 : 0),
244 if (api_request_params.place_id || (api_request_params.osmtype && api_request_params.osmid)) {
245 fetch_from_api('details', api_request_params, function (aFeature) {
246 var context = { aPlace: aFeature, base_url: window.location.search };
248 render_template($('main'), 'detailspage-template', context);
249 if (api_request_params.place_id) {
250 update_html_title('Details for ' + api_request_params.place_id);
252 update_html_title('Details for ' + api_request_params.osmtype + api_request_params.osmid);
257 var lat = aFeature.centroid.coordinates[1];
258 var lon = aFeature.centroid.coordinates[0];
259 init_map_on_detail_page(lat, lon, aFeature.geometry);
262 render_template($('main'), 'detailspage-index-template');
265 $('#form-by-type-and-id,#form-by-osm-url').on('submit', function (e) {
268 var val = $(this).find('input[type=edit]').val();
269 var matches = val.match(/^\s*([NWR])(\d+)\s*$/i);
272 matches = val.match(/\/(relation|way|node)\/(\d+)\s*$/);
276 $(this).find('input[name=osmtype]').val(matches[1].charAt(0).toUpperCase());
277 $(this).find('input[name=osmid]').val(matches[2]);
278 $(this).get(0).submit();
280 alert('invalid input');
285 // *********************************************************
286 // FORWARD/REVERSE SEARCH PAGE
287 // *********************************************************
290 function display_map_position(mouse_lat_lng) {
293 mouse_lat_lng = map.wrapLatLng(mouse_lat_lng);
296 var html_mouse = 'mouse position: -';
298 html_mouse = 'mouse position: '
299 + [mouse_lat_lng.lat.toFixed(5), mouse_lat_lng.lng.toFixed(5)].join(',');
301 var html_click = 'last click: -';
302 if (last_click_latlng) {
303 html_click = 'last click: '
304 + [last_click_latlng.lat.toFixed(5), last_click_latlng.lng.toFixed(5)].join(',');
307 var html_center = 'map center: '
308 + map.getCenter().lat.toFixed(5) + ',' + map.getCenter().lng.toFixed(5)
309 + ' <a target="_blank" href="' + map_link_to_osm() + '">view on osm.org</a>';
311 var html_zoom = 'map zoom: ' + map.getZoom();
312 var html_viewbox = 'viewbox: ' + map_viewbox_as_string();
314 $('#map-position-inner').html([
322 var center_lat_lng = map.wrapLatLng(map.getCenter());
323 var reverse_params = {
324 lat: center_lat_lng.lat.toFixed(5),
325 lon: center_lat_lng.lng.toFixed(5)
329 $('#switch-to-reverse').attr('href', 'reverse.html?' + $.param(reverse_params));
331 $('input#use_viewbox').trigger('change');
334 function init_map_on_search_page(is_reverse_search, nominatim_results, request_lat,
335 request_lon, init_zoom) {
337 var attribution = get_config_value('Map_Tile_Attribution') || null;
338 map = new L.map('map', {
339 // center: [nominatim_map_init.lat, nominatim_map_init.lon],
340 // zoom: nominatim_map_init.zoom,
341 attributionControl: (attribution && attribution.length),
342 scrollWheelZoom: true, // !L.Browser.touch,
347 L.tileLayer(get_config_value('Map_Tile_URL'), {
349 // '© <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
350 attribution: attribution
353 // console.log(Nominatim_Config);
355 map.setView([request_lat, request_lon], init_zoom);
357 var osm2 = new L.TileLayer(get_config_value('Map_Tile_URL'), {
360 attribution: attribution
362 new L.Control.MiniMap(osm2, { toggleDisplay: true }).addTo(map);
364 if (is_reverse_search) {
365 // We don't need a marker, but an L.circle instance changes radius once you zoom in/out
366 var cm = L.circleMarker(
367 [request_lat, request_lon],
371 fillColor: '#ff7800',
380 var search_params = new URLSearchParams(window.location.search);
381 var viewbox = search_params.get('viewbox');
383 var coords = viewbox.split(','); // <x1>,<y1>,<x2>,<y2>
384 var bounds = L.latLngBounds([coords[1], coords[0]], [coords[3], coords[2]]);
385 L.rectangle(bounds, {
395 var MapPositionControl = L.Control.extend({
399 onAdd: function (/* map */) {
400 var container = L.DomUtil.create('div', 'my-custom-control');
402 $(container).text('show map bounds')
403 .addClass('leaflet-bar btn btn-sm btn-outline-secondary')
404 .on('click', function (e) {
407 $('#map-position').show();
410 $('#map-position-close a').on('click', function (e) {
413 $('#map-position').hide();
421 map.addControl(new MapPositionControl());
427 function update_viewbox_field() {
429 $('input[name=viewbox]')
430 .val($('input#use_viewbox')
431 .prop('checked') ? map_viewbox_as_string() : '');
434 map.on('move', function () {
435 display_map_position();
436 update_viewbox_field();
439 map.on('mousemove', function (e) {
440 display_map_position(e.latlng);
443 map.on('click', function (e) {
444 last_click_latlng = e.latlng;
445 display_map_position();
448 map.on('load', function () {
449 display_map_position();
452 $('input#use_viewbox').on('change', function () {
453 update_viewbox_field();
456 function get_result_element(position) {
457 return $('.result').eq(position);
459 // function marker_for_result(result) {
460 // return L.marker([result.lat, result.lon], { riseOnHover: true, title: result.name });
462 function circle_for_result(result) {
466 fillColor: '#ff7800',
469 clickable: !is_reverse_search
471 return L.circleMarker([result.lat, result.lon], cm_style);
474 var layerGroup = (new L.layerGroup()).addTo(map);
476 function highlight_result(position, bool_focus) {
477 var result = nominatim_results[position];
478 if (!result) { return; }
479 var result_el = get_result_element(position);
481 $('.result').removeClass('highlight');
482 result_el.addClass('highlight');
484 layerGroup.clearLayers();
487 var circle = circle_for_result(result);
488 circle.on('click', function () {
489 highlight_result(position);
491 layerGroup.addLayer(circle);
494 if (result.boundingbox) {
496 [result.boundingbox[0] * 1, result.boundingbox[2] * 1],
497 [result.boundingbox[1] * 1, result.boundingbox[3] * 1]
501 if (result.geojson && result.geojson.type.match(/(Polygon)|(Line)/)) {
503 var geojson_layer = L.geoJson(
504 parse_and_normalize_geojson_string(result.geojson),
506 // https://leafletjs.com/reference-1.0.3.html#path-option
507 style: function (/* feature */) {
508 return { interactive: false, color: 'blue' };
512 layerGroup.addLayer(geojson_layer);
515 // var layer = L.rectangle(bounds, {color: "#ff7800", weight: 1} );
516 // layerGroup.addLayer(layer);
519 var result_coord = L.latLng(result.lat, result.lon);
521 if (is_reverse_search) {
522 // console.dir([result_coord, [request_lat, request_lon]]);
523 // make sure the search coordinates are in the map view as well
525 [result_coord, [request_lat, request_lon]],
528 maxZoom: map.getZoom()
532 map.panTo(result_coord, result.zoom || get_config_value('Map_Default_Zoom'));
542 $('.result').on('click', function () {
543 highlight_result($(this).data('position'), true);
546 if (is_reverse_search) {
547 map.on('click', function (e) {
548 $('form input[name=lat]').val(e.latlng.lat);
549 $('form input[name=lon]').val(e.latlng.wrap().lng);
553 $('#switch-coords').on('click', function (e) {
556 var lat = $('form input[name=lat]').val();
557 var lon = $('form input[name=lon]').val();
558 $('form input[name=lat]').val(lon);
559 $('form input[name=lon]').val(lat);
564 highlight_result(0, false);
566 // common mistake is to copy&paste latitude and longitude into the 'lat' search box
567 $('form input[name=lat]').on('change', function () {
568 var coords_split = $(this).val().split(',');
569 if (coords_split.length === 2) {
570 $(this).val(L.Util.trim(coords_split[0]));
571 $(this).siblings('input[name=lon]').val(L.Util.trim(coords_split[1]));
578 function search_page_load() {
580 var is_reverse_search = window.location.pathname.match(/reverse/);
582 var search_params = new URLSearchParams(window.location.search);
584 // return view('search', [
585 // 'sQuery' => $sQuery,
588 // 'aSearchResults' => $aSearchResults,
589 // 'sMoreURL' => 'example.com',
590 // 'sDataDate' => $this->fetch_status_date(),
594 var api_request_params;
597 if (is_reverse_search) {
598 api_request_params = {
599 lat: search_params.get('lat'),
600 lon: search_params.get('lon'),
601 zoom: (search_params.get('zoom') > 1
602 ? search_params.get('zoom')
603 : get_config_value('Reverse_Default_Search_Zoom')),
609 fLat: api_request_params.lat,
610 fLon: api_request_params.lon,
611 iZoom: (search_params.get('zoom') > 1
612 ? api_request_params.zoom
613 : get_config_value('Reverse_Default_Search_Zoom'))
617 if (api_request_params.lat && api_request_params.lon) {
619 fetch_from_api('reverse', api_request_params, function (aPlace) {
625 context.bSearchRan = true;
626 context.aPlace = aPlace;
628 render_template($('main'), 'reversepage-template', context);
629 update_html_title('Reverse result for '
630 + api_request_params.lat
632 + api_request_params.lon);
634 init_map_on_search_page(
637 api_request_params.lat,
638 api_request_params.lon,
639 api_request_params.zoom
645 render_template($('main'), 'reversepage-template', context);
647 init_map_on_search_page(
650 get_config_value('Map_Default_Lat'),
651 get_config_value('Map_Default_Lon'),
652 get_config_value('Map_Default_Zoom')
657 api_request_params = {
658 q: search_params.get('q'),
659 street: search_params.get('street'),
660 city: search_params.get('city'),
661 county: search_params.get('county'),
662 state: search_params.get('state'),
663 country: search_params.get('country'),
664 postalcode: search_params.get('postalcode'),
665 polygon_geojson: get_config_value('Search_AreaPolygons', false) ? 1 : 0,
666 viewbox: search_params.get('viewbox'),
667 exclude_place_ids: search_params.get('exclude_place_ids'),
672 sQuery: api_request_params.q,
673 sViewBox: search_params.get('viewbox'),
677 if (api_request_params.street || api_request_params.city || api_request_params.county
678 || api_request_params.state || api_request_params.country || api_request_params.postalcode) {
679 context.hStructured = {
680 street: api_request_params.street,
681 city: api_request_params.city,
682 county: api_request_params.county,
683 state: api_request_params.state,
684 country: api_request_params.country,
685 postalcode: api_request_params.postalcode
689 if (api_request_params.q || context.hStructured) {
691 fetch_from_api('search', api_request_params, function (aResults) {
693 context.bSearchRan = true;
694 context.aSearchResults = aResults;
696 // lonvia wrote: https://github.com/osm-search/nominatim-ui/issues/24
697 // I would suggest to remove the guessing and always show the link. Nominatim only returns
698 // one or two results when it believes the result to be a good enough match.
699 // if (aResults.length >= 10) {
700 var aExcludePlaceIds = [];
701 if (search_params.has('exclude_place_ids')) {
702 aExcludePlaceIds = search_params.get('exclude_place_ids').split(',');
704 for (var i = 0; i < aResults.length; i += 1) {
705 aExcludePlaceIds.push(aResults[i].place_id);
707 var parsed_url = new URLSearchParams(window.location.search);
708 parsed_url.set('exclude_place_ids', aExcludePlaceIds.join(','));
709 context.sMoreURL = '?' + parsed_url.toString();
711 render_template($('main'), 'searchpage-template', context);
712 update_html_title('Result for ' + api_request_params.q);
714 init_map_on_search_page(
717 get_config_value('Map_Default_Lat'),
718 get_config_value('Map_Default_Lon'),
719 get_config_value('Map_Default_Zoom')
727 render_template($('main'), 'searchpage-template', context);
729 init_map_on_search_page(
732 get_config_value('Map_Default_Lat'),
733 get_config_value('Map_Default_Lon'),
734 get_config_value('Map_Default_Zoom')
741 // *********************************************************
743 // *********************************************************
745 function deletable_page_load() {
747 var api_request_params = {
751 fetch_from_api('deletable', api_request_params, function (aPolygons) {
752 var context = { aPolygons: aPolygons };
754 render_template($('main'), 'deletable-template', context);
755 update_html_title('Deletable objects');
760 // *********************************************************
761 // BROKEN POLYGON PAGE
762 // *********************************************************
764 function polygons_page_load() {
766 var api_request_params = {
770 fetch_from_api('polygons', api_request_params, function (aPolygons) {
771 var context = { aPolygons: aPolygons };
773 render_template($('main'), 'polygons-template', context);
774 update_html_title('Broken polygons');
779 jQuery(document).ready(function () {
782 function parse_url_and_load_page() {
783 // 'search', 'reverse', 'details'
784 var pagename = window.location.pathname.replace('.html', '').replace(/^.*\//, '');
786 if (pagename === '') pagename = 'search';
788 $('body').attr('id', pagename + '-page');
790 if (pagename === 'search' || pagename === 'reverse') {
792 } else if (pagename === 'details') {
794 } else if (pagename === 'deletable') {
795 deletable_page_load();
796 } else if (pagename === 'polygons') {
797 polygons_page_load();
801 function is_relative_url(url) {
802 if (!url) return false;
803 if (url.match(/debug=1/)) return false;
804 if (url.indexOf('?') === 0) return true;
805 if (url.indexOf('/') === 0) return true;
806 if (url.indexOf('#') === 0) return false;
807 if (url.match(/^http/)) return false;
808 if (!url.match(/\.html/)) return true;
813 // remove any URL paramters with empty values
814 // '&empty=&filled=value' => 'filled=value'
815 function clean_up_url_parameters(url) {
816 var url_params = new URLSearchParams(url);
817 var to_delete = []; // deleting inside loop would skip iterations
818 url_params.forEach(function (value, key) {
819 if (value === '') to_delete.push(key);
821 for (var i = 0; i < to_delete.length; i += 1) {
822 url_params.delete(to_delete[i]);
824 return url_params.toString();
827 parse_url_and_load_page();
829 // load page after form submit
830 $(document).on('submit', 'form', function (e) {
833 var target_url = $(this).serialize();
834 target_url = clean_up_url_parameters(target_url);
836 window.history.pushState(myhistory, '', '?' + target_url);
838 parse_url_and_load_page();
841 // load page after click on relative URL
842 $(document).on('click', 'a', function (e) {
843 var target_url = $(this).attr('href');
844 if (!is_relative_url(target_url)) return;
849 window.history.pushState(myhistory, '', target_url);
851 parse_url_and_load_page();
854 // deal with back-button and other user action
855 window.onpopstate = function () {
856 parse_url_and_load_page();