openlayer3要比天地图灵活一些,但也更繁琐。
废话不多说,上代码:
<template>
<div>
<div ref="olMap" class="ol-map">
</div>
</div>
</template>
<script>
import "ol/ol.css";
import { Map, View, Feature, Overlay } from "ol";
import TileLayer from "ol/layer/Tile";
import VectorLayer from "ol/layer/Vector";
import XYZSource from "ol/source/XYZ";
import VectorSource from "ol/source/Vector";
import { Point, Polygon } from "ol/geom";
import { Style, Text, Fill, Stroke, Icon } from "ol/style";
// 引入行政区划的json数据文件
import bjs from '../../api/broadcast/610300_full.json'
export default {
data () {
return {
map: null
}
},
mounted () {
this.initMap()
this.addDivision()
this.addIcon(require('../../assets/images/logo.png'), 0.2, 107.090134, 34.434537)
this.addText('这是金台区中心位置', 107.090134, 34.434537)
},
methods: {
initMap () {
this.map = new Map({
layers: [
// 地图的底图
new TileLayer({
source: new XYZSource({
url: 'http://t0.tianditu.gov.cn/img_w/wmts?' +
'SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles' +
'&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=950317887aad3940b03bd591c0db8db9'
})
}),
],
view: new View({
projection: 'EPSG:4326',
center: [107.115498, 34.442182],
zoom: 12,
}),
target: this.$refs.olMap
})
},
/**
* 加载行政区域
*/
addDivision () {
// 定义矢量图层
let divisionLayer = new VectorLayer({
source: new VectorSource()
})
// 从610300_full.json文件中获取经纬度坐标构建多边形(Polygon参数是数组的数组)
let polygon = new Polygon(bjs.features[1].geometry.coordinates[0])
// 创建地理要素
let divisionFeature = new Feature({
geometry: polygon,
})
// 设置要素样式(填充和描边)
divisionFeature.setStyle(new Style({
fill: new Fill({
color: 'rgba(1,210,241,0.1)'
}),
stroke: new Stroke({
color: '#f00',
width: 3
})
}))
// 将要素添加到图层中
divisionLayer.getSource().addFeature(divisionFeature)
// 将矢量图层添加到地图中
this.map.addLayer(divisionLayer)
},
/**
* 加载图标
* @param {*} src 图标的url,必须使用require方式传入
* @param {*} scale 图标缩放比例
* @param {*} lng 经度
* @param {*} lat 纬度
*/
addIcon (src, scale, lng, lat) {
// 定义矢量图层
let iconLayer = new VectorLayer({
source: new VectorSource()
})
// 创建地理要素
let iconFeature = new Feature({
geometry: new Point([lng, lat]),
})
// 设置要素样式
iconFeature.setStyle(new Style({
image: new Icon({
src: src, // 传参时必须通过require来加载图片,否则不显示
scale: scale // 通过scale缩放图片,不能设置size
})
}))
iconLayer.getSource().addFeature(iconFeature)
// 将矢量图层添加到地图中
this.map.addLayer(iconLayer)
},
/**
* 加载文字
* @param {*} info
* @param {*} lng
* @param {*} lat
*/
addText (info, lng, lat) {
// 定义矢量图层
let textLayer = new VectorLayer({
source: new VectorSource()
})
// 创建地理要素
let textFeature = new Feature({
geometry: new Point([lng, lat]),
})
// 设置要素样式(填充和描边)
textFeature.setStyle(new Style({
text: new Text({
text: info,
font: '16px sans-serif',
fill: new Fill({
color: 'red'
}),
stroke: new Stroke({
color: '#fff',
width: 1
})
})
}))
// 将要素添加到图层中
textLayer.getSource().addFeature(textFeature)
// 将矢量图层添加到地图中
this.map.addLayer(textLayer)
}
}
}
</script>
<style>
.ol-map {
width: 100%;
height: 800px;
}
</style>
最终效果如下: