一、准备工作
从官网下载所需的包https://openlayers.org/
二、下载瓦片地图
这边使用迈高图下载的高德街道地图,仅下载了某个区域 下面以此区域为例:甘南藏族自治州
下载后的文件结构预览其中保函瓦片影像以及所选区域的KML
三、开始正文
引入openLayer包
<link rel="stylesheet" type="text/css" href="cs/ol.css" />
<script src="js/ol.js"></script>
<body onload="init()">
<div id="map"></div>
<!--标注点-->
<div id="mouse-position" class="mouse-position-wrapper">
<div class="custom-mouse-position"></div>
<div id="popup" class="ol-popup">
<a href="#" id="popup-closer" class="ol-popup-closer"></a>
<div id="popup-content"></div>
</div>
</div>
</body>
初始化瓦片地图
var projection = ol.proj.get('EPSG:3857');
/*********************加载基础地图**************************/
var map = new ol.Map({
target: 'map',
view: new ol.View({
center: ol.proj.transform([102.912413, 35.008063], 'EPSG:4326', 'EPSG:3857'),
zoom: 10,
projection: projection,
})
});
var layer = new ol.layer.Tile({
title: "基础地图",
source: new ol.source.XYZ({
url: '/title/{z}/{x}/{y}.png'
})
});
map.addLayer(layer);
加载一个KML文件
/*********************加载一个KML文件**************************/
var styles = new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255,255,255, 0)'
}),
stroke: new ol.style.Stroke({
color: '#000',
width: 2
})
});
var vectorSource2 = new ol.source.Vector({
url: 'kml/甘南藏族自治州.kml',
format: new ol.format.KML({
dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:3857',
extractStyles: false //至关重要
}),
projection: 'EPSG:3857'
});
var kmlLayer = new ol.layer.Vector({
source: vectorSource2,
style: styles
});
map.addLayer(kmlLayer);
显示标注与标注的点击事件
/*********************显示弹出层地图标注**************************/
var container = document.getElementById("popup");
var content = document.getElementById("popup-content");
var popupCloser = document.getElementById("popup-closer");
var overlay = new ol.Overlay({
element: container,
autoPan: true
});
map.on('click', function(e) {
var pixel = map.getEventPixel(e.originalEvent);
map.forEachFeatureAtPixel(pixel, function(feature) {
console.log(feature);
var json = feature;
var g = json.G.name;
if (g == '10001') {
var coodinate = e.coordinate;
content.innerHTML = "<p>你点击的坐标为:" + 10001 + "</p>";
overlay.setPosition(coodinate);
} else if (g == '10002') {
var coodinate = e.coordinate;
content.innerHTML = "<p>你点击的坐标为:" + 10002 + "</p>";
overlay.setPosition(coodinate);
}
map.addOverlay(overlay);
});
});
popupCloser.addEventListener('click', function() {
overlay.setPosition(undefined);
});
/*********************显示地标**************************/
//设置icon
//创建空的矢量容器
var vectorSource = new ol.source.Vector({});
//创建图标特性
var iconFeature1 = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([102.675835, 34.837231]), "XY"),
name: "10002",
});
//将图标特性添加进矢量中
vectorSource.addFeature(iconFeature1);
//console.log(t1+" "+t2);
//创建图标样式
var iconStyle = new ol.style.Style({
image: new ol.style.Icon({
opacity: 0.75,
src: "图标地址"
}),
});
//创建图标层
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: iconStyle
});
map.addLayer(vectorLayer);
源码下载: