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 fetch_from_api(endpoint_name, params, callback) {
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?'
96 if (endpoint_name !== 'status') {
97 $('#api-request-link').attr('href', api_url);
99 $.get(api_url, function (data) {
104 function update_data_date() {
105 fetch_from_api('status', { format: 'json' }, function (data) {
106 $('#data-date').text(data.data_updated);
110 function render_template(el, template_name, page_context) {
111 var template_source = $('#' + template_name).text();
112 var template = Handlebars.compile(template_source);
113 var html = template(page_context);
117 function update_html_title(title) {
119 if (title && title.length > 1) {
120 prefix = title + ' | ';
122 $('head title').text(prefix + 'OpenStreetMap Nominatim');
125 function show_error(html) {
126 $('#error-overlay').html(html).show();
129 function hide_error() {
130 $('#error-overlay').empty().hide();
134 jQuery(document).ready(function () {
137 $(document).ajaxStart(function () {
138 $('#loading').fadeIn('fast');
139 }).ajaxComplete(function () {
140 $('#loading').fadeOut('fast');
141 }).ajaxError(function (event, jqXHR, ajaxSettings/* , thrownError */) {
142 // console.log(thrownError);
143 // console.log(ajaxSettings);
144 var url = ajaxSettings.url;
145 show_error('Error fetching results from <a href="' + url + '">' + url + '</a>');
148 // *********************************************************
150 // *********************************************************
153 function init_map_on_detail_page(lat, lon, geojson) {
154 var attribution = get_config_value('Map_Tile_Attribution') || null;
155 map = new L.map('map', {
156 // center: [nominatim_map_init.lat, nominatim_map_init.lon],
157 // zoom: nominatim_map_init.zoom,
158 attributionControl: (attribution && attribution.length),
159 scrollWheelZoom: true, // !L.Browser.touch,
163 L.tileLayer(get_config_value('Map_Tile_URL'), {
165 // '© <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
166 attribution: attribution
169 // var layerGroup = new L.layerGroup().addTo(map);
171 var circle = L.circleMarker([lat, lon], {
172 radius: 10, weight: 2, fillColor: '#ff7800', color: 'blue', opacity: 0.75
174 map.addLayer(circle);
177 var geojson_layer = L.geoJson(
178 // https://leafletjs.com/reference-1.0.3.html#path-option
179 parse_and_normalize_geojson_string(geojson),
182 return { interactive: false, color: 'blue' };
186 map.addLayer(geojson_layer);
187 map.fitBounds(geojson_layer.getBounds());
189 map.setView([lat, lon], 10);
192 var osm2 = new L.TileLayer(
193 get_config_value('Map_Tile_URL'),
197 attribution: (get_config_value('Map_Tile_Attribution') || null)
200 (new L.Control.MiniMap(osm2, { toggleDisplay: true })).addTo(map);
204 function details_page_load() {
206 var search_params = new URLSearchParams(window.location.search);
207 // var place_id = search_params.get('place_id');
209 var api_request_params = {
210 place_id: search_params.get('place_id'),
211 osmtype: search_params.get('osmtype'),
212 osmid: search_params.get('osmid'),
213 keywords: search_params.get('keywords'),
215 hierarchy: (search_params.get('hierarchy') === '1' ? 1 : 0),
221 if (api_request_params.place_id || (api_request_params.osmtype && api_request_params.osmid)) {
222 fetch_from_api('details', api_request_params, function (aFeature) {
223 var context = { aPlace: aFeature, base_url: window.location.search };
225 render_template($('main'), 'detailspage-template', context);
226 if (api_request_params.place_id) {
227 update_html_title('Details for ' + api_request_params.place_id);
229 update_html_title('Details for ' + api_request_params.osmtype + api_request_params.osmid);
234 var lat = aFeature.centroid.coordinates[1];
235 var lon = aFeature.centroid.coordinates[0];
236 init_map_on_detail_page(lat, lon, aFeature.geometry);
239 render_template($('main'), 'detailspage-index-template');
242 $('#form-by-type-and-id,#form-by-osm-url').on('submit', function (e) {
245 var val = $(this).find('input[type=edit]').val();
246 var matches = val.match(/^\s*([NWR])(\d+)\s*$/i);
249 matches = val.match(/\/(relation|way|node)\/(\d+)\s*$/);
253 $(this).find('input[name=osmtype]').val(matches[1].charAt(0).toUpperCase());
254 $(this).find('input[name=osmid]').val(matches[2]);
255 $(this).get(0).submit();
257 alert('invalid input');
262 // *********************************************************
263 // FORWARD/REVERSE SEARCH PAGE
264 // *********************************************************
267 function display_map_position(mouse_lat_lng) {
270 mouse_lat_lng = map.wrapLatLng(mouse_lat_lng);
273 var html_mouse = 'mouse position: -';
275 html_mouse = 'mouse position: '
276 + [mouse_lat_lng.lat.toFixed(5), mouse_lat_lng.lng.toFixed(5)].join(',');
278 var html_click = 'last click: -';
279 if (last_click_latlng) {
280 html_click = 'last click: '
281 + [last_click_latlng.lat.toFixed(5), last_click_latlng.lng.toFixed(5)].join(',');
284 var html_center = 'map center: '
285 + map.getCenter().lat.toFixed(5) + ',' + map.getCenter().lng.toFixed(5)
286 + ' <a target="_blank" href="' + map_link_to_osm() + '">view on osm.org</a>';
288 var html_zoom = 'map zoom: ' + map.getZoom();
289 var html_viewbox = 'viewbox: ' + map_viewbox_as_string();
291 $('#map-position-inner').html([
299 var center_lat_lng = map.wrapLatLng(map.getCenter());
300 var reverse_params = {
301 lat: center_lat_lng.lat.toFixed(5),
302 lon: center_lat_lng.lng.toFixed(5)
306 $('#switch-to-reverse').attr('href', 'reverse.html?' + $.param(reverse_params));
308 $('input#use_viewbox').trigger('change');
311 function init_map_on_search_page(is_reverse_search, nominatim_results, request_lat,
312 request_lon, init_zoom) {
314 var attribution = get_config_value('Map_Tile_Attribution') || null;
315 map = new L.map('map', {
316 // center: [nominatim_map_init.lat, nominatim_map_init.lon],
317 // zoom: nominatim_map_init.zoom,
318 attributionControl: (attribution && attribution.length),
319 scrollWheelZoom: true, // !L.Browser.touch,
324 L.tileLayer(get_config_value('Map_Tile_URL'), {
326 // '© <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
327 attribution: attribution
330 // console.log(Nominatim_Config);
332 map.setView([request_lat, request_lon], init_zoom);
334 var osm2 = new L.TileLayer(get_config_value('Map_Tile_URL'), {
337 attribution: attribution
339 new L.Control.MiniMap(osm2, { toggleDisplay: true }).addTo(map);
341 if (is_reverse_search) {
342 // We don't need a marker, but an L.circle instance changes radius once you zoom in/out
343 var cm = L.circleMarker(
344 [request_lat, request_lon],
348 fillColor: '#ff7800',
357 var search_params = new URLSearchParams(window.location.search);
358 var viewbox = search_params.get('viewbox');
360 var coords = viewbox.split(','); // <x1>,<y1>,<x2>,<y2>
361 var bounds = L.latLngBounds([coords[1], coords[0]], [coords[3], coords[2]]);
362 L.rectangle(bounds, {
372 var MapPositionControl = L.Control.extend({
376 onAdd: function (/* map */) {
377 var container = L.DomUtil.create('div', 'my-custom-control');
379 $(container).text('show map bounds')
380 .addClass('leaflet-bar btn btn-sm btn-outline-secondary')
381 .on('click', function (e) {
384 $('#map-position').show();
387 $('#map-position-close a').on('click', function (e) {
390 $('#map-position').hide();
398 map.addControl(new MapPositionControl());
404 function update_viewbox_field() {
406 $('input[name=viewbox]')
407 .val($('input#use_viewbox')
408 .prop('checked') ? map_viewbox_as_string() : '');
411 map.on('move', function () {
412 display_map_position();
413 update_viewbox_field();
416 map.on('mousemove', function (e) {
417 display_map_position(e.latlng);
420 map.on('click', function (e) {
421 last_click_latlng = e.latlng;
422 display_map_position();
425 map.on('load', function () {
426 display_map_position();
429 $('input#use_viewbox').on('change', function () {
430 update_viewbox_field();
433 function get_result_element(position) {
434 return $('.result').eq(position);
436 // function marker_for_result(result) {
437 // return L.marker([result.lat, result.lon], { riseOnHover: true, title: result.name });
439 function circle_for_result(result) {
443 fillColor: '#ff7800',
446 clickable: !is_reverse_search
448 return L.circleMarker([result.lat, result.lon], cm_style);
451 var layerGroup = (new L.layerGroup()).addTo(map);
453 function highlight_result(position, bool_focus) {
454 var result = nominatim_results[position];
455 if (!result) { return; }
456 var result_el = get_result_element(position);
458 $('.result').removeClass('highlight');
459 result_el.addClass('highlight');
461 layerGroup.clearLayers();
464 var circle = circle_for_result(result);
465 circle.on('click', function () {
466 highlight_result(position);
468 layerGroup.addLayer(circle);
471 if (result.boundingbox) {
473 [result.boundingbox[0] * 1, result.boundingbox[2] * 1],
474 [result.boundingbox[1] * 1, result.boundingbox[3] * 1]
478 if (result.geojson && result.geojson.type.match(/(Polygon)|(Line)/)) {
480 var geojson_layer = L.geoJson(
481 parse_and_normalize_geojson_string(result.geojson),
483 // https://leafletjs.com/reference-1.0.3.html#path-option
484 style: function (/* feature */) {
485 return { interactive: false, color: 'blue' };
489 layerGroup.addLayer(geojson_layer);
492 // var layer = L.rectangle(bounds, {color: "#ff7800", weight: 1} );
493 // layerGroup.addLayer(layer);
496 var result_coord = L.latLng(result.lat, result.lon);
498 if (is_reverse_search) {
499 // console.dir([result_coord, [request_lat, request_lon]]);
500 // make sure the search coordinates are in the map view as well
502 [result_coord, [request_lat, request_lon]],
505 maxZoom: map.getZoom()
509 map.panTo(result_coord, result.zoom || get_config_value('Map_Default_Zoom'));
519 $('.result').on('click', function () {
520 highlight_result($(this).data('position'), true);
523 if (is_reverse_search) {
524 map.on('click', function (e) {
525 $('form input[name=lat]').val(e.latlng.lat);
526 $('form input[name=lon]').val(e.latlng.wrap().lng);
530 $('#switch-coords').on('click', function (e) {
533 var lat = $('form input[name=lat]').val();
534 var lon = $('form input[name=lon]').val();
535 $('form input[name=lat]').val(lon);
536 $('form input[name=lon]').val(lat);
541 highlight_result(0, false);
543 // common mistake is to copy&paste latitude and longitude into the 'lat' search box
544 $('form input[name=lat]').on('change', function () {
545 var coords_split = $(this).val().split(',');
546 if (coords_split.length === 2) {
547 $(this).val(L.Util.trim(coords_split[0]));
548 $(this).siblings('input[name=lon]').val(L.Util.trim(coords_split[1]));
555 function search_page_load() {
557 var is_reverse_search = window.location.pathname.match(/reverse/);
559 var search_params = new URLSearchParams(window.location.search);
561 // return view('search', [
562 // 'sQuery' => $sQuery,
565 // 'aSearchResults' => $aSearchResults,
566 // 'sMoreURL' => 'example.com',
567 // 'sDataDate' => $this->fetch_status_date(),
571 var api_request_params;
574 if (is_reverse_search) {
575 api_request_params = {
576 lat: search_params.get('lat'),
577 lon: search_params.get('lon'),
578 zoom: (search_params.get('zoom') > 1
579 ? search_params.get('zoom')
580 : get_config_value('Reverse_Default_Search_Zoom')),
586 fLat: api_request_params.lat,
587 fLon: api_request_params.lon,
588 iZoom: (search_params.get('zoom') > 1
589 ? api_request_params.zoom
590 : get_config_value('Reverse_Default_Search_Zoom'))
594 if (api_request_params.lat && api_request_params.lon) {
596 fetch_from_api('reverse', api_request_params, function (aPlace) {
602 context.aPlace = aPlace;
604 render_template($('main'), 'reversepage-template', context);
605 update_html_title('Reverse result for '
606 + api_request_params.lat
608 + api_request_params.lon);
610 init_map_on_search_page(
613 api_request_params.lat,
614 api_request_params.lon,
615 api_request_params.zoom
621 render_template($('main'), 'reversepage-template', context);
623 init_map_on_search_page(
626 get_config_value('Map_Default_Lat'),
627 get_config_value('Map_Default_Lon'),
628 get_config_value('Map_Default_Zoom')
633 api_request_params = {
634 q: search_params.get('q'),
635 street: search_params.get('street'),
636 city: search_params.get('city'),
637 county: search_params.get('county'),
638 state: search_params.get('state'),
639 country: search_params.get('country'),
640 postalcode: search_params.get('postalcode'),
641 polygon_geojson: get_config_value('Search_AreaPolygons', false) ? 1 : 0,
642 viewbox: search_params.get('viewbox'),
643 exclude_place_ids: search_params.get('exclude_place_ids'),
648 sQuery: api_request_params.q,
649 sViewBox: search_params.get('viewbox'),
653 if (api_request_params.street || api_request_params.city || api_request_params.county
654 || api_request_params.state || api_request_params.country || api_request_params.postalcode) {
655 context.hStructured = {
656 street: api_request_params.street,
657 city: api_request_params.city,
658 county: api_request_params.county,
659 state: api_request_params.state,
660 country: api_request_params.country,
661 postalcode: api_request_params.postalcode
665 if (api_request_params.q || context.hStructured) {
667 fetch_from_api('search', api_request_params, function (aResults) {
669 context.aSearchResults = aResults;
671 if (aResults.length >= 10) {
672 var aExcludePlaceIds = [];
673 if (search_params.has('exclude_place_ids')) {
674 aExcludePlaceIds = search_params.get('exclude_place_ids').split(',');
676 for (var i = 0; i < aResults.length; i += 1) {
677 aExcludePlaceIds.push(aResults[i].place_id);
680 var parsed_url = new URLSearchParams(window.location.search);
681 parsed_url.set('exclude_place_ids', aExcludePlaceIds.join(','));
682 context.sMoreURL = '?' + parsed_url.toString();
685 render_template($('main'), 'searchpage-template', context);
686 update_html_title('Result for ' + api_request_params.q);
688 init_map_on_search_page(
691 get_config_value('Map_Default_Lat'),
692 get_config_value('Map_Default_Lon'),
693 get_config_value('Map_Default_Zoom')
701 render_template($('main'), 'searchpage-template', context);
703 init_map_on_search_page(
706 get_config_value('Map_Default_Lat'),
707 get_config_value('Map_Default_Lon'),
708 get_config_value('Map_Default_Zoom')
715 // *********************************************************
717 // *********************************************************
719 function deletable_page_load() {
721 var api_request_params = {
725 fetch_from_api('deletable', api_request_params, function (aPolygons) {
726 var context = { aPolygons: aPolygons };
728 render_template($('main'), 'deletable-template', context);
729 update_html_title('Deletable objects');
734 // *********************************************************
735 // BROKEN POLYGON PAGE
736 // *********************************************************
738 function polygons_page_load() {
740 var api_request_params = {
744 fetch_from_api('polygons', api_request_params, function (aPolygons) {
745 var context = { aPolygons: aPolygons };
747 render_template($('main'), 'polygons-template', context);
748 update_html_title('Broken polygons');
753 jQuery(document).ready(function () {
756 function parse_url_and_load_page() {
757 // 'search', 'reverse', 'details'
758 var pagename = window.location.pathname.replace('.html', '').replace(/^\//, '');
760 $('body').attr('id', pagename + '-page');
762 if (pagename === 'search' || pagename === 'reverse') {
764 } else if (pagename === 'details') {
766 } else if (pagename === 'deletable') {
767 deletable_page_load();
768 } else if (pagename === 'polygons') {
769 polygons_page_load();
773 function is_relative_url(url) {
774 if (!url) return false;
775 if (url.indexOf('?') === 0) return true;
776 if (url.indexOf('/') === 0) return true;
777 if (url.indexOf('#') === 0) return false;
778 if (url.match(/^http/)) return false;
779 if (!url.match(/\.html/)) return true;
784 // remove any URL paramters with empty values
785 // '&empty=&filled=value' => 'filled=value'
786 function clean_up_url_parameters(url) {
787 var url_params = new URLSearchParams(url);
788 var to_delete = []; // deleting inside loop would skip iterations
789 url_params.forEach(function (value, key) {
790 if (value === '') to_delete.push(key);
792 for (var i=0; i<to_delete.length; i++) {
793 url_params.delete(to_delete[i]);
795 return url_params.toString();
798 parse_url_and_load_page();
800 // load page after form submit
801 $(document).on('submit', 'form', function (e) {
804 var target_url = $(this).serialize();
805 target_url = clean_up_url_parameters(target_url);
807 window.history.pushState(myhistory, '', '?' + target_url);
809 parse_url_and_load_page();
812 // load page after click on relative URL
813 $(document).on('click', 'a', function (e) {
814 var target_url = $(this).attr('href');
815 if (!is_relative_url(target_url)) return;
820 window.history.pushState(myhistory, '', target_url);
822 parse_url_and_load_page();
825 // deal with back-button and other user action
826 window.onpopstate = function () {
827 parse_url_and_load_page();