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 $('#last-updated').hide();
162 $(document).ajaxStart(function () {
163 $('#loading').fadeIn('fast');
164 }).ajaxComplete(function () {
165 $('#loading').fadeOut('fast');
166 }).ajaxError(function (event, jqXHR, ajaxSettings/* , thrownError */) {
167 // console.log(thrownError);
168 // console.log(ajaxSettings);
169 var url = ajaxSettings.url;
170 show_error('Error fetching results from <a href="' + url + '">' + url + '</a>');
173 // *********************************************************
175 // *********************************************************
178 function init_map_on_detail_page(lat, lon, geojson) {
179 var attribution = get_config_value('Map_Tile_Attribution') || null;
180 map = new L.map('map', {
181 // center: [nominatim_map_init.lat, nominatim_map_init.lon],
182 // zoom: nominatim_map_init.zoom,
183 attributionControl: (attribution && attribution.length),
184 scrollWheelZoom: true, // !L.Browser.touch,
188 L.tileLayer(get_config_value('Map_Tile_URL'), {
190 // '© <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
191 attribution: attribution
194 // var layerGroup = new L.layerGroup().addTo(map);
196 var circle = L.circleMarker([lat, lon], {
197 radius: 10, weight: 2, fillColor: '#ff7800', color: 'blue', opacity: 0.75
199 map.addLayer(circle);
202 var geojson_layer = L.geoJson(
203 // https://leafletjs.com/reference-1.0.3.html#path-option
204 parse_and_normalize_geojson_string(geojson),
207 return { interactive: false, color: 'blue' };
211 map.addLayer(geojson_layer);
212 map.fitBounds(geojson_layer.getBounds());
214 map.setView([lat, lon], 10);
217 var osm2 = new L.TileLayer(
218 get_config_value('Map_Tile_URL'),
222 attribution: (get_config_value('Map_Tile_Attribution') || null)
225 (new L.Control.MiniMap(osm2, { toggleDisplay: true })).addTo(map);
229 function details_page_load() {
231 var search_params = new URLSearchParams(window.location.search);
232 // var place_id = search_params.get('place_id');
234 var api_request_params = {
235 place_id: search_params.get('place_id'),
236 osmtype: search_params.get('osmtype'),
237 osmid: search_params.get('osmid'),
238 class: search_params.get('class'),
239 keywords: search_params.get('keywords'),
241 hierarchy: (search_params.get('hierarchy') === '1' ? 1 : 0),
247 if (api_request_params.place_id || (api_request_params.osmtype && api_request_params.osmid)) {
248 fetch_from_api('details', api_request_params, function (aFeature) {
249 var context = { aPlace: aFeature, base_url: window.location.search };
251 render_template($('main'), 'detailspage-template', context);
252 if (api_request_params.place_id) {
253 update_html_title('Details for ' + api_request_params.place_id);
255 update_html_title('Details for ' + api_request_params.osmtype + api_request_params.osmid);
260 var lat = aFeature.centroid.coordinates[1];
261 var lon = aFeature.centroid.coordinates[0];
262 init_map_on_detail_page(lat, lon, aFeature.geometry);
265 render_template($('main'), 'detailspage-index-template');
268 $('#form-by-type-and-id,#form-by-osm-url').on('submit', function (e) {
271 var val = $(this).find('input[type=edit]').val();
272 var matches = val.match(/^\s*([NWR])(\d+)\s*$/i);
275 matches = val.match(/\/(relation|way|node)\/(\d+)\s*$/);
279 $(this).find('input[name=osmtype]').val(matches[1].charAt(0).toUpperCase());
280 $(this).find('input[name=osmid]').val(matches[2]);
281 $(this).get(0).submit();
283 alert('invalid input');
288 // *********************************************************
289 // FORWARD/REVERSE SEARCH PAGE
290 // *********************************************************
293 function display_map_position(mouse_lat_lng) {
296 mouse_lat_lng = map.wrapLatLng(mouse_lat_lng);
299 var html_mouse = 'mouse position: -';
301 html_mouse = 'mouse position: '
302 + [mouse_lat_lng.lat.toFixed(5), mouse_lat_lng.lng.toFixed(5)].join(',');
304 var html_click = 'last click: -';
305 if (last_click_latlng) {
306 html_click = 'last click: '
307 + [last_click_latlng.lat.toFixed(5), last_click_latlng.lng.toFixed(5)].join(',');
310 var html_center = 'map center: '
311 + map.getCenter().lat.toFixed(5) + ',' + map.getCenter().lng.toFixed(5)
312 + ' <a target="_blank" href="' + map_link_to_osm() + '">view on osm.org</a>';
314 var html_zoom = 'map zoom: ' + map.getZoom();
315 var html_viewbox = 'viewbox: ' + map_viewbox_as_string();
317 $('#map-position-inner').html([
325 var center_lat_lng = map.wrapLatLng(map.getCenter());
326 var reverse_params = {
327 lat: center_lat_lng.lat.toFixed(5),
328 lon: center_lat_lng.lng.toFixed(5)
332 $('#switch-to-reverse').attr('href', 'reverse.html?' + $.param(reverse_params));
334 $('input#use_viewbox').trigger('change');
337 function init_map_on_search_page(is_reverse_search, nominatim_results, request_lat,
338 request_lon, init_zoom) {
340 var attribution = get_config_value('Map_Tile_Attribution') || null;
341 map = new L.map('map', {
342 // center: [nominatim_map_init.lat, nominatim_map_init.lon],
343 // zoom: nominatim_map_init.zoom,
344 attributionControl: (attribution && attribution.length),
345 scrollWheelZoom: true, // !L.Browser.touch,
350 L.tileLayer(get_config_value('Map_Tile_URL'), {
352 // '© <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
353 attribution: attribution
356 // console.log(Nominatim_Config);
358 map.setView([request_lat, request_lon], init_zoom);
360 var osm2 = new L.TileLayer(get_config_value('Map_Tile_URL'), {
363 attribution: attribution
365 new L.Control.MiniMap(osm2, { toggleDisplay: true }).addTo(map);
367 if (is_reverse_search) {
368 // We don't need a marker, but an L.circle instance changes radius once you zoom in/out
369 var cm = L.circleMarker(
370 [request_lat, request_lon],
374 fillColor: '#ff7800',
383 var search_params = new URLSearchParams(window.location.search);
384 var viewbox = search_params.get('viewbox');
386 var coords = viewbox.split(','); // <x1>,<y1>,<x2>,<y2>
387 var bounds = L.latLngBounds([coords[1], coords[0]], [coords[3], coords[2]]);
388 L.rectangle(bounds, {
398 var MapPositionControl = L.Control.extend({
402 onAdd: function (/* map */) {
403 var container = L.DomUtil.create('div', 'my-custom-control');
405 $(container).text('show map bounds')
406 .addClass('leaflet-bar btn btn-sm btn-outline-secondary')
407 .on('click', function (e) {
410 $('#map-position').show();
413 $('#map-position-close a').on('click', function (e) {
416 $('#map-position').hide();
424 map.addControl(new MapPositionControl());
430 function update_viewbox_field() {
432 $('input[name=viewbox]')
433 .val($('input#use_viewbox')
434 .prop('checked') ? map_viewbox_as_string() : '');
437 map.on('move', function () {
438 display_map_position();
439 update_viewbox_field();
442 map.on('mousemove', function (e) {
443 display_map_position(e.latlng);
446 map.on('click', function (e) {
447 last_click_latlng = e.latlng;
448 display_map_position();
451 map.on('load', function () {
452 display_map_position();
455 $('input#use_viewbox').on('change', function () {
456 update_viewbox_field();
459 function get_result_element(position) {
460 return $('.result').eq(position);
462 // function marker_for_result(result) {
463 // return L.marker([result.lat, result.lon], { riseOnHover: true, title: result.name });
465 function circle_for_result(result) {
469 fillColor: '#ff7800',
472 clickable: !is_reverse_search
474 return L.circleMarker([result.lat, result.lon], cm_style);
477 var layerGroup = (new L.layerGroup()).addTo(map);
479 function highlight_result(position, bool_focus) {
480 var result = nominatim_results[position];
481 if (!result) { return; }
482 var result_el = get_result_element(position);
484 $('.result').removeClass('highlight');
485 result_el.addClass('highlight');
487 layerGroup.clearLayers();
490 var circle = circle_for_result(result);
491 circle.on('click', function () {
492 highlight_result(position);
494 layerGroup.addLayer(circle);
497 if (result.boundingbox) {
499 [result.boundingbox[0] * 1, result.boundingbox[2] * 1],
500 [result.boundingbox[1] * 1, result.boundingbox[3] * 1]
504 if (result.geojson && result.geojson.type.match(/(Polygon)|(Line)/)) {
506 var geojson_layer = L.geoJson(
507 parse_and_normalize_geojson_string(result.geojson),
509 // https://leafletjs.com/reference-1.0.3.html#path-option
510 style: function (/* feature */) {
511 return { interactive: false, color: 'blue' };
515 layerGroup.addLayer(geojson_layer);
518 // var layer = L.rectangle(bounds, {color: "#ff7800", weight: 1} );
519 // layerGroup.addLayer(layer);
522 var result_coord = L.latLng(result.lat, result.lon);
524 if (is_reverse_search) {
525 // console.dir([result_coord, [request_lat, request_lon]]);
526 // make sure the search coordinates are in the map view as well
528 [result_coord, [request_lat, request_lon]],
531 maxZoom: map.getZoom()
535 map.panTo(result_coord, result.zoom || get_config_value('Map_Default_Zoom'));
545 $('.result').on('click', function () {
546 highlight_result($(this).data('position'), true);
549 if (is_reverse_search) {
550 map.on('click', function (e) {
551 $('form input[name=lat]').val(e.latlng.lat);
552 $('form input[name=lon]').val(e.latlng.wrap().lng);
556 $('#switch-coords').on('click', function (e) {
559 var lat = $('form input[name=lat]').val();
560 var lon = $('form input[name=lon]').val();
561 $('form input[name=lat]').val(lon);
562 $('form input[name=lon]').val(lat);
567 highlight_result(0, false);
569 // common mistake is to copy&paste latitude and longitude into the 'lat' search box
570 $('form input[name=lat]').on('change', function () {
571 var coords_split = $(this).val().split(',');
572 if (coords_split.length === 2) {
573 $(this).val(L.Util.trim(coords_split[0]));
574 $(this).siblings('input[name=lon]').val(L.Util.trim(coords_split[1]));
581 function search_page_load() {
583 var is_reverse_search = window.location.pathname.match(/reverse/);
585 var search_params = new URLSearchParams(window.location.search);
587 // return view('search', [
588 // 'sQuery' => $sQuery,
591 // 'aSearchResults' => $aSearchResults,
592 // 'sMoreURL' => 'example.com',
593 // 'sDataDate' => $this->fetch_status_date(),
597 var api_request_params;
600 if (is_reverse_search) {
601 api_request_params = {
602 lat: search_params.get('lat'),
603 lon: search_params.get('lon'),
604 zoom: (search_params.get('zoom') > 1
605 ? search_params.get('zoom')
606 : get_config_value('Reverse_Default_Search_Zoom')),
612 fLat: api_request_params.lat,
613 fLon: api_request_params.lon,
614 iZoom: (search_params.get('zoom') > 1
615 ? api_request_params.zoom
616 : get_config_value('Reverse_Default_Search_Zoom'))
620 if (api_request_params.lat && api_request_params.lon) {
622 fetch_from_api('reverse', api_request_params, function (aPlace) {
628 context.bSearchRan = true;
629 context.aPlace = aPlace;
631 render_template($('main'), 'reversepage-template', context);
632 update_html_title('Reverse result for '
633 + api_request_params.lat
635 + api_request_params.lon);
637 init_map_on_search_page(
640 api_request_params.lat,
641 api_request_params.lon,
642 api_request_params.zoom
648 render_template($('main'), 'reversepage-template', context);
650 init_map_on_search_page(
653 get_config_value('Map_Default_Lat'),
654 get_config_value('Map_Default_Lon'),
655 get_config_value('Map_Default_Zoom')
660 api_request_params = {
661 q: search_params.get('q'),
662 street: search_params.get('street'),
663 city: search_params.get('city'),
664 county: search_params.get('county'),
665 state: search_params.get('state'),
666 country: search_params.get('country'),
667 postalcode: search_params.get('postalcode'),
668 polygon_geojson: get_config_value('Search_AreaPolygons', false) ? 1 : 0,
669 viewbox: search_params.get('viewbox'),
670 exclude_place_ids: search_params.get('exclude_place_ids'),
675 sQuery: api_request_params.q,
676 sViewBox: search_params.get('viewbox'),
680 if (api_request_params.street || api_request_params.city || api_request_params.county
681 || api_request_params.state || api_request_params.country || api_request_params.postalcode) {
682 context.hStructured = {
683 street: api_request_params.street,
684 city: api_request_params.city,
685 county: api_request_params.county,
686 state: api_request_params.state,
687 country: api_request_params.country,
688 postalcode: api_request_params.postalcode
692 if (api_request_params.q || context.hStructured) {
694 fetch_from_api('search', api_request_params, function (aResults) {
696 context.bSearchRan = true;
697 context.aSearchResults = aResults;
699 // lonvia wrote: https://github.com/osm-search/nominatim-ui/issues/24
700 // I would suggest to remove the guessing and always show the link. Nominatim only returns
701 // one or two results when it believes the result to be a good enough match.
702 // if (aResults.length >= 10) {
703 var aExcludePlaceIds = [];
704 if (search_params.has('exclude_place_ids')) {
705 aExcludePlaceIds = search_params.get('exclude_place_ids').split(',');
707 for (var i = 0; i < aResults.length; i += 1) {
708 aExcludePlaceIds.push(aResults[i].place_id);
710 var parsed_url = new URLSearchParams(window.location.search);
711 parsed_url.set('exclude_place_ids', aExcludePlaceIds.join(','));
712 context.sMoreURL = '?' + parsed_url.toString();
714 render_template($('main'), 'searchpage-template', context);
715 update_html_title('Result for ' + api_request_params.q);
717 init_map_on_search_page(
720 get_config_value('Map_Default_Lat'),
721 get_config_value('Map_Default_Lon'),
722 get_config_value('Map_Default_Zoom')
730 render_template($('main'), 'searchpage-template', context);
732 init_map_on_search_page(
735 get_config_value('Map_Default_Lat'),
736 get_config_value('Map_Default_Lon'),
737 get_config_value('Map_Default_Zoom')
744 // *********************************************************
746 // *********************************************************
748 function deletable_page_load() {
750 var api_request_params = {
754 fetch_from_api('deletable', api_request_params, function (aPolygons) {
755 var context = { aPolygons: aPolygons };
757 render_template($('main'), 'deletable-template', context);
758 update_html_title('Deletable objects');
763 // *********************************************************
764 // BROKEN POLYGON PAGE
765 // *********************************************************
767 function polygons_page_load() {
769 var api_request_params = {
773 fetch_from_api('polygons', api_request_params, function (aPolygons) {
774 var context = { aPolygons: aPolygons };
776 render_template($('main'), 'polygons-template', context);
777 update_html_title('Broken polygons');
782 jQuery(document).ready(function () {
785 function parse_url_and_load_page() {
786 // 'search', 'reverse', 'details'
787 var pagename = window.location.pathname.replace('.html', '').replace(/^.*\//, '');
789 if (pagename === '') pagename = 'search';
791 $('body').attr('id', pagename + '-page');
793 if (pagename === 'search' || pagename === 'reverse') {
795 } else if (pagename === 'details') {
797 } else if (pagename === 'deletable') {
798 deletable_page_load();
799 } else if (pagename === 'polygons') {
800 polygons_page_load();
804 function is_relative_url(url) {
805 if (!url) return false;
806 if (url.indexOf('?') === 0) return true;
807 if (url.indexOf('/') === 0) return true;
808 if (url.indexOf('#') === 0) return false;
809 if (url.match(/^http/)) return false;
810 if (!url.match(/\.html/)) return true;
815 // remove any URL paramters with empty values
816 // '&empty=&filled=value' => 'filled=value'
817 function clean_up_url_parameters(url) {
818 var url_params = new URLSearchParams(url);
819 var to_delete = []; // deleting inside loop would skip iterations
820 url_params.forEach(function (value, key) {
821 if (value === '') to_delete.push(key);
823 for (var i = 0; i < to_delete.length; i += 1) {
824 url_params.delete(to_delete[i]);
826 return url_params.toString();
829 parse_url_and_load_page();
831 // load page after form submit
832 $(document).on('submit', 'form', function (e) {
835 var target_url = $(this).serialize();
836 target_url = clean_up_url_parameters(target_url);
838 window.history.pushState(myhistory, '', '?' + target_url);
840 parse_url_and_load_page();
843 // load page after click on relative URL
844 $(document).on('click', 'a', function (e) {
845 var target_url = $(this).attr('href');
846 if (!is_relative_url(target_url)) return;
847 if ($(this).parents('#last-updated').length !== 0) return;
852 window.history.pushState(myhistory, '', target_url);
854 parse_url_and_load_page();
857 // deal with back-button and other user action
858 window.onpopstate = function () {
859 parse_url_and_load_page();