Capacitor 有提供 @capacitor/geolocation,讓開發者可以拿到使用者的裝置定位,若裝置有支援,還可以提供裝置速率、方向等
首先下載 @capacitor/geolocation
npm install @capacitor/geolocation
npx cap sync
範例程式碼,抓到當前的經緯度
import { Geolocation } from '@capacitor/geolocation';
const printCurrentPosition = async () => {
const coordinates = await Geolocation.getCurrentPosition();
console.log('這樣就可以拿到當前的經緯度了~',
'lat:', coordinates.coords.latitude,
'lng:', coordinates.coords.longitude,
);
<template>
<capacitor-google-map id="map"></capacitor-google-map>
</template>
<style scoped>
capacitor-google-map {
display: inline-block;
width: 100%;
height: 100vh;
}
</style>
<script setup>
import { ref, reactive, onMounted } from "vue";
import { GoogleMap } from "@capacitor/google-maps";
import { Geolocation } from "@capacitor/geolocation";
const newMap = ref(null);
const centerCoordinates = reactive({});
const createMap = async () => { //create google map
const mapRef = document.getElementById("map");
//使用 @capacitor/geolocation 提供的方法 getCurrentPosition() 來獲取目前裝置定位
const coordinates = await Geolocation.getCurrentPosition();
//將裝置定位抓到的經緯度存到 centerCoordinates 物件中
centerCoordinates.lat = coordinates.coords.latitude;
centerCoordinates.lng = coordinates.coords.longitude;
//繪製 google map
const newMap = await GoogleMap.create({
id: "my-map",
element: mapRef,
apiKey: import.meta.env.VITE_GOOGLE_API_KEY,
config: {
center: centerCoordinates,
zoom: 16,
disableDefaultUI: true,
},
});
//建立標示
const markerId = await newMap.addMarker({
coordinate: centerCoordinates,
});
};
onMounted(async () => {
await createMap();
});