Vue利用高德地圖API實(shí)現(xiàn)實(shí)時(shí)天氣
前言
閑來(lái)無(wú)事,利用摸魚時(shí)間實(shí)現(xiàn)實(shí)時(shí)天氣的小功能
目錄
- 登錄 高德開放平臺(tái)控制臺(tái),如果沒有開發(fā)者賬號(hào),請(qǐng) 注冊(cè)開發(fā)者。
- 創(chuàng)建 key,進(jìn)入應(yīng)用管理,創(chuàng)建新應(yīng)用,新應(yīng)用中添加 key,服務(wù)平臺(tái)選擇 Web端(JS API)。
- 獲取 key 和密鑰
- 獲取當(dāng)前城市定位
- 通過定位獲取城市名稱、區(qū)域編碼,查詢目標(biāo)城市/區(qū)域的實(shí)時(shí)天氣狀況
效果圖
這里樣式我就不做處理了,地圖可以不用做展示,只需要拿到獲取到天氣的結(jié)果,結(jié)合自己的樣式展示就可以了,未來(lái)天氣可以結(jié)合echarts進(jìn)行展示,頁(yè)面效果更佳

實(shí)現(xiàn)
1.登錄高德開放平臺(tái)控制臺(tái)

2.創(chuàng)建 key
這里應(yīng)用名稱可以隨便?。▊€(gè)人建議功能名稱或者項(xiàng)目稱)


3.獲取 key 和密鑰

4.獲取當(dāng)前城市定位
首先,先安裝依賴
npm install @amap/amap-jsapi-loader --save
或者
pnpm add @amap/amap-jsapi-loader --save
頁(yè)面使用時(shí)引入即可 import AMapLoader from "@amap/amap-jsapi-loader"
/** 1. 調(diào)用AMapLoader.load方法,通過傳入一個(gè)對(duì)象作為參數(shù)來(lái)指定加載地圖時(shí)的配置信息。
* - key: 申請(qǐng)好的Web端開發(fā)者Key,是必填項(xiàng),用于授權(quán)您的應(yīng)用程序使用高德地圖API。
* - version: 指定要加載的JSAPI版本,不指定時(shí)默認(rèn)為1.4.15。
* - plugins: 需要使用的插件列表,如比例尺、縮放控件等。
*/
function initMap() {
AMapLoader.load({
key: "申請(qǐng)好的Web端開發(fā)者Key", // 申請(qǐng)好的Web端開發(fā)者Key,首次調(diào)用 load 時(shí)必填
version: "2.0", // 指定要加載的 JSAPI 的版本,缺省時(shí)默認(rèn)為 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", {
//設(shè)置地圖容器id
resizeEnable: true,
viewMode: "3D", //是否為3D地圖模式
zoom: 10, //初始化地圖級(jí)別
center: locationArr.value, //初始化地圖中心點(diǎn)位置
});
getGeolocation(AMap);
getCitySearch(AMap, map.value);
})
.catch((e) => {
console.log(e);
});
}
// 瀏覽器定位
const getGeolocation = (AMap: any) => {
const geolocation = new AMap.Geolocation({
enableHighAccuracy: true, //是否使用高精度定位,默認(rèn):true
timeout: 1000, //超過10秒后停止定位,默認(rèn):5s
position: "RB", //定位按鈕的??课恢?
offset: [10, 20], //定位按鈕與設(shè)置的停靠位置的偏移量,默認(rèn):[10, 20]
zoomToAccuracy: true, //定位成功后是否自動(dòng)調(diào)整地圖視野到定位點(diǎn)
});
map.value.addControl(geolocation);
geolocation.getCurrentPosition(function (status: string, result: any) {
if (status == "complete") {
onComplete(result);
} else {
onError(result);
}
});
};
// IP定位獲取當(dāng)前城市信息
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即為當(dāng)前所在城市信息
getWeather(AMap, map, result.city);
}
});
};
onMounted(() => {
initMap();
});
5.通過定位獲取城市名稱、區(qū)域編碼,查詢目標(biāo)城市/區(qū)域的實(shí)時(shí)天氣狀況
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 >實(shí)時(shí)天氣" + "</h4><hr>");
str.push("<p>城市/區(qū):" + data.city + "</p>");
str.push("<p>天氣:" + data.weather + "</p>");
str.push("<p>溫度:" + data.temperature + "℃</p>");
str.push("<p>風(fēng)向:" + data.windDirection + "</p>");
str.push("<p>風(fēng)力:" + data.windPower + " 級(jí)</p>");
str.push("<p>空氣濕度:" + data.humidity + "</p>");
str.push("<p>發(fā)布時(shí)間:" + 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: "申請(qǐng)好的Web端開發(fā)者Key", // 申請(qǐng)好的Web端開發(fā)者Key,首次調(diào)用 load 時(shí)必填
version: "2.0", // 指定要加載的 JSAPI 的版本,缺省時(shí)默認(rèn)為 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", {
//設(shè)置地圖容器id
resizeEnable: true,
viewMode: "3D", //是否為3D地圖模式
zoom: 10, //初始化地圖級(jí)別
center: locationArr.value, //初始化地圖中心點(diǎn)位置
});
getGeolocation(AMap);
getCitySearch(AMap, map.value);
})
.catch((e) => {
console.log(e);
});
}
// 瀏覽器定位
const getGeolocation = (AMap: any) => {
const geolocation = new AMap.Geolocation({
enableHighAccuracy: true, //是否使用高精度定位,默認(rèn):true
timeout: 1000, //超過10秒后停止定位,默認(rèn):5s
position: "RB", //定位按鈕的??课恢?
offset: [10, 20], //定位按鈕與設(shè)置的停靠位置的偏移量,默認(rèn):[10, 20]
zoomToAccuracy: true, //定位成功后是否自動(dòng)調(diào)整地圖視野到定位點(diǎn)
});
map.value.addControl(geolocation);
geolocation.getCurrentPosition(function (status: string, result: any) {
if (status == "complete") {
onComplete(result);
} else {
onError(result);
}
});
};
// IP定位獲取當(dāng)前城市信息
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即為當(dāng)前所在城市信息
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 >實(shí)時(shí)天氣" + "</h4><hr>");
str.push("<p>城市/區(qū):" + data.city + "</p>");
str.push("<p>天氣:" + data.weather + "</p>");
str.push("<p>溫度:" + data.temperature + "℃</p>");
str.push("<p>風(fēng)向:" + data.windDirection + "</p>");
str.push("<p>風(fēng)力:" + data.windPower + " 級(jí)</p>");
str.push("<p>空氣濕度:" + data.humidity + "</p>");
str.push("<p>發(fā)布時(shí)間:" + 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());
});
}
}
);
// 未來(lái)4天天氣預(yù)報(bào)
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);
// 定位出錯(cuò)
}
onMounted(() => {
initMap();
});
</script>
<style scoped lang="less">
#container {
padding: 0px;
margin: 0px;
width: 100%;
height: 100%;
}
</style>
到此這篇關(guān)于Vue利用高德地圖API實(shí)現(xiàn)實(shí)時(shí)天氣的文章就介紹到這了,更多相關(guān)Vue實(shí)時(shí)天氣內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用electron-builder將項(xiàng)目打包成桌面程序的詳細(xì)教程
這篇文章主要介紹了使用electron-builder把web端的項(xiàng)目打包生成桌面程序,并可安裝程序,文中通過代碼示例和圖文結(jié)合的方式給大家介紹的非常詳細(xì),具有一定的參考價(jià)值,需要的朋友可以參考下2024-08-08
vite項(xiàng)目import.meta.env如何能獲取非VITE開發(fā)的環(huán)境變量
這篇文章主要介紹了vite項(xiàng)目import.meta.env如何能獲取非VITE開發(fā)的環(huán)境變量問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
vue基于Echarts的拖拽數(shù)據(jù)可視化功能實(shí)現(xiàn)
這篇文章主要給大家介紹了關(guān)于vue基于Echars的拖拽數(shù)據(jù)可視化功能實(shí)現(xiàn)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
vue create、vue webpack init創(chuàng)建vue項(xiàng)目產(chǎn)生的項(xiàng)目文件的區(qū)別
這篇文章主要介紹了vue create、vue webpack init創(chuàng)建vue項(xiàng)目產(chǎn)生的項(xiàng)目文件的區(qū)別及說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11
vue之保留小數(shù)點(diǎn)兩位小數(shù) 使用filters(過濾器)
這篇文章主要介紹了vue之保留小數(shù)點(diǎn)兩位小數(shù) 使用filters(過濾器),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11

