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 fetch_from_api(endpoint_name, params, callback) {
100 var api_url = generate_full_api_url(endpoint_name, params);
101 if (endpoint_name !== 'status') {
102 $('#api-request-link').attr('href', api_url);
104 $.get(api_url, function (data) {
109 function update_data_date() {
110 fetch_from_api('status', { format: 'json' }, function (data) {
111 $('#data-date').text(data.data_updated);
115 function render_template(el, template_name, page_context) {
116 var template_source = $('#' + template_name).text();
117 var template = Handlebars.compile(template_source);
118 var html = template(page_context);
122 function update_html_title(title) {
124 if (title && title.length > 1) {
125 prefix = title + ' | ';
127 $('head title').text(prefix + 'OpenStreetMap Nominatim');
130 function show_error(html) {
131 $('#error-overlay').html(html).show();
134 function hide_error() {
135 $('#error-overlay').empty().hide();
139 jQuery(document).ready(function () {
142 $(document).ajaxStart(function () {
143 $('#loading').fadeIn('fast');
144 }).ajaxComplete(function () {
145 $('#loading').fadeOut('fast');
146 }).ajaxError(function (event, jqXHR, ajaxSettings/* , thrownError */) {
147 // console.log(thrownError);
148 // console.log(ajaxSettings);
149 var url = ajaxSettings.url;
150 show_error('Error fetching results from <a href="' + url + '">' + url + '</a>');
153 // *********************************************************
155 // *********************************************************
158 function init_map_on_detail_page(lat, lon, geojson) {
159 var attribution = get_config_value('Map_Tile_Attribution') || null;
160 map = new L.map('map', {
161 // center: [nominatim_map_init.lat, nominatim_map_init.lon],
162 // zoom: nominatim_map_init.zoom,
163 attributionControl: (attribution && attribution.length),
164 scrollWheelZoom: true, // !L.Browser.touch,
168 L.tileLayer(get_config_value('Map_Tile_URL'), {
170 // '© <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
171 attribution: attribution
174 // var layerGroup = new L.layerGroup().addTo(map);
176 var circle = L.circleMarker([lat, lon], {
177 radius: 10, weight: 2, fillColor: '#ff7800', color: 'blue', opacity: 0.75
179 map.addLayer(circle);
182 var geojson_layer = L.geoJson(
183 // https://leafletjs.com/reference-1.0.3.html#path-option
184 parse_and_normalize_geojson_string(geojson),
187 return { interactive: false, color: 'blue' };
191 map.addLayer(geojson_layer);
192 map.fitBounds(geojson_layer.getBounds());
194 map.setView([lat, lon], 10);
197 var osm2 = new L.TileLayer(
198 get_config_value('Map_Tile_URL'),
202 attribution: (get_config_value('Map_Tile_Attribution') || null)
205 (new L.Control.MiniMap(osm2, { toggleDisplay: true })).addTo(map);
209 function details_page_load() {
211 var search_params = new URLSearchParams(window.location.search);
212 // var place_id = search_params.get('place_id');
214 var api_request_params = {
215 place_id: search_params.get('place_id'),
216 osmtype: search_params.get('osmtype'),
217 osmid: search_params.get('osmid'),
218 keywords: search_params.get('keywords'),
220 hierarchy: (search_params.get('hierarchy') === '1' ? 1 : 0),
226 if (api_request_params.place_id || (api_request_params.osmtype && api_request_params.osmid)) {
227 fetch_from_api('details', api_request_params, function (aFeature) {
228 var context = { aPlace: aFeature, base_url: window.location.search };
230 render_template($('main'), 'detailspage-template', context);
231 if (api_request_params.place_id) {
232 update_html_title('Details for ' + api_request_params.place_id);
234 update_html_title('Details for ' + api_request_params.osmtype + api_request_params.osmid);
239 var lat = aFeature.centroid.coordinates[1];
240 var lon = aFeature.centroid.coordinates[0];
241 init_map_on_detail_page(lat, lon, aFeature.geometry);
244 render_template($('main'), 'detailspage-index-template');
247 $('#form-by-type-and-id,#form-by-osm-url').on('submit', function (e) {
250 var val = $(this).find('input[type=edit]').val();
251 var matches = val.match(/^\s*([NWR])(\d+)\s*$/i);
254 matches = val.match(/\/(relation|way|node)\/(\d+)\s*$/);
258 $(this).find('input[name=osmtype]').val(matches[1].charAt(0).toUpperCase());
259 $(this).find('input[name=osmid]').val(matches[2]);
260 $(this).get(0).submit();
262 alert('invalid input');
267 // *********************************************************
268 // FORWARD/REVERSE SEARCH PAGE
269 // *********************************************************
272 function display_map_position(mouse_lat_lng) {
275 mouse_lat_lng = map.wrapLatLng(mouse_lat_lng);
278 var html_mouse = 'mouse position: -';
280 html_mouse = 'mouse position: '
281 + [mouse_lat_lng.lat.toFixed(5), mouse_lat_lng.lng.toFixed(5)].join(',');
283 var html_click = 'last click: -';
284 if (last_click_latlng) {
285 html_click = 'last click: '
286 + [last_click_latlng.lat.toFixed(5), last_click_latlng.lng.toFixed(5)].join(',');
289 var html_center = 'map center: '
290 + map.getCenter().lat.toFixed(5) + ',' + map.getCenter().lng.toFixed(5)
291 + ' <a target="_blank" href="' + map_link_to_osm() + '">view on osm.org</a>';
293 var html_zoom = 'map zoom: ' + map.getZoom();
294 var html_viewbox = 'viewbox: ' + map_viewbox_as_string();
296 $('#map-position-inner').html([
304 var center_lat_lng = map.wrapLatLng(map.getCenter());
305 var reverse_params = {
306 lat: center_lat_lng.lat.toFixed(5),
307 lon: center_lat_lng.lng.toFixed(5)
311 $('#switch-to-reverse').attr('href', 'reverse.html?' + $.param(reverse_params));
313 $('input#use_viewbox').trigger('change');
316 function init_map_on_search_page(is_reverse_search, nominatim_results, request_lat,
317 request_lon, init_zoom) {
319 var attribution = get_config_value('Map_Tile_Attribution') || null;
320 map = new L.map('map', {
321 // center: [nominatim_map_init.lat, nominatim_map_init.lon],
322 // zoom: nominatim_map_init.zoom,
323 attributionControl: (attribution && attribution.length),
324 scrollWheelZoom: true, // !L.Browser.touch,
329 L.tileLayer(get_config_value('Map_Tile_URL'), {
331 // '© <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
332 attribution: attribution
335 // console.log(Nominatim_Config);
337 map.setView([request_lat, request_lon], init_zoom);
339 var osm2 = new L.TileLayer(get_config_value('Map_Tile_URL'), {
342 attribution: attribution
344 new L.Control.MiniMap(osm2, { toggleDisplay: true }).addTo(map);
346 if (is_reverse_search) {
347 // We don't need a marker, but an L.circle instance changes radius once you zoom in/out
348 var cm = L.circleMarker(
349 [request_lat, request_lon],
353 fillColor: '#ff7800',
362 var search_params = new URLSearchParams(window.location.search);
363 var viewbox = search_params.get('viewbox');
365 var coords = viewbox.split(','); // <x1>,<y1>,<x2>,<y2>
366 var bounds = L.latLngBounds([coords[1], coords[0]], [coords[3], coords[2]]);
367 L.rectangle(bounds, {
377 var MapPositionControl = L.Control.extend({
381 onAdd: function (/* map */) {
382 var container = L.DomUtil.create('div', 'my-custom-control');
384 $(container).text('show map bounds')
385 .addClass('leaflet-bar btn btn-sm btn-outline-secondary')
386 .on('click', function (e) {
389 $('#map-position').show();
392 $('#map-position-close a').on('click', function (e) {
395 $('#map-position').hide();
403 map.addControl(new MapPositionControl());
409 function update_viewbox_field() {
411 $('input[name=viewbox]')
412 .val($('input#use_viewbox')
413 .prop('checked') ? map_viewbox_as_string() : '');
416 map.on('move', function () {
417 display_map_position();
418 update_viewbox_field();
421 map.on('mousemove', function (e) {
422 display_map_position(e.latlng);
425 map.on('click', function (e) {
426 last_click_latlng = e.latlng;
427 display_map_position();
430 map.on('load', function () {
431 display_map_position();
434 $('input#use_viewbox').on('change', function () {
435 update_viewbox_field();
438 function get_result_element(position) {
439 return $('.result').eq(position);
441 // function marker_for_result(result) {
442 // return L.marker([result.lat, result.lon], { riseOnHover: true, title: result.name });
444 function circle_for_result(result) {
448 fillColor: '#ff7800',
451 clickable: !is_reverse_search
453 return L.circleMarker([result.lat, result.lon], cm_style);
456 var layerGroup = (new L.layerGroup()).addTo(map);
458 function highlight_result(position, bool_focus) {
459 var result = nominatim_results[position];
460 if (!result) { return; }
461 var result_el = get_result_element(position);
463 $('.result').removeClass('highlight');
464 result_el.addClass('highlight');
466 layerGroup.clearLayers();
469 var circle = circle_for_result(result);
470 circle.on('click', function () {
471 highlight_result(position);
473 layerGroup.addLayer(circle);
476 if (result.boundingbox) {
478 [result.boundingbox[0] * 1, result.boundingbox[2] * 1],
479 [result.boundingbox[1] * 1, result.boundingbox[3] * 1]
483 if (result.geojson && result.geojson.type.match(/(Polygon)|(Line)/)) {
485 var geojson_layer = L.geoJson(
486 parse_and_normalize_geojson_string(result.geojson),
488 // https://leafletjs.com/reference-1.0.3.html#path-option
489 style: function (/* feature */) {
490 return { interactive: false, color: 'blue' };
494 layerGroup.addLayer(geojson_layer);
497 // var layer = L.rectangle(bounds, {color: "#ff7800", weight: 1} );
498 // layerGroup.addLayer(layer);
501 var result_coord = L.latLng(result.lat, result.lon);
503 if (is_reverse_search) {
504 // console.dir([result_coord, [request_lat, request_lon]]);
505 // make sure the search coordinates are in the map view as well
507 [result_coord, [request_lat, request_lon]],
510 maxZoom: map.getZoom()
514 map.panTo(result_coord, result.zoom || get_config_value('Map_Default_Zoom'));
524 $('.result').on('click', function () {
525 highlight_result($(this).data('position'), true);
528 if (is_reverse_search) {
529 map.on('click', function (e) {
530 $('form input[name=lat]').val(e.latlng.lat);
531 $('form input[name=lon]').val(e.latlng.wrap().lng);
535 $('#switch-coords').on('click', function (e) {
538 var lat = $('form input[name=lat]').val();
539 var lon = $('form input[name=lon]').val();
540 $('form input[name=lat]').val(lon);
541 $('form input[name=lon]').val(lat);
546 highlight_result(0, false);
548 // common mistake is to copy&paste latitude and longitude into the 'lat' search box
549 $('form input[name=lat]').on('change', function () {
550 var coords_split = $(this).val().split(',');
551 if (coords_split.length === 2) {
552 $(this).val(L.Util.trim(coords_split[0]));
553 $(this).siblings('input[name=lon]').val(L.Util.trim(coords_split[1]));
560 function search_page_load() {
562 var is_reverse_search = window.location.pathname.match(/reverse/);
564 var search_params = new URLSearchParams(window.location.search);
566 // return view('search', [
567 // 'sQuery' => $sQuery,
570 // 'aSearchResults' => $aSearchResults,
571 // 'sMoreURL' => 'example.com',
572 // 'sDataDate' => $this->fetch_status_date(),
576 var api_request_params;
579 if (is_reverse_search) {
580 api_request_params = {
581 lat: search_params.get('lat'),
582 lon: search_params.get('lon'),
583 zoom: (search_params.get('zoom') > 1
584 ? search_params.get('zoom')
585 : get_config_value('Reverse_Default_Search_Zoom')),
589 if (search_params.get('debug') === '1') {
590 window.location.href = generate_full_api_url('reverse', api_request_params);
596 fLat: api_request_params.lat,
597 fLon: api_request_params.lon,
598 iZoom: (search_params.get('zoom') > 1
599 ? api_request_params.zoom
600 : get_config_value('Reverse_Default_Search_Zoom'))
604 if (api_request_params.lat && api_request_params.lon) {
606 fetch_from_api('reverse', api_request_params, function (aPlace) {
612 context.bSearchRan = true;
613 context.aPlace = aPlace;
615 render_template($('main'), 'reversepage-template', context);
616 update_html_title('Reverse result for '
617 + api_request_params.lat
619 + api_request_params.lon);
621 init_map_on_search_page(
624 api_request_params.lat,
625 api_request_params.lon,
626 api_request_params.zoom
632 render_template($('main'), 'reversepage-template', context);
634 init_map_on_search_page(
637 get_config_value('Map_Default_Lat'),
638 get_config_value('Map_Default_Lon'),
639 get_config_value('Map_Default_Zoom')
644 api_request_params = {
645 q: search_params.get('q'),
646 street: search_params.get('street'),
647 city: search_params.get('city'),
648 county: search_params.get('county'),
649 state: search_params.get('state'),
650 country: search_params.get('country'),
651 postalcode: search_params.get('postalcode'),
652 polygon_geojson: get_config_value('Search_AreaPolygons', false) ? 1 : 0,
653 viewbox: search_params.get('viewbox'),
654 exclude_place_ids: search_params.get('exclude_place_ids'),
658 if (search_params.get('debug') === '1') {
659 window.location.href = generate_full_api_url('search', api_request_params);
664 sQuery: api_request_params.q,
665 sViewBox: search_params.get('viewbox'),
669 if (api_request_params.street || api_request_params.city || api_request_params.county
670 || api_request_params.state || api_request_params.country || api_request_params.postalcode) {
671 context.hStructured = {
672 street: api_request_params.street,
673 city: api_request_params.city,
674 county: api_request_params.county,
675 state: api_request_params.state,
676 country: api_request_params.country,
677 postalcode: api_request_params.postalcode
681 if (api_request_params.q || context.hStructured) {
683 fetch_from_api('search', api_request_params, function (aResults) {
685 context.bSearchRan = true;
686 context.aSearchResults = aResults;
688 // lonvia wrote: https://github.com/osm-search/nominatim-ui/issues/24
689 // I would suggest to remove the guessing and always show the link. Nominatim only returns
690 // one or two results when it believes the result to be a good enough match.
691 // if (aResults.length >= 10) {
692 var aExcludePlaceIds = [];
693 if (search_params.has('exclude_place_ids')) {
694 aExcludePlaceIds = search_params.get('exclude_place_ids').split(',');
696 for (var i = 0; i < aResults.length; i += 1) {
697 aExcludePlaceIds.push(aResults[i].place_id);
699 var parsed_url = new URLSearchParams(window.location.search);
700 parsed_url.set('exclude_place_ids', aExcludePlaceIds.join(','));
701 context.sMoreURL = '?' + parsed_url.toString();
703 render_template($('main'), 'searchpage-template', context);
704 update_html_title('Result for ' + api_request_params.q);
706 init_map_on_search_page(
709 get_config_value('Map_Default_Lat'),
710 get_config_value('Map_Default_Lon'),
711 get_config_value('Map_Default_Zoom')
719 render_template($('main'), 'searchpage-template', context);
721 init_map_on_search_page(
724 get_config_value('Map_Default_Lat'),
725 get_config_value('Map_Default_Lon'),
726 get_config_value('Map_Default_Zoom')
733 // *********************************************************
735 // *********************************************************
737 function deletable_page_load() {
739 var api_request_params = {
743 fetch_from_api('deletable', api_request_params, function (aPolygons) {
744 var context = { aPolygons: aPolygons };
746 render_template($('main'), 'deletable-template', context);
747 update_html_title('Deletable objects');
752 // *********************************************************
753 // BROKEN POLYGON PAGE
754 // *********************************************************
756 function polygons_page_load() {
758 var api_request_params = {
762 fetch_from_api('polygons', api_request_params, function (aPolygons) {
763 var context = { aPolygons: aPolygons };
765 render_template($('main'), 'polygons-template', context);
766 update_html_title('Broken polygons');
771 jQuery(document).ready(function () {
774 function parse_url_and_load_page() {
775 // 'search', 'reverse', 'details'
776 var pagename = window.location.pathname.replace('.html', '').replace(/^.*\//, '');
778 if (pagename === '') pagename = 'search';
780 $('body').attr('id', pagename + '-page');
782 if (pagename === 'search' || pagename === 'reverse') {
784 } else if (pagename === 'details') {
786 } else if (pagename === 'deletable') {
787 deletable_page_load();
788 } else if (pagename === 'polygons') {
789 polygons_page_load();
793 function is_relative_url(url) {
794 if (!url) return false;
795 if (url.indexOf('?') === 0) return true;
796 if (url.indexOf('/') === 0) return true;
797 if (url.indexOf('#') === 0) return false;
798 if (url.match(/^http/)) return false;
799 if (!url.match(/\.html/)) return true;
804 // remove any URL paramters with empty values
805 // '&empty=&filled=value' => 'filled=value'
806 function clean_up_url_parameters(url) {
807 var url_params = new URLSearchParams(url);
808 var to_delete = []; // deleting inside loop would skip iterations
809 url_params.forEach(function (value, key) {
810 if (value === '') to_delete.push(key);
812 for (var i = 0; i < to_delete.length; i += 1) {
813 url_params.delete(to_delete[i]);
815 return url_params.toString();
818 parse_url_and_load_page();
820 // load page after form submit
821 $(document).on('submit', 'form', function (e) {
824 var target_url = $(this).serialize();
825 target_url = clean_up_url_parameters(target_url);
827 window.history.pushState(myhistory, '', '?' + target_url);
829 parse_url_and_load_page();
832 // load page after click on relative URL
833 $(document).on('click', 'a', function (e) {
834 var target_url = $(this).attr('href');
835 if (!is_relative_url(target_url)) return;
840 window.history.pushState(myhistory, '', target_url);
842 parse_url_and_load_page();
845 // deal with back-button and other user action
846 window.onpopstate = function () {
847 parse_url_and_load_page();