today_ai_weather/app/javascript/controllers/map_controller.js

61 lines
1.6 KiB
JavaScript
Raw Normal View History

import { Controller } from "@hotwired/stimulus"
import Map from 'ol/Map'
import View from 'ol/View'
import TileLayer from 'ol/layer/Tile'
import OSM from 'ol/source/OSM'
import { fromLonLat } from 'ol/proj'
import Feature from 'ol/Feature'
import Point from 'ol/geom/Point'
import { Vector as VectorLayer } from 'ol/layer'
import { Vector as VectorSource } from 'ol/source'
import { Style, Icon } from 'ol/style'
export default class extends Controller {
static values = {
latitude: Number,
longitude: Number
}
connect() {
this.initializeMap()
}
initializeMap() {
// 创建地图实例
const map = new Map({
target: this.element,
layers: [
new TileLayer({
source: new OSM()
})
],
view: new View({
center: fromLonLat([this.longitudeValue, this.latitudeValue]),
zoom: 4
})
})
// 添加标记点
const marker = new Feature({
geometry: new Point(fromLonLat([this.longitudeValue, this.latitudeValue]))
})
const vectorSource = new VectorSource({
features: [marker]
})
const vectorLayer = new VectorLayer({
source: vectorSource,
style: new Style({
image: new Icon({
anchor: [0.5, 1],
src: '/marker-icon.svg', // 确保在public目录下有这个图标
scale: 1.5
})
})
})
map.addLayer(vectorLayer)
}
}