File size: 2,276 Bytes
d4648ea
 
 
 
 
 
 
 
 
814d2b2
d4648ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
814d2b2
d4648ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
814d2b2
d4648ea
814d2b2
d4648ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const loadJs = require('licia/loadJs')

module.exports = function (eruda) {
  const { evalCss } = eruda.util

  class Geolocation extends eruda.Tool {
    constructor() {
      super()
      this.name = 'geolocation'
      this.displayName = '地理位置情報'
      this._style = evalCss(require('./style.scss'))
    }
    init($el, container) {
      super.init($el, container)
      $el.html(
        '<div id="eruda-map" class="eruda-map"></div><div class="eruda-info"></div>'
      )

      this._initMap()
      this._$info = this._$el.find('.eruda-info')
    }
    show() {
      super.show()

      this.resetView()
    }
    resetView() {
      if (!navigator.geolocation) return

      navigator.geolocation.getCurrentPosition(
        (position) => {
          var coords = position.coords,
            longitude = coords.longitude,
            latitude = coords.latitude

          this.setView(latitude, longitude)
        },
        (e) => {
          this.setInfo(e.message)
        }
      )
    }
    setView(latitude, longitude) {
      if (!this._map) return

      this._map.setView([latitude, longitude], 12)

      this.setInfo('緯度: ' + latitude + ' 経度: ' + longitude)
    }
    setInfo(text) {
      this._$info.text(text)
    }
    hide() {
      super.hide()
    }
    destroy() {
      super.destroy()
      evalCss.remove(this._style)
    }
    _initMap() {
      loadCss(
        'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css',
        this._$el.get(0)
      )
      loadJs('https://unpkg.com/leaflet@1.9.4/dist/leaflet.js', (isLoaded) => {
        if (!isLoaded) return this.setInfo('地図の初期化に失敗しました')

        this.setInfo('地図の初期化に成功しました')

        this._map = L.map(this._$el.find('#eruda-map').get(0), {
          center: [39.9, 116.39],
          zoom: 2,
        })
        L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {}).addTo(
          this._map
        )

        this.resetView()
      })
    }
  }

  return new Geolocation()
}

function loadCss(src, container) {
  const link = document.createElement('link')

  link.rel = 'stylesheet'
  link.type = 'text/css'
  link.href = src

  container = container || document.head
  container.appendChild(link)
}