前提配置

假设你已经初始化vue项目

1
npm install ol  

创建容器,记得设置宽高

1
<div id="map"></div>

按需引入openlayers

1
2
3
4
5
import Map from'ol/Map';
import View from 'ol/View';
import XYZ from 'ol/source/XYZ';
import { Tile as TileLayer} from 'ol/layer';
import {fromLonLat,transform} from "ol/proj";

初始化地图

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
let baseLayer = new TileLayer({
                visible: true,
                name: "电子图",
                source: new XYZ({
                    url: 'https://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}',
                    crossOrigin: "anonymous",
                }),
            });
    this.map = new Map({
                target: 'map',
                layers: [baseLayer],
                view: new View({
                    center: fromLonLat([113.56762000, 34.82407000]),
                    zoom: 16
                })
            });

至此,就可以愉快的玩耍openlayers啦。

以下是整体代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<template>
    <div>
        <div id="map">
        </div>
    </div>
</template>

<script>
import Map from 'ol/Map';
import View from 'ol/View';
import XYZ from 'ol/source/XYZ';
import { Tile as TileLayer} from 'ol/layer';
import {fromLonLat,transform} from "ol/proj";
export default {
    name: 'HelloWorld',
    data() {
        return {
            map: null,

        }
    },
    mounted() {

        this.init();
    },
    methods: {
        init() {
            let baseLayer = new TileLayer({
                visible: true,
                name: "电子图",
                source: new XYZ({
                    url: 'https://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}',
                    crossOrigin: "anonymous",
                }),
            });
            this.map = new Map({
                target: 'map',
                layers: [baseLayer],
                view: new View({
                    center: fromLonLat([113.56762000, 34.82407000]),
                    zoom: 16
                })
            });


        }
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#map {
    width: 1920px;
    height: 1080px;
}
</style>