vue3搭配高德地图实现打卡功能
时间: 2023-12-28 07:05:53 浏览: 146
vue整合高德地图笔记
要实现 Vue3 搭配高德地图实现打卡功能,需要进行以下步骤:
1. 引入高德地图 API
在 Vue3 中,我们可以在 main.js 中引入高德地图 API,并将其挂载到 Vue 实例上,以便全局使用。
```javascript
import AMapLoader from "@amap/amap-jsapi-loader";
const _loadAMapApi = () => {
return AMapLoader.load({
key: "Your Key",
version: "2.0",
plugins: ["AMap.MarkerClusterer"],
});
};
createApp(App)
.use(router)
.provide("amapApi", _loadAMapApi())
.mount("#app");
```
2. 创建地图实例
在组件中,我们可以通过 inject 获取到 AMapLoader 实例,然后创建地图实例。
```javascript
import { inject } from "vue";
export default {
name: "Map",
setup() {
const amapApi = inject("amapApi");
const map = new amapApi.Map("map-container", {
zoom: 13,
center: [116.39, 39.9],
});
return {
map,
};
},
};
```
3. 添加标记点
添加标记点可以使用 AMap.Marker 类,先通过 createMarker 创建 Marker 实例,然后通过 map.add 方法将 Marker 添加到地图上。
```javascript
import { createMarker } from "@amap/amap-jsapi-loader";
export default {
name: "Map",
setup() {
const amapApi = inject("amapApi");
const map = new amapApi.Map("map-container", {
zoom: 13,
center: [116.39, 39.9],
});
const addMarker = async () => {
const marker = await createMarker({
position: [116.39, 39.9],
icon: "https://webapi.amap.com/images/car.png",
offset: [-24, -24],
map,
});
};
return {
map,
addMarker,
};
},
};
```
4. 获取当前定位
可以使用 AMap.Geolocation 类获取当前定位,通过 createGeolocation 创建 Geolocation 实例,然后调用 getCurrentPosition 方法获取当前位置。
```javascript
import { createMarker, createGeolocation } from "@amap/amap-jsapi-loader";
export default {
name: "Map",
setup() {
const amapApi = inject("amapApi");
const map = new amapApi.Map("map-container", {
zoom: 13,
center: [116.39, 39.9],
});
const addMarker = async () => {
const geolocation = await createGeolocation({
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0,
});
const marker = await createMarker({
position: geolocation.getCurrentPosition(),
icon: "https://webapi.amap.com/images/car.png",
offset: [-24, -24],
map,
});
};
return {
map,
addMarker,
};
},
};
```
5. 保存数据到后台
最后,我们可以通过 axios 等库将打卡数据保存到后台。
```javascript
import axios from "axios";
export default {
name: "Map",
setup() {
const amapApi = inject("amapApi");
const map = new amapApi.Map("map-container", {
zoom: 13,
center: [116.39, 39.9],
});
const addMarker = async () => {
const geolocation = await createGeolocation({
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0,
});
const marker = await createMarker({
position: geolocation.getCurrentPosition(),
icon: "https://webapi.amap.com/images/car.png",
offset: [-24, -24],
map,
});
const postData = {
location: marker.getPosition(),
time: new Date(),
};
axios.post("https://your-api-endpoint.com/checkin", postData);
};
return {
map,
addMarker,
};
},
};
```
通过以上步骤,我们就可以在 Vue3 搭配高德地图中实现打卡功能了。
阅读全文