使用最新高德JSAPI2.0
先看效果
在 官方示例基础上做了些改动
很多控件在初始化添加即可:如小窗口,指南针等,根据自己的需要加吧
html代码
<!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">
<title>高德api</title>
<link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
<style>
html,
body,
#container {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="container"></div>
<div class="info" id="text">
请用鼠标在地图上操作试试
</div>
<div class="input-card" style="width:16rem">
<h4>地图点击相关事件</h4>
<div>
<div class="input-item">
<button id="clickOn" class="btn" style="margin-right:1rem;">绑定事件</button>
<button id="clickOff" class="btn">解绑事件</button>
</div>
</div>
</div>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=你的key"></script>
<script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script><script src="index.js"></script>
<script type="text/javascript">
</script>
</body>
</html>
js
var map;
var marker;
var ilon = 114.468668;
var ilat = 38.03703;
//初始化地图![](/i/l/?n=22&i=blog/1898315/202211/1898315-20221126095416519-1876629016.gif)
对象,加载地图
map = new AMap.Map("container", {
zoom: 13,
});
// 实例化点标记
marker = new AMap.Marker({
icon: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
position: [ilon, ilat],
offset: new AMap.Pixel(-25, -60)
});
map.setZoomAndCenter(13, [ilon, ilat]);
map.add(marker)
function showInfoDbClick(e){
var text = '您在 [ '+e.lnglat.getLng()+','+e.lnglat.getLat()+' ] 的位置双击了地图!'
document.querySelector("#text").innerText = text;
}
function showInfoMove(){
var text = '您移动了您的鼠标!'
document.querySelector("#text").innerText = text;
}
// 事件绑定
function clickOn(){
log.success("绑定事件!");
map.on('click', function (e) {
map.clearMap();
//console.log(e.lnglat);
marker = new AMap.Marker({
icon: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
position: [e.lnglat.lng, e.lnglat.lat],
offset: new AMap.Pixel(-25, -60)
});
var text = '您在 [ '+e.lnglat.getLng()+','+e.lnglat.getLat()+' ] 的位置单击了地图!'
document.querySelector("#text").innerText = text;
console.log(text)
map.add(marker);
})
map.on('dblclick', showInfoDbClick);
map.on('mousemove', showInfoMove);
}
// 解绑事件
function clickOff(){
log.success("解除事件绑定!");
map.off('click', showInfoClick);
map.off('dblclick', showInfoDbClick);
map.off('mousemove', showInfoMove);
}
// 给按钮绑定事件
document.getElementById("clickOn").onclick = clickOn;
标签:map,示例,text,lnglat,JS,var,API,AMap,marker
From: https://www.cnblogs.com/rzkwz/p/16926956.html