today_ai_weather/app/javascript/controllers/map_controller.js

72 lines
2.3 KiB
JavaScript
Raw Normal View History

import { Controller } from "@hotwired/stimulus"
import mapboxgl from 'mapbox-gl'
import 'mapbox-gl/dist/mapbox-gl.css';
export default class extends Controller {
static values = {
latitude: Number,
longitude: Number,
zoom: { type: Number, default: 6 },
weatherArt: Object,
weatherArtUrl: String,
token: String
}
connect() {
mapboxgl.accessToken = this.tokenValue
this.map = new mapboxgl.Map({
container: this.element,
style: 'mapbox://styles/mapbox/satellite-streets-v12',
// projection: 'globe', // 启用 3D 地球模式
center: [this.longitudeValue, this.latitudeValue],
zoom: this.zoomValue
});
this.map.on('style.load', () => {
// 设置地球效果
this.map.setFog({
'color': 'rgb(186, 210, 235)',
'high-color': 'rgb(36, 92, 223)',
'horizon-blend': 0.02
});
});
// 添加标记
// const marker = new mapboxgl.Marker({
// color: "#FF6B6B",
// scale: 1.2
// })
// .setLngLat([this.longitudeValue, this.latitudeValue])
// .addTo(this.map);
const marker = new mapboxgl.Marker()
.setLngLat([this.longitudeValue, this.latitudeValue])
.addTo(this.map);
// marker.getElement().addEventListener('click', () => {
// this.showPopup();
// });
// 默认弹出窗口
// this.showPopup();
// 添加缩放控件
this.map.addControl(new mapboxgl.NavigationControl());
}
showPopup() {
console.log("weatherArtValue: ", this.weatherArtValue)
const popupContent = `
<div class="p-4 bg-white rounded-lg shadow-lg">
<img src="${this.weatherArtUrlValue}" alt="${this.weatherArtValue.description}" class="w-full h-auto rounded-md mb-2" />
<p class="text-sm text-gray-600">${this.weatherArtValue.description}</p>
<a href="/weather_arts/${this.weatherArtValue.id}" class="btn btn-primary mt-2">查看详情</a>
</div>
`;
const popup = new mapboxgl.Popup()
.setLngLat([this.longitudeValue, this.latitudeValue])
.setHTML(popupContent)
.addTo(this.map);
}
}