高德地图API使用示例
这是一个关于如何使用高德地图API的示例网站。我们将在这个网站上展示如何通过高德地图API获取地理编码信息、进行地理定位以及在地图上添加标记等功能。
1. 获取地理编码信息
要获取地理编码信息,我们需要使用高德地图API的geocoder
对象。首先,我们需要引入高德地图API的JavaScript库,然后初始化geocoder
对象,最后调用getAddress
方法来获取地址信息。
<!DOCTYPE html>
<html>
<head>
<title>高德地图API示例</title>
<script src="https://webapi.amap.com/maps?v=1.4.15&key=您的高德地图API密钥"></script>
</head>
<body>
<div id="container" style="width: 100%; height: 100%;"></div>
<script>
var map = new AMap.Map('container', {
zoom: 13,
center: [116.397428, 39.90923]
});
var geocoder = new AMap.Geocoder();
var address = '北京市海淀区上地十街10号';
var infoWindow = new AMap.InfoWindow({content: '北京市海淀区上地十街10号'});
geocoder.getLocation(address, function(status, result){
if (status === 'complete' && result.info === 'OK'){
var lnglat = result.geocodes[0].location;
infoWindow.setPosition(new AMap.Pixel(lnglat.lng, lnglat.lat));
infoWindow.open(map);
map.setCenter(lnglat);
} else {
alert('您选择的位置无效!');
}
});
</script>
</body>
</html>
2. 地理定位
要在地图上显示用户的位置,我们可以使用高德地图API的AMap.Geolocation
类。首先,我们需要引入高德地图API的JavaScript库,然后创建一个Geolocation
对象,最后调用getCurrentPosition
方法来获取当前位置信息。
<!DOCTYPE html>
<html>
<head>
<title>高德地图API示例</title>
<script src="https://webapi.amap.com/maps?v=1.4.15&key=您的高德地图API密钥"></script>
</head>
<body>
<div id="mapContainer" style="width: 100%; height: 100%;"></div>
<script>
var map = new AMap.Map('mapContainer', {
zoom: 13,
center: [116.397428, 39.90923]
});
var geolocation = new AMap.Geolocation({enableHighAccuracy: true, timeout: 10000, maximumAge: 0});
geolocation.getCurrentPosition(function(status, result){
if (status === 'complete'){
var position = result.position;
map.setCenter(position);
map.setZoom(16);
} else {
alert('无法获取地理位置信息!');
}
});
</script>
</body>
</html>
3. 在地图上添加标记
在地图上添加标记非常简单,只需创建一个AMap.Marker
对象,并将其添加到地图上的指定位置即可。以下是一个简单的示例,展示了如何在地图上添加一个红色的标记:
”`html <!DOCTYPE html>