是得好好记录一下这个曲折的过程
看了n篇博客,没一个是代码复制过来能显示地图的。这对于0基础但是急需快速弄出个地图显示出来及其不友好!!
而且很多博客都是一样的,不知道那些直接去复制别人的博客过来的人是怎么想的,这么做有什么意义吗。
表示很无语,但是废话不多说,进入正题!
天地图部分
1、首先默认你会用vue了,然后去openlayers官网简单做个了解,知道基础用法。
2、加载天地图得有一个key,先去天地图官网搞一个,具体步骤看我的另一篇文章,说到这个也是没有几篇博客写得很清楚的,就很。。。无助。
3、在vue中安装openlayers
npm i --save ol
这里说的vue是基于脚手架构建的。 新建个页面,也就是vue文件,配置好路由。接着就是可以直接放入我的代码运行显示了。
<template>
<div class="wrapper">
<div>天地图</div>
<div class="map" id="olMap"></div>
</div>
</template>
<script>
import "ol/ol.css";
import { Tile as TileLayer } from "ol/layer";
import XYZ from "ol/source/XYZ";
import { defaults as defaultControls } from "ol/control";
import Map from "ol/Map.js";
import View from "ol/View.js";
export default {
data() {
return {
map: null,
parser: null,
};
},
mounted() {
this.initMap();
},
methods: {
initMap() {
const map = new Map({
target: "olMap",
view: new View({
center: [0, 0],
zoom: 4,
projection: "EPSG:4326",
}),
controls: defaultControls({
zoom: true,
attribution: false,
rotate: false,
}),
});
this.map = map;
let url = "http://t{0-7}.tianditu.com/DataServer?x={x}&y={y}&l={z}";
url = `${url}&T=vec_c&tk=替代你的key`;
const source = new XYZ({
url: url,
projection: "EPSG:4326",
});
const tdtLayer = new TileLayer({
source: source,
});
this.map.addLayer(tdtLayer);
url = "http://t{0-7}.tianditu.com/DataServer?x={x}&y={y}&l={z}";
url = `${url}&T=cva_c&tk=替代你的key`;
const sourceCVA = new XYZ({
url: url,
projection: "EPSG:4326",
});
const tdtcvaLayer = new TileLayer({
source: sourceCVA,
});
this.map.addLayer(tdtcvaLayer);
},
},
};
</script>
<style scoped>
.map {
width: 100%;
height: 100vh;
}
</style>
天地图就可以显示出来了。
效果图
高德地图部分
相对于天地图,高德地图就容易多了,直接上代码
<template>
<div class="wrapper">
<div>高德地图</div>
<div id="map"></div>
</div>
</template>
<script>
import {Map,View,Feature} from 'ol'
import * as olProj from 'ol/proj'
import {Point} from 'ol/geom'
import { Style, Fill, Stroke, Circle as sCircle } from "ol/style";
import Tilelayer from 'ol/layer/Tile'
import {Vector as VectorLayer} from 'ol/layer'
import {XYZ,Vector as VectorSource} from 'ol/source'
import "ol/ol.css"
export default {
data() {
return {
map:null
}
},
mounted() {
this.init();
this.setMarker();
},
methods: {
init(){
this.map=new Map({
target:'map',
layers:[new Tilelayer({
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}',
})
})
],
view:new View({
center:olProj.fromLonLat([108.945951, 34.465262]),
zoom:2
}),
})
},
setMarker(){
let _style = new Style({
image:new sCircle({
radius:10,
stroke:new Stroke({
color:"#fff",
}),
fill: new Fill({
color:'#3399CC',
}),
}),
});
let _feature = new Feature({
geometry:new Point(olProj.fromLonLat([108.945951, 34.465262])),
});
_feature.setStyle(_style);
let _marker = new VectorLayer({
source: new VectorSource({
feature:[_feature],
}),
});
this.map.addLayer(_marker);
},
},
}
</script>
<style scoped>
#map{
width: 100vw;
height: 100vh;
}
</style>
总而言之,全过程都是自己琢磨,太难受了,希望对于像我这样的小白能够有所帮助,如果真显示不出来有bug可以私聊相互学习学习QQ:2669743568