先安装依赖 我是用的cnpm
cnpm install ol --save-dev
<div id="map" class="map"></div>
import 'ol/ol.css'
import Map from 'ol/Map'
import View from 'ol/View'
import {getCenter} from 'ol/extent'
import ImageLayer from 'ol/layer/Image'
import Projection from 'ol/proj/Projection'
import Static from 'ol/source/ImageStatic'
import Draw, {createBox} from 'ol/interaction/Draw'
import {Vector as VectorLayer} from 'ol/layer'
import {Vector as VectorSource} from 'ol/source'
extent: null,
map: null,
draw: null,
source: null,
imageLayer: null,
vector: null,
feature: null,
coordinate: [],
picturePath: '/symbol/fish1575335778547.jpg'
// 根据图片的大小去获取extent
let image = new Image()
image.src = this.api + this.picturePath
image.onload = () => {
this.extent = [0, 0, image.width, image.height]
// console.log(this.extent)
var projection = new Projection({
code: 'xkcd-image',
units: 'pixels',
extent: this.extent
})
this.source = new VectorSource({wrapX: false})
this.vector = new VectorLayer({
source: this.source
})
this.raster = new ImageLayer({
source: new Static({
url: 'https://imgs.xkcd.com/comics/online_communities.png',
projection: projection,
imageExtent: this.extent
})
})
this.map = new Map({
layers: [
this.raster,
this.vector
],
target: 'map',
view: new View({
projection: projection,
center: getCenter(this.extent),
zoom: 1,
maxZoom: 8
// extent: this.extent
})
})
}
addDrawInteraction () {
this.draw = new Draw({
source: this.source,
type: 'Circle',
geometryFunction: createBox()
})
this.draw.on('drawend', (e) => {
console.log(e.feature.getGeometry().extent_)
this.feature = e.feature
this.map.removeInteraction(this.draw) // 取消连续画框的操作
})
this.map.addInteraction(this.draw)
},
// 点击添加的时候再在图上画框
add () {
if (this.feature) {
this.source.removeFeature(this.feature) // 删除之前标记的内容
}
this.addDrawInteraction()
}