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.

84 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. })
  47. tab.content.classList.add('nominatim-search')
  48. global.tabs.add(tab)
  49. tab.header.innerHTML = '<i class="fa fa-search" aria-hidden="true"></i>'
  50. tab.header.title = lang('search')
  51. let input = document.createElement('input')
  52. let inputTimer
  53. input.type = 'text'
  54. input.addEventListener('input', () => {
  55. if (inputTimer) {
  56. global.clearTimeout(inputTimer)
  57. }
  58. inputTimer = global.setTimeout(
  59. () => search(input.value),
  60. 300
  61. )
  62. })
  63. tab.content.appendChild(input)
  64. domResults = document.createElement('ul')
  65. tab.content.appendChild(domResults)
  66. tab.on('select', () => input.focus())
  67. })