设计目标
利用Vue的特性,结合Openlayers 5搭建一个单页地图应用。布局草图如图1所示,页面的主体为地图,在地图上添加查询框、工具栏、信息栏等内容。
图1 布局草图
创建项目
安装Vue CLI 3
npm install -g @vue/cli
创建Vue项目,可以使用命令行创建,并在其中配置插件、依赖等
vue create hi-story
也可以使用GUI创建,按照提示来即可
vue ui
修改文档结构
创建后的文档结构如图2所示,主要的代码位于/src
文件夹中,该文件夹的格式如图3所示
图2 文档结构
图3 src文件夹结构
由于主体只有一个地图,功能全都体现在地图上的对话框,不需要使用多页面跳转的功能,因此可以放弃vue-router
,使用模块化开发,搭建地图。首先将App.vue
文件改名为HiMap.vue
,然后删掉/views
、/components/HelloWorld.vue
、router.js
,在/src/components
中添加名为MainMap.vue
的文件。修改后的/src
文件夹结构如图4所示。
图4 修改后的文件夹结构
修改代码
详细内容如代码所示。
main.js
import Vue from 'vue'
import HiMap from './HiMap.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
store,
render: function (h) { return h(HiMap) }
}).$mount('#app')
HiMap.vue
<template>
<div id="app">
<main-map></main-map>
</div>
</template>
<script>
// Map
import MainMap from './components/MainMap.vue';
export default {
name: 'HiMap',
components: {
MainMap
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
html, body, div {
margin: 0;
}
</style>
/components/MainMap.vue
<template>
<div id="map" :style="MapStyle"></div>
</template>
<script>
// Openlayers based modules
import 'ol/ol.css';
import {Map, View} from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
// Map Control
import {defaults} from 'ol/control'
export default {
name: 'MainMap',
data() {
return {
Map: {},
View: {},
Layers: [],
MapStyle: {
height: innerHeight + 'px',
width: innerWidth + 'px'
}
}
},
created() {
const self = this;
onresize = e => {
let win = e.currentTarget;
self.MapStyle.height = win.innerHeight + 'px';
self.MapStyle.width = win.innerWidth + 'px';
}
},
mounted() {
const self = this;
// View
const center = [12175093.67465372, 4209022.808896985];
const zoom = 4;
const projecton = 'EPSG:3857';
self.View = new View({
center: center,
zoom: zoom,
projecton: projecton,
});
// Layers
const osmLayer = new TileLayer({
source: new OSM(),
opacity: 1
});
self.Layers.push(osmLayer);
// Map
self.Map = new Map({
target: 'map',
view: self.View,
layers: self.Layers,
controls: defaults({
attribution: false,
rotate: false,
zoom: false
}),
});
self.map.on('click', event => {
console.log('(' + event.coordinate.toString() + ') ' + event.map.getView().getZoom());
});
},
}
</script>
<style scoped>
</style>
运行
在命令行输入如下命令,即可编译运行,之后在浏览器中打开即可。
cd hi-story
npm run serve
或者使用vue ui
命令在浏览器中打开GUI,运行项目。
基本地图页面搭建完成:
图5 基本地图页面