58 lines
1.6 KiB
JavaScript
58 lines
1.6 KiB
JavaScript
|
import { Controller } from "@hotwired/stimulus"
|
||
|
import L from 'leaflet'
|
||
|
|
||
|
import 'leaflet/dist/leaflet.css'
|
||
|
import iconUrl from 'leaflet/dist/images/marker-icon.png';
|
||
|
import iconRetinaUrl from 'leaflet/dist/images/marker-icon-2x.png';
|
||
|
// import iconRetinaUrl from '../images/leaflet/marker-icon-2x.png';
|
||
|
import shadowUrl from 'leaflet/dist/images/marker-shadow.png';
|
||
|
|
||
|
export default class extends Controller {
|
||
|
static values = {
|
||
|
latitude: Number,
|
||
|
longitude: Number
|
||
|
}
|
||
|
|
||
|
init() {
|
||
|
}
|
||
|
|
||
|
connect() {
|
||
|
|
||
|
delete L.Icon.Default.prototype._getIconUrl
|
||
|
L.Icon.Default.mergeOptions({
|
||
|
// iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
|
||
|
// iconUrl: require('leaflet/dist/images/marker-icon.png'),
|
||
|
// shadowUrl: require('leaflet/dist/images/marker-shadow.png')
|
||
|
iconRetinaUrl: iconRetinaUrl,
|
||
|
iconUrl: iconUrl,
|
||
|
shadowUrl: shadowUrl,
|
||
|
});
|
||
|
|
||
|
this.initializeMap()
|
||
|
}
|
||
|
|
||
|
initializeMap() {
|
||
|
// 创建地图实例
|
||
|
this.map = L.map(this.element).setView(
|
||
|
[this.latitudeValue, this.longitudeValue],
|
||
|
4 // 缩放级别
|
||
|
)
|
||
|
|
||
|
// 添加地图图层
|
||
|
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
|
||
|
attribution: '© OpenStreetMap contributors'
|
||
|
}).addTo(this.map)
|
||
|
|
||
|
// 添加标记
|
||
|
L.marker([this.latitudeValue, this.longitudeValue])
|
||
|
.addTo(this.map)
|
||
|
.bindPopup(document.querySelector('h1').textContent)
|
||
|
.openPopup()
|
||
|
}
|
||
|
|
||
|
disconnect() {
|
||
|
if (this.map) {
|
||
|
this.map.remove()
|
||
|
}
|
||
|
}
|
||
|
}
|