vue使用OpenLayers初始化vectorLayer
时间: 2024-03-10 17:40:20 浏览: 89
以下是使用Vue和OpenLayers初始化VectorLayer的示例代码:
```vue
<template>
<div id="map"></div>
</template>
<script>
import 'ol/ol.css';
import { Map, View } from 'ol';
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer';
import { OSM, Vector as VectorSource } from 'ol/source';
import { fromLonLat } from 'ol/proj';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import { Icon, Style } from 'ol/style';
export default {
name: 'Map',
mounted() {
const map = new Map({
target: 'map',
layers: [
new TileLayer({
source: new OSM(),
}),
],
view: new View({
center: fromLonLat([0, 0]),
zoom: 2,
}),
});
const pointLayer = new VectorLayer({
source: new VectorSource(),
});
map.addLayer(pointLayer);
const coordinates = [
[0, 0], [10, 10],
[20, 20],
];
const featuresArr = [];
coordinates.forEach((coordinate) => {
const feature = new Feature({
geometry: new Point(fromLonLat(coordinate)),
});
feature.setStyle(
new Style({
image: new Icon({
src: 'https://openlayers.org/en/latest/examples/data/icon.png',
}),
})
);
featuresArr.push(feature);
});
pointLayer.getSource().addFeatures(featuresArr);
},
};
</script>
<style>
#map {
height: 400px;
}
</style>
```
上述代码中,我们首先在Vue组件中引入了OpenLayers相关的模块,然后在mounted钩子函数中初始化了一个地图,并添加了一个OSM图层。接着,我们创建了一个VectorLayer矢量图层,并将其添加到地图中。然后,我们定义了一组经纬度坐标数据,并循环遍历这些坐标数据,创建了一个点要素Feature,并设置了其样式。最后,我们将所有的要素信息添加到了pointLayer图层的数据源中。
阅读全文