获取当前坐标,并在成功回调函数 showPosition 中异步加载腾讯地图API;在Vue的挂载生命周期函数中调用
navigator.geolocation.getCurrentPosition(showPosition, showError);
const showPosition = (position) => {
longitude.value = position.coords.longitude;
latitude.value = position.coords.latitude;
loadScript();
}
const showError = (error) => {
console.error(`Error code: ${error.code}. Message: ${error.message}`);
}
异步加载腾讯地图API - 创建 <script>,指定 src 并挂载到 <body>,最后使用回调函数 callback 初始化地图
const loadScript = () => {
let script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://map.qq.com/api/gljs?v=1.exp&key=your key&callback=initMap";
document.body.appendChild(script);
}
初始化地图,函数需要挂载到 window 对象;地图初始化,指定中心点,添加标记 showMarker
window.initMap = () => {
let center = new TMap.LatLng(latitude.value, longitude.value)
mapInstance.value = new TMap.Map(map.value, {
center: center,
zoom: 17.2,
viewMode: '2D',
showControl: false
});
showMarker(center);
}
添加标记
const showMarker = (center) => {
// center marker
let marker = new TMap.MultiMarker({
position: center,
map: mapInstance.value,
styles: {
marker: new TMap.MarkerStyle({
width: 20,
height: 30,
anchor: { x: 10, y: 30 },
})
},
geometries: [
{
position: center,
id: 'marker',
}
]
});
}