基于高德地图 API 的地理定位与交互功能实现
高德地图 JavaScript API 提供了丰富的地理信息处理能力,适用于Web端的地图展示、位置选择、逆地理编码、自动补全搜索等场景。本文介绍如何集成并使用其核心功能:地图初始化、点击标记、地址自动补全、逆地理编码解析及工具栏定位。
引入API与插件配置
高德地图仅需引入一个主JS文件,但可通过plugin参数加载所需扩展模块,多个插件以英文逗号分隔。以下为推荐的引入方式:
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=YOUR_API_KEY&plugin=AMap.Geocoder,AMap.Autocomplete,AMap.ToolBar,AMap.Geolocation"></script>
HTML结构设计
构建包含地图容器和表单输入项的界面布局,用于显示地图并收集地理数据:
<div id="mapContainer" style="height: 400px;"></div>
<form id="locationForm">
<input type="hidden" id="recordId" value="" />
<div class="form-group">
<label>地址</label>
<input id="addressInput" class="form-control" placeholder="请输入地址" />
<input id="fullAddress" name="address" type="hidden" />
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>经度</label>
<input id="lngOutput" class="form-control" readonly />
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>纬度</label>
<input id="latOutput" class="form-control" readonly />
</div>
</div>
</div>
<div class="form-group">
<label>行政区代码</label>
<input id="adCode" class="form-control" readonly />
</div>
<button type="button" class="btn btn-primary" onclick="submitLocation()">提交</button>
<button type="button" class="btn btn-default" onclick="closePanel()">取消</button>
</form>
地图初始化与事件绑定
设置地图容器尺寸,并创建地图实例。初始中心点可动态获取或设为默认坐标。
// 设置地图高度
document.getElementById('mapContainer').style.height = (window.innerHeight / 2) + 'px';
// 初始化地图
let map = new AMap.Map('mapContainer', {
zoom: 15,
resizeEnable: true
});
// 初始标记
let marker;
let currentPos = map.getCenter();
marker = new AMap.Marker({ position: currentPos });
marker.setMap(map);
// 更新表单坐标值
document.getElementById('lngOutput').value = currentPos.lng;
document.getElementById('latOutput').value = currentPos.lat;
// 地图点击事件:更新标记位置
map.on('click', function(e) {
let clickedLngLat = e.lnglat;
map.remove(marker);
marker = new AMap.Marker({ position: clickedLngLat });
marker.setMap(map);
// 更新经纬度字段
document.getElementById('lngOutput').value = clickedLngLat.lng;
document.getElementById('latOutput').value = clickedLngLat.lat;
// 执行逆地理编码
reverseGeocode(clickedLngLat);
});
逆地理编码(坐标 → 地址)
将选中的地理坐标转换为可读地址信息,包括区域编码和详细描述。
function reverseGeocode(lnglat) {
let geocoder = new AMap.Geocoder({
radius: 1000,
extensions: 'all'
});
geocoder.getAddress(lnglat, function(status, result) {
if (status === 'complete' && result.info === 'OK') {
let addrComponent = result.regeocode.addressComponent;
let formattedAddr = result.regeocode.formattedAddress;
document.getElementById('addressInput').value = formattedAddr;
document.getElementById('fullAddress').value = formattedAddr;
document.getElementById('adCode').value = addrComponent.adcode;
}
});
}
地址自动补全与选择
利用AMap.Autocomplete实现输入建议,用户选择后自动跳转至对应位置并更新标记。
let autoComp = new AMap.Autocomplete({
input: 'addressInput'
});
AMap.event.addListener(autoComp, 'select', function(selected) {
let poi = selected.poi;
if (!poi.location) return;
map.setCenter(poi.location);
map.remove(marker);
marker = new AMap.Marker({ position: poi.location });
marker.setMap(map);
document.getElementById('fullAddress').value = poi.district + poi.name;
document.getElementById('addressInput').value = poi.district + poi.name;
document.getElementById('adCode').value = poi.adcode;
document.getElementById('lngOutput').value = poi.location.lng;
document.getElementById('latOutput').value = poi.location.lat;
});
工具栏与定位控制
通过插件添加工具栏和定位控件。注意:所有插件相关对象必须在map.plugin()回调中创建和操作。
map.plugin(['AMap.ToolBar', 'AMap.Geolocation'], function() {
// 添加工具栏
let toolbar = new AMap.ToolBar({
position: 'LT',
ruler: true,
direction: true
});
map.addControl(toolbar);
// 工具栏定位回调
toolbar.on('location', function(e) {
let locRes = e.lnglat;
document.getElementById('lngOutput').value = locRes.lng;
document.getElementById('latOutput').value = locRes.lat;
map.remove(marker);
marker = new AMap.Marker({ position: locRes });
marker.setMap(map);
reverseGeocode(locRes);
});
// 浏览器定位控件
let geoLoc = new AMap.Geolocation({
enableHighAccuracy: true,
timeout: 3000,
buttonPosition: 'RB',
zoomToAccuracy: true
});
map.addControl(geoLoc);
// 获取当前位置
geoLoc.getCurrentPosition();
AMap.event.addListener(geoLoc, 'complete', function(data) {
if (data.info === 'SUCCESS') {
let pos = data.position;
document.getElementById('lngOutput').value = pos.lng;
document.getElementById('latOutput').value = pos.lat;
document.getElementById('fullAddress').value = data.formattedAddress;
document.getElementById('addressInput').value = data.formattedAddress;
document.getElementById('adCode').value = data.addressComponent.adcode;
map.remove(marker);
marker = new AMap.Marker({ position: pos });
marker.setMap(map);
}
});
AMap.event.addListener(geoLoc, 'error', function() {
alert('定位失败,请检查网络或权限设置');
});
});
关键注意事项
- 插件作用域限制:所有依赖插件的对象(如
ToolBar、Geolocation)必须在map.plugin([...], callback)的回调函数内实例化,否则会报错。 - 异步加载机制:地图API为异步加载,确保DOM就绪后再初始化地图。
- 安全密钥管理:前端使用的Key应配置合法域名白名单,避免被盗用。