在线引用:
地址:OpenLayers - Get the Code
离线引用:
下载地址:Releases · openlayers/openlayers · GitHub
v10.0.0版本
地图初始化代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--在线引用ol3
<script src="https://cdn.jsdelivr.net/npm/ol@v10.1.0/dist/ol.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@v10.1.0/ol.css">
-->
<!--离线引用ol3-->
<script src="./v10.0.0-package/dist/ol.js"></script>
<link rel="stylesheet" href="./v10.0.0-package/ol.css">
<title>初始化地图</title>
<style>
*{margin:0;padding:0}
#map{
width:100vw;
height: 100vh;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
/***初始化一个高德图层***/
const gaodeLayer = new ol.layer.Tile({
title:"高德地图",
source:new ol.source.XYZ({
url:'http://webst0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}',
wrapX:false
})
});
const gaodemap = new ol.Map({
target:"map",
layers:[
gaodeLayer
],
view:new ol.View({
// EPSG:3857投影
center:[13951671.781120978, 5449979.971864047],
projection:'EPSG:3857',
zoom:11,
// EPSG:4326投影
//center:[125.33,43.90],
//projection:'EPSG:4326'
})
});
</script>
</body>
</html>
坐标系转换: EPSG:3857 和 EPSG:4326 坐标系相互转换
// EPSG:3857 转换经纬度(EPSG:4326)
function mercatorTolonlat(mercator){
var lonlat={
x:0,
y:0
};
var x = mercator.x/20037508.34*180;
var y = mercator.y/20037508.34*180;
y= 180/Math.PI*(2*Math.atan(Math.exp(y*Math.PI/180))-Math.PI/2);
lonlat.x = x;
lonlat.y = y;
return lonlat;
}
// 经纬度(EPSG:4326)转换EPSG:3857
function lonLat2Mercator(lonlat){
var mercator = {
x:0,
y:0
};
var earthRad = 6378137.0;
mercator.x = lonlat.lng * Math.PI / 180 * earthRad;
var a = lonlat.lat * Math.PI / 180;
mercator.y = earthRad / 2 * Math.log((1.0 + Math.sin(a)) / (1.0 - Math.sin(a)));
return mercator;
}
// 使用
var lonlat={
lat:43.90,
lng:125.33
}
// 打印
console.log( lonLat2Mercator(lonlat));
补充(坐标转换):
const map = new ol.Map({
target:"map",
layers:[
gaodeLayer
],
// 坐标转换也可以用如下方法
view:new ol.View({
//xy值转至经纬度
//center:ol.proj.transform([13951671.781120978, 5449979.971864047], 'EPSG:3857','EPSG:4326' ),
//projection:'EPSG:4326',
// 经纬度转至xy值
center:ol.proj.transform([125.33,43.90],'EPSG:4326', 'EPSG:3857' ),
projection:'EPSG:3857',
zoom:11
})
});