腾讯地图提供了丰富的API接口,其中就包括了JavaScript API用于在网页上实现定位功能。以下是一个简单的示例代码,用于在网页上获取并显示用户的当前位置:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>腾讯地图定位示例</title>
<script charset="utf-8" src="https://map.qq.com/api/js?v=2.exp&key=YOUR_API_KEY"></script>
</head>
<body>
<div id="container" style="width:100%;height:500px"></div>
<script>
var map, marker;
function init() {
map = new qq.maps.Map(document.getElementById("container"), {
zoom: 13
});
// 获取当前位置
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var center = new qq.maps.LatLng(lat, lng);
map.setCenter(center);
// 添加标记
marker = new qq.maps.Marker({
position: center,
map: map
});
}, function(error) {
console.error('定位失败:', error);
});
} else {
console.error('浏览器不支持地理位置服务');
}
}
window.onload = init;
</script>
</body>
</html>
请确保在使用上述代码时替换YOUR_API_KEY
为你自己的腾讯地图API密钥。
领取专属 10元无门槛券
手把手带您无忧上云