官网上有个quick start 我是在这个基础上进行修改的:
https://openlayers.org/en/latest/doc/quickstart.html
这个是官网的:
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.6.1/css/ol.css" type="text/css">
<style>
.map {
height: 400px;
width: 100%;
}
</style>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.6.1/build/ol.js"></script>
<title>OpenLayers example</title>
</head>
<body>
<h2>My Map</h2>
<div id="map" class="map"></div>
<script type="text/javascript">
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: ol.proj.fromLonLat([37.41, 8.82]),
zoom: 4
})
});
</script>
</body>
</html>
在网页中打开如下:
BUT,这里,他使用的是OSM为底图 我们需要做一些修改
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
改为,整段代码都附上好了:(这里我修改了一下缩放比例和页面高度)
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.6.1/css/ol.css" type="text/css">
<style>
.map {
height: 600px;
width: 100%;
}
</style>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.6.1/build/ol.js"></script>
<title>OpenLayers example</title>
</head>
<body>
<h2>My Map</h2>
<div id="map" class="map"></div>
<script type="text/javascript">
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.XYZ({
url: "http://t2.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=94b23cf14b33f25fbade47ecacddffb8"
})
}),
new ol.layer.Tile({
source: new ol.source.XYZ({
url: "http://t3.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=94b23cf14b33f25fbade47ecacddffb8"
})
})
],
view: new ol.View({
center: ol.proj.fromLonLat([108.01, 32.206]),
zoom: 9
})
});
</script>
</body>
</html>
注意,红圈里的一串数字要填写你在天地图申请到的key
在网页中打开: