<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- -->
<!-- 引入ol(OpenLayer)css和js资源-->
<link href="https://cdn.bootcdn.net/ajax/libs/ol3/4.6.5/ol.css" rel="stylesheet">
<script src="https://cdn.bootcdn.net/ajax/libs/ol3/4.6.5/ol.js"></script>
<style>
html,
body {
margin: 0;
height: 100%;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
/* 修改控件位置 */
.ol-zoomslider {
top: 7.5em;
}
.btn {
position: fixed;
top: 60px;
right: 20px;
}
</style>
</head>
<body>
<div id="map"></div>
<button class="btn">复位地图</button>
</body>
<script>
const gaode = new ol.layer.Tile({
title: '高德地图',
source: new ol.source.XYZ({
url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}',
wrapX: false
})
})
//1. 创建地图
const map = new ol.Map({
// 挂载到Dom元素上
target: 'map',
// 添加图层
layers: [gaode],
// 设置视图
view: new ol.View({
center: [114.30, 30.50],
zoom: 14,
projection: 'EPSG:4326'
})
})
//2. 将数据添加到矢量数据源中
var source = new ol.source.Vector({
url: "./data/map.json",
format: new ol.format.GeoJSON()
})
// 3设置资源到图层
var layer = new ol.layer.Vector({
source
})
// 4.设置图层到地图
map.addLayer(layer)
// 5设置点的样式
var style = new ol.style.Style({
image: new ol.style.Circle({
radius: 20,
fill: new ol.style.Fill({
color: "#ffed66"
}),
stroke: new ol.style.Stroke({
color: "#333",
width: 3
})
})
})
layer.setStyle(style)
// 6.添加控件
// 添加跳转控件
const zoomtoExtent = new ol.control.ZoomToExtent({
extent: [110, 30, 160, 30],
})
map.addControl(zoomtoExtent)
// 添加放大缩小控件
const zoomSlider = new ol.control.ZoomSlider()
map.addControl(zoomSlider)
// 添加全屏控件
const full = new ol.control.FullScreen()
map.addControl(full)
//7、 添加点击事件
map.on('click', function (e) {
var {
coordinate
} = e
//添加要素
var point = new ol.Feature({
geometry: new ol.geom.Point(coordinate)
})
source.addFeature(point)
// 实现漫游
var view = map.getView()
view.animate({
center: coordinate
})
})
//8. 点击漫游复位
var btn = document.querySelector('.btn')
btn.onclick = function () {
map.getView().animate({
center: [114.30, 30.50],
zoom: 6,
duration: 3000
})
}
</script>
</html>
data-->map.json data
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [114.30, 30.50]
}
}
]
}