这里是关于一个根据下拉框的选项在地图上显示图标的需求,用的是vue+openlayers
显示效果大概是这样:
选中选项之后会跳转到所点击的城市,并且在地图上显示图标+温度,这一块UI没设计我就大概先弄了一下,比较丑。。
首先放一个层
<div id="weatherInfo"></div>
//下面是遮盖物的div
<div id="temperatureOverlay" ></div>
接下来是js部分,首先创建一个地图,我这里使用的是本地静态切片。
const center = ol.proj.transform([112, 38.42], 'EPSG:4326', 'EPSG:3857');
const map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'satellite/{z}/{x}/{y}.jpg'
}),
isGroup: true,
}),
new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'overlay/{z}/{x}/{y}.png'
}),
isGroup: true,
name: '天地图文字标注'
}),
],
view: new ol.View({
center: center,
zoom:4
})
})
接下来是用本地的数据生成下拉框选项,以及绘制/创建天气text覆盖物
//创建天气列表
const cityWeatherData = [
{
city: '北京',
temperature: 25,
icon: 'icon/sun.png',
coordinates: [116.4074, 39.9042]
},
{
city: '上海',
temperature: 28,
icon: 'icon/sun.png',
coordinates: [121.4737, 31.2304]
},
// 其他城市的天气数据
];
const citySelect = document.getElementById('citySelect');
const iconLayer = new ol.layer.Vector({
source: new ol.source.Vector()
});
map.addLayer(iconLayer);
cityWeatherData.forEach(function(data) {
const option = document.createElement('option');
option.value = data.city;
option.textContent = data.city;
citySelect.appendChild(option);
});
const weatherInfo = document.getElementById('weatherInfo');
citySelect.addEventListener('change', function() {
const selectedCity = citySelect.value;
const selectedWeatherData = cityWeatherData.find(function(data) {
return data.city === selectedCity;
});
iconLayer.getSource().clear();
if (selectedWeatherData) {
const iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat(selectedWeatherData.coordinates)),
name: selectedWeatherData.city,
temperature: selectedWeatherData.temperature,
icon: selectedWeatherData.icon
});
const iconStyle = new ol.style.Style({
image: new ol.style.Icon({
src: selectedWeatherData.icon,
scale: 0.5
})
});
iconFeature.setStyle(iconStyle);
iconLayer.getSource().addFeature(iconFeature);
map.getView().animate({
center: ol.proj.fromLonLat(selectedWeatherData.coordinates),
zoom: 10
});
} else {
iconLayer.getSource().clear();
map.getView().animate({
center: ol.proj.fromLonLat([0, 0]),
zoom: 2
});
}
});
// 创建天气温度覆盖物
const temperatureOverlay = new ol.Overlay({
element: document.getElementById('temperatureOverlay'),
positioning: 'bottom-center',
offset: [0, -10],
stopEvent: false // 允许覆盖物接收事件
});
map.addOverlay(temperatureOverlay);
// 在城市选择事件中更新天气温度覆盖物
citySelect.addEventListener('change', function() {
const selectedCity = citySelect.value;
const selectedWeatherData = cityWeatherData.find(function(data) {
return data.city === selectedCity;
});
if (selectedWeatherData) {
// 更新覆盖物内容
const temperatureElement = temperatureOverlay.getElement();
temperatureElement.innerHTML = selectedWeatherData.temperature + '°C';
// 更新覆盖物位置
temperatureOverlay.setPosition(ol.proj.fromLonLat(selectedWeatherData.coordinates));
} else {
// 隐藏覆盖物
temperatureOverlay.setPosition(undefined);
}
});