You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
1.8 KiB

  1. const tabs = require('modulekit-tabs')
  2. const httpGet = require('./httpGet')
  3. require('./nominatim-search.css')
  4. let tab
  5. let input
  6. let domResults
  7. function show (data) {
  8. while(domResults.lastChild) {
  9. domResults.removeChild(domResults.lastChild)
  10. }
  11. data.forEach(
  12. entry => {
  13. let a = document.createElement('a')
  14. a.appendChild(document.createTextNode(entry.display_name))
  15. a.href = '#'
  16. a.onclick = () => {
  17. let bounds = new L.LatLngBounds(
  18. L.latLng(entry.boundingbox[0], entry.boundingbox[2]),
  19. L.latLng(entry.boundingbox[1], entry.boundingbox[3])
  20. )
  21. global.map.fitBounds(bounds, { animate: true })
  22. return false
  23. }
  24. let li = document.createElement('li')
  25. li.appendChild(a)
  26. domResults.appendChild(li)
  27. }
  28. )
  29. }
  30. function search (str) {
  31. httpGet(
  32. 'https://nominatim.openstreetmap.org/search?format=json&q=' + encodeURIComponent(str),
  33. {},
  34. (err, result) => {
  35. if (err) {
  36. return alert(err)
  37. }
  38. let data = JSON.parse(result.body)
  39. show(data)
  40. }
  41. )
  42. }
  43. register_hook('init', function () {
  44. tab = new tabs.Tab({
  45. id: 'search',
  46. weight: -1
  47. })
  48. tab.content.classList.add('nominatim-search')
  49. global.tabs.add(tab)
  50. tab.header.innerHTML = '<i class="fa fa-search" aria-hidden="true"></i>'
  51. tab.header.title = lang('search')
  52. let input = document.createElement('input')
  53. let inputTimer
  54. input.type = 'text'
  55. input.addEventListener('input', () => {
  56. if (inputTimer) {
  57. global.clearTimeout(inputTimer)
  58. }
  59. inputTimer = global.setTimeout(
  60. () => search(input.value),
  61. 300
  62. )
  63. })
  64. tab.content.appendChild(input)
  65. domResults = document.createElement('ul')
  66. tab.content.appendChild(domResults)
  67. tab.on('select', () => input.focus())
  68. })