应用场景: 客户手上有一批从百度获取的资源数据,想要在我们的地图上展示,已知我们切片底图用的是高德地图,坐标系是GCJ-02火星坐标系,也叫国测局坐标系,如果根据百度的资源数据直接打点,会出现偏差。要先把百度坐标系转换为火星坐标系,再进行打点。
开源工具 coordtransform 坐标转换支持前端浏览器的转换:传送门:coordtransform 文档
具体代码:使用高德地图,key可在官网申请 传送门:高德key申请
资源下载,包含坐标转换的index.js模块,含有高德key的源代码:传送门:资源下载
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
<link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
<title>地图显示</title>
<style>
html,
body,
#container {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div>
<input type="text" id="x" style="width:120px;height:30px;" placeholder="请输入经度"/>
<input type="text" id="y" style="width:120px;height:30px;" placeholder="请输入纬度">
<button id="btn" onclick="addPoint()" style="background-color: #4CAF50;
border: none;
color: white;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 15px;
margin: 1px 1px;
cursor: pointer;">添加点
</button>
<button id="btn" onclick="removePoint()" style="background-color: #4CAF50;
border: none;
color: white;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 15px;
margin: 1px 1px;
cursor: pointer;">移除点
</button>
</div>
<div id="container"></div>
<!-- 加载地图JSAPI脚本 -->
<script src="https://webapi.amap.com/maps?v=1.4.15&key=你申请的key"></script>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script src="index.js"></script>
<script>
var map = new AMap.Map('container', {
resizeEnable: true, //是否监控地图容器尺寸变化
zoom:11, //初始化地图层级
center: [116.397428, 39.90923] //初始化地图中心点
});
var marker; // 点实例
var markerList = [] //用于存放已添加点的集合
//添加点的方法
var addPoint = function() {
let x = parseFloat($("#x").val()) //获取文本框输入的经度并转为float类型
let y = parseFloat($("#y").val()) //获取文本框输入的纬度并转为float类型
// 本例子是从百度获取的资源数据在高德地图上打点,需要将百度坐标转火星坐标
let bd09togcj02 = coordtransform.bd09togcj02(x, y) // 百度坐标转火星坐标
//var gcj02tobd09 = coordtransform.gcj02tobd09(116.404, 39.915); // 火星坐标转百度坐标
//var wgs84togcj02 = coordtransform.wgs84togcj02(116.404, 39.915); // wgs84坐标转火星坐标
//var gcj02towgs84 = coordtransform.gcj02towgs84(115.6282, 22.0907); // 火星坐标转wgs84坐标
let lon = bd09togcj02[0] //转换后的火星坐标经度
let lat = bd09togcj02[1] //转换后的火星坐标纬度
marker = new AMap.Marker({ //点实例
position: new AMap.LngLat(lon, lat), //位置
icon: new AMap.Icon({ //图标实例
image: 'dw.png', //图标路径
size: new AMap.Size(30, 40), //图标所处区域大小
imageSize: new AMap.Size(30,40) //图标大小
}),
offset: new AMap.Pixel(0, 0), //图标偏移
anchor:'center' //锚点位置
});
map.add(marker) //将点添加到地图
markerList.push(marker) //将添加的点放入集合
}
//删除点方法
var removePoint = function() {
map.remove(markerList) //移除集合内已添加的所有点
markerList.length = 0 //将集合清空
}
</script>
</body>
</html>
实用效果: