<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>高德地图</title>
<link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
<style>
html,
body,
#container {
height: 500px;
width: 500px;
}
.amap-marker:first-child .amap-icon img {
width: 25px;
height: 34px;
}
.btn {
width: 10rem;
margin-left: 6.8rem;
}
</style>
</head>
<body onload="init()">
<div id="container"></div>
<div class="input-card" style='width:28rem;'>
<label style='color:grey'>地理编码,根据地址获取经纬度坐标</label>
<div class="input-item">
<div class="input-item-prepend"><span class="input-item-text">地址</span></div>
<input id='address' type="text" value='北京市朝阳区阜荣街10号'>
</div>
<div class="input-item">
<div class="input-item-prepend"><span class="input-item-text">经纬度</span></div>
<input id='lnglat' disabled type="text">
</div>
<input id="geo" type="button" class="btn" value="地址 -> 经纬度" />
</div>
<div class="info">鼠标拖拽点标记试试</div>
</body>
</html>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=申请的秘钥&plugin=AMap.Geocoder"></script>
<script type="text/javascript">
var marker = null
var map = null
var geocoder = null
/*
* newlocation 经纬度
**/
function init(newlocation = [116.397428, 39.90923]) {
map = new AMap.Map("container", {
resizeEnable: true,
center: newlocation,
zoom: 16
});
geocoder = new AMap.Geocoder({
city: "全国",
});
marker = new AMap.Marker({
position: map.getCenter(),
// icon: 'https://a.amap.com/jsapi_demos/static/resource/img/user.png',
offset: new AMap.Pixel(-13, -30),
// 设置是否可以拖拽
draggable: true,
cursor: 'move'
});
marker.setMap(map);
var clickHandler = function (e) { // 点图点击
// console.log(e.lnglat)
marker.setPosition(e.lnglat);
againAddress(e.lnglat)
};
map.on('click', clickHandler);
}
function geoCode() {
var address = document.getElementById('address').value;
geocoder.getLocation(address, function (status, result) {
console.log(status, result, result.geocodes[0].location, 'status, result')
if (status === 'complete' && result.geocodes.length) {
againLocation(result.geocodes[0].location)
log.success('根据地址');
} else {
log.error('根据地址查询位置失败');
}
});
}
document.getElementById("geo").onclick = geoCode;
document.getElementById('address').onkeydown = function (e) {
if (e.keyCode === 13) {
geoCode();
return false;
}
return true;
};
// 根据地址获取经纬度更新地图最新标点
function againLocation(newlocation) {
marker.setMap(null); // 先移除点再添加新点
marker = null;
setTimeout(() => {
init(newlocation)
}, 300);
}
// 根据经纬度获取详情地址
function againAddress(newlocation) {
geocoder.getAddress(newlocation, function (status, result) {
if (status === 'complete' && result.regeocode) {
console.log(status, result)
document.getElementById('address').value = result.regeocode.formattedAddress
log.success('根据经纬度查询地址成功啦啦啦啦')
} else {
log.error('根据经纬度查询地址失败')
}
});
}
function ceshi() { // 根据地址获取金纬度
console.log(marker)
}
</script>