Vue利用高德地圖API實現(xiàn)實時天氣
前言
閑來無事,利用摸魚時間實現(xiàn)實時天氣的小功能
目錄
- 登錄 高德開放平臺控制臺,如果沒有開發(fā)者賬號,請 注冊開發(fā)者。
- 創(chuàng)建 key,進入應用管理,創(chuàng)建新應用,新應用中添加 key,服務平臺選擇 Web端(JS API)。
- 獲取 key 和密鑰
- 獲取當前城市定位
- 通過定位獲取城市名稱、區(qū)域編碼,查詢目標城市/區(qū)域的實時天氣狀況
效果圖
這里樣式我就不做處理了,地圖可以不用做展示,只需要拿到獲取到天氣的結果,結合自己的樣式展示就可以了,未來天氣可以結合echarts進行展示,頁面效果更佳
實現(xiàn)
1.登錄高德開放平臺控制臺
2.創(chuàng)建 key
這里應用名稱可以隨便?。▊€人建議功能名稱或者項目稱)
3.獲取 key 和密鑰
4.獲取當前城市定位
首先,先安裝依賴
npm install @amap/amap-jsapi-loader --save
或者
pnpm add @amap/amap-jsapi-loader --save
頁面使用時引入即可 import AMapLoader from "@amap/amap-jsapi-loader"
/** 1. 調(diào)用AMapLoader.load方法,通過傳入一個對象作為參數(shù)來指定加載地圖時的配置信息。 * - key: 申請好的Web端開發(fā)者Key,是必填項,用于授權您的應用程序使用高德地圖API。 * - version: 指定要加載的JSAPI版本,不指定時默認為1.4.15。 * - plugins: 需要使用的插件列表,如比例尺、縮放控件等。 */ function initMap() { AMapLoader.load({ key: "申請好的Web端開發(fā)者Key", // 申請好的Web端開發(fā)者Key,首次調(diào)用 load 時必填 version: "2.0", // 指定要加載的 JSAPI 的版本,缺省時默認為 1.4.15 plugins: [ "AMap.ToolBar", "AMap.Scale", "AMap.HawkEye", "AMap.MapType", "AMap.Geolocation", "AMap.Geocoder", "AMap.Weather", "AMap.CitySearch", "AMap.InfoWindow", "AMap.Marker", "AMap.Pixel", ], // 需要使用的的插件列表,如比例尺'AMap.Scale'等 }) .then((AMap) => { map.value = new AMap.Map("container", { //設置地圖容器id resizeEnable: true, viewMode: "3D", //是否為3D地圖模式 zoom: 10, //初始化地圖級別 center: locationArr.value, //初始化地圖中心點位置 }); getGeolocation(AMap); getCitySearch(AMap, map.value); }) .catch((e) => { console.log(e); }); } // 瀏覽器定位 const getGeolocation = (AMap: any) => { const geolocation = new AMap.Geolocation({ enableHighAccuracy: true, //是否使用高精度定位,默認:true timeout: 1000, //超過10秒后停止定位,默認:5s position: "RB", //定位按鈕的??课恢? offset: [10, 20], //定位按鈕與設置的??课恢玫钠屏?,默認:[10, 20] zoomToAccuracy: true, //定位成功后是否自動調(diào)整地圖視野到定位點 }); map.value.addControl(geolocation); geolocation.getCurrentPosition(function (status: string, result: any) { if (status == "complete") { onComplete(result); } else { onError(result); } }); }; // IP定位獲取當前城市信息 const getCitySearch = (AMap: any, map: any) => { const citySearch = new AMap.CitySearch(); citySearch.getLocalCity(function ( status: string, result: { city: string; info: string; } ) { if (status === "complete" && result.info === "OK") { console.log( "?? ~ file: map-container.vue:88 ~ getCitySearch ~ result:", result ); // 查詢成功,result即為當前所在城市信息 getWeather(AMap, map, result.city); } }); }; onMounted(() => { initMap(); });
5.通過定位獲取城市名稱、區(qū)域編碼,查詢目標城市/區(qū)域的實時天氣狀況
const getWeather = (AMap: any, map: any, city: string) => { const weather = new AMap.Weather(); weather.getLive( city, function ( err: any, data: { city: string; weather: string; temperature: string; windDirection: string; windPower: string; humidity: string; reportTime: string; } ) { if (!err) { const str = []; str.push("<h4 >實時天氣" + "</h4><hr>"); str.push("<p>城市/區(qū):" + data.city + "</p>"); str.push("<p>天氣:" + data.weather + "</p>"); str.push("<p>溫度:" + data.temperature + "℃</p>"); str.push("<p>風向:" + data.windDirection + "</p>"); str.push("<p>風力:" + data.windPower + " 級</p>"); str.push("<p>空氣濕度:" + data.humidity + "</p>"); str.push("<p>發(fā)布時間:" + data.reportTime + "</p>"); const marker = new AMap.Marker({ map: map, position: map.getCenter(), }); const infoWin = new AMap.InfoWindow({ content: '<div class="info" style="position:inherit;margin-bottom:0;background:#ffffff90;padding:10px">' + str.join("") + '</div><div class="sharp"></div>', isCustom: true, offset: new AMap.Pixel(0, -37), }); infoWin.open(map, marker.getPosition()); marker.on("mouseover", function () { infoWin.open(map, marker.getPosition()); }); } } ); }
完整代碼
<template> <div id="container"></div> </template> <script setup lang="ts"> import AMapLoader from "@amap/amap-jsapi-loader"; import { ref, onMounted, watch, reactive } from "vue"; const props = defineProps({ search: { type: String, default: "杭州市", }, }); const isFalse = ref(false); const map = ref<any>(null); let locationArr = ref<any>(); watch( () => props.search, (newValue) => { console.log("search", newValue); initMap(); } ); function initMap() { AMapLoader.load({ key: "申請好的Web端開發(fā)者Key", // 申請好的Web端開發(fā)者Key,首次調(diào)用 load 時必填 version: "2.0", // 指定要加載的 JSAPI 的版本,缺省時默認為 1.4.15 plugins: [ "AMap.ToolBar", "AMap.Scale", "AMap.HawkEye", "AMap.MapType", "AMap.Geolocation", "AMap.Geocoder", "AMap.Weather", "AMap.CitySearch", "AMap.InfoWindow", "AMap.Marker", "AMap.Pixel", ], // 需要使用的的插件列表,如比例尺'AMap.Scale'等 }) .then((AMap) => { map.value = new AMap.Map("container", { //設置地圖容器id resizeEnable: true, viewMode: "3D", //是否為3D地圖模式 zoom: 10, //初始化地圖級別 center: locationArr.value, //初始化地圖中心點位置 }); getGeolocation(AMap); getCitySearch(AMap, map.value); }) .catch((e) => { console.log(e); }); } // 瀏覽器定位 const getGeolocation = (AMap: any) => { const geolocation = new AMap.Geolocation({ enableHighAccuracy: true, //是否使用高精度定位,默認:true timeout: 1000, //超過10秒后停止定位,默認:5s position: "RB", //定位按鈕的??课恢? offset: [10, 20], //定位按鈕與設置的??课恢玫钠屏浚J:[10, 20] zoomToAccuracy: true, //定位成功后是否自動調(diào)整地圖視野到定位點 }); map.value.addControl(geolocation); geolocation.getCurrentPosition(function (status: string, result: any) { if (status == "complete") { onComplete(result); } else { onError(result); } }); }; // IP定位獲取當前城市信息 const getCitySearch = (AMap: any, map: any) => { const citySearch = new AMap.CitySearch(); citySearch.getLocalCity(function ( status: string, result: { city: string; info: string; } ) { if (status === "complete" && result.info === "OK") { console.log( "?? ~ file: map-container.vue:88 ~ getCitySearch ~ result:", result ); // 查詢成功,result即為當前所在城市信息 getWeather(AMap, map, result.city); } }); }; // 天氣 const getWeather = (AMap: any, map: any, city: string) => { const weather = new AMap.Weather(); weather.getLive( city, function ( err: any, data: { city: string; weather: string; temperature: string; windDirection: string; windPower: string; humidity: string; reportTime: string; } ) { console.log("?? ~ file: map-container.vue:96 ~ .then ~ data:", data); if (!err) { const str = []; str.push("<h4 >實時天氣" + "</h4><hr>"); str.push("<p>城市/區(qū):" + data.city + "</p>"); str.push("<p>天氣:" + data.weather + "</p>"); str.push("<p>溫度:" + data.temperature + "℃</p>"); str.push("<p>風向:" + data.windDirection + "</p>"); str.push("<p>風力:" + data.windPower + " 級</p>"); str.push("<p>空氣濕度:" + data.humidity + "</p>"); str.push("<p>發(fā)布時間:" + data.reportTime + "</p>"); const marker = new AMap.Marker({ map: map, position: map.getCenter(), }); const infoWin = new AMap.InfoWindow({ content: '<div class="info" style="position:inherit;margin-bottom:0;background:#ffffff90;padding:10px">' + str.join("") + '</div><div class="sharp"></div>', isCustom: true, offset: new AMap.Pixel(0, -37), }); infoWin.open(map, marker.getPosition()); marker.on("mouseover", function () { infoWin.open(map, marker.getPosition()); }); } } ); // 未來4天天氣預報 weather.getForecast( city, function (err: any, data: { forecasts: string | any[] }) { console.log( "?? ~ file: map-container.vue:186 ~ getWeather ~ data:", data ); if (err) { return; } var strs = []; for (var i = 0, dayWeather; i < data.forecasts.length; i++) { dayWeather = data.forecasts[i]; strs.push( `<p>${dayWeather.date}  ${dayWeather.dayWeather}  ${dayWeather.nightTemp}~${dayWeather.dayTemp}℃</p><br />` ); } } ); }; function onComplete(data: any) { console.log("?? ~ file: map-container.vue:107 ~ onComplete ~ data:", data); const lngLat = [data.position.lng, data.position.lat]; locationArr.value = lngLat; } function onError(data: any) { console.log("?? ~ file: map-container.vue:113 ~ onError ~ data:", data); // 定位出錯 } onMounted(() => { initMap(); }); </script> <style scoped lang="less"> #container { padding: 0px; margin: 0px; width: 100%; height: 100%; } </style>
到此這篇關于Vue利用高德地圖API實現(xiàn)實時天氣的文章就介紹到這了,更多相關Vue實時天氣內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue實現(xiàn)動態(tài)顯示textarea剩余字數(shù)
這篇文章主要為大家詳細介紹了Vue實現(xiàn)動態(tài)顯示textarea剩余文字數(shù)量,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05vant的Uploader?文件上傳,圖片數(shù)據(jù)回顯問題
這篇文章主要介紹了vant的Uploader?文件上傳,圖片數(shù)據(jù)回顯問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10