首先得去高德控制臺申請兩個?key,一個天氣key和一個定位key
?
獲取天氣信息的函數:
const getWeather = function (city) {// 使用 fetch 發送請求獲取天氣信息fetch(`https://restapi.amap.com/v3/weather/weatherInfo?city=${city}&key=eefd36557b0250d19d243aea0f62d499`).then((response) => response.json()).then((data) => {const { lives } = data;// 更新響應式數據weather.city = lives[0].city;weather.weather = lives[0].weather;weather.temperature = lives[0].temperature;weather.winddirection = lives[0].winddirection;weather.windpower = lives[0].windpower;weather.reporttime = lives[0].reporttime;});
};
使用Geolocation API獲取當前位置:
onMounted(() => {let latitude = 0;let longitude = 0;if ("geolocation" in navigator) {navigator.geolocation.getCurrentPosition(function (position) {latitude = position.coords.latitude;longitude = position.coords.longitude;},function (error) {console.error("獲取位置失敗:", error.message);});} else {console.error("瀏覽器不支持Geolocation");}
});
加載高德地圖API并在地圖上顯示標記和天氣信息:
AMapLoader.load({// 加載高德地圖API
}).then((AMap) => {// 在地圖上顯示當前位置的標記const marker = new AMap.Marker({position: new AMap.LngLat(longitude, latitude),title: "當前位置",});// 其他地圖初始化和相關操作// 在地圖上顯示信息窗體watch(weather, (newVal, oldVal) => {// 創建信息窗體var content = ["<div><b>天氣</b>",`城市:${weather.city}`,// 其他天氣信息..."</div>",];var infoWindow = new AMap.InfoWindow({content: content.join("<br>"),anchor: "top-left",});infoWindow.open(map, [longitude, latitude]);});// 添加標記到地圖map.add(marker);// 標記點擊事件marker.on('click', function (e) {// 打開信息窗體infoWindow.open(map, [longitude, latitude]);});
}).catch(e => {console.error(e);
});
全部代碼
<template><div id="container"></div><!-- -->
</template>
<script setup lang="ts">
import {onMounted, reactive, ref, watch} from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import {computed} from "vue-demi";// 如果是在 ts 的項目中,這一步會有類型錯誤,解決方案請移步 2.1.1
window._AMapSecurityConfig = {securityJsCode: 'd6a5157a0b06c55bcee22c7b69a42c5a'// 你的安全密鑰
};
// 定義當前經緯度
/** 初始化地圖函數 */
// IP定位獲取當前城市信息
const weather = reactive({city: '',weather: '',temperature: '',winddirection: '',windpower: '',reporttime: ''
})
const weatheritem = computed(() => {// 回調函數必須return,結果就是計算的結果// 如果計算屬性依賴的數據發生變化,那么會重新計算return weather
})const getWeather = function (city) {fetch(`https://restapi.amap.com/v3/weather/weatherInfo?city=${city}&key=eefd36557b0250d19d243aea0f62d499` //天氣key).then((response) => {return response.json();}).then((data) => {const {lives} = dataconsole.log(lives[0])weather.city = lives[0].cityweather.weather = lives[0].weatherweather.temperature = lives[0].temperatureweather.winddirection = lives[0].winddirectionweather.windpower = lives[0].windpowerweather.reporttime = lives[0].reporttime});
}
onMounted(() => {let latitude = 0;let longitude = 0;// 獲取當前位置的經緯度
// 檢查瀏覽器是否支持Geolocationif ("geolocation" in navigator) {// 獲取當前位置navigator.geolocation.getCurrentPosition(function (position) {// 獲取經緯度latitude = position.coords.latitude;longitude = position.coords.longitude;// 在這里使用經緯度數據進行其他操作console.log("緯度:" + latitude + ", 經度:" + longitude);},function (error) {// 處理獲取位置失敗的情況console.error("獲取位置失敗:", error.message);});} else {// 瀏覽器不支持Geolocationconsole.error("瀏覽器不支持Geolocation");}// AMapLoader => 加載器// 資源加載完成后就會觸發 thenAMapLoader.load({"key": "34b7b1e632fcf24d30be5c5825f8043d", // 申請好的Web端開發者定位Key,首次調用 load 時必填"version": "2.0", // 指定要加載的 JS API 的版本,缺省時默認為 1.4.15"plugins": [], // 需要使用的的插件列表,如比例尺'AMap.Scale'等}).then((AMap) => {AMap.plugin('AMap.CitySearch', function () {var citySearch = new AMap.CitySearch()citySearch.getLocalCity(function (status, result) {if (status === 'complete' && result.info === 'OK') {// 查詢成功,result即為當前所在城市信息console.log(result.city)getWeather(result.city)}})})const marker = new AMap.Marker({position: new AMap.LngLat(longitude, latitude), //經緯度對象,也可以是經緯度構成的一維數組[116.39, 39.9]title: "當前位置",});//打開信息窗體// 初始化地圖const map = new AMap.Map('container', {center: [longitude, latitude], //地圖中心點zoom: 10// 配置對象 - 配置地圖的風格和縮放比例,請移步 2.2});//獲取當前城市信息//信息窗體的內容watch(weather, (newVal, oldVal) => {console.log(newVal, oldVal)var content = ["<div><b>天氣</b>",`城市:${weather.city}`,`時間:${weather.reporttime}`,`天氣:${weather.weather}`,`溫度:${weather.temperature}℃`,`風向:${weather.winddirection}`,`風速:${weather.windpower}`,"</div>",];
//創建 infoWindow 實例var infoWindow = new AMap.InfoWindow({content: content.join("<br>"), //傳入字符串拼接的 DOM 元素anchor: "top-left",});infoWindow.open(map, [longitude, latitude]); //map 為當前地圖的實例,map.getCenter() 用于獲取地圖中心點坐標。})map.add(marker)marker.on('click', function (e) {// 打開信息窗體,顯示信息console.log(e)infoWindow.open(map, [longitude, latitude]);});}).catch(e => {console.log(e);});
});</script><style scoped>
#container {width: 100vw;height: 100vh;
}
</style>