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

實(shí)現(xiàn)
1.登錄高德開(kāi)放平臺(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方法,通過(guò)傳入一個(gè)對(duì)象作為參數(shù)來(lái)指定加載地圖時(shí)的配置信息。
* - key: 申請(qǐng)好的Web端開(kāi)發(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端開(kāi)發(fā)者Key", // 申請(qǐng)好的Web端開(kāi)發(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, //超過(guò)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.通過(guò)定位獲取城市名稱、區(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端開(kāi)發(fā)者Key", // 申請(qǐng)好的Web端開(kāi)發(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, //超過(guò)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)文章
解決vue打包之后靜態(tài)資源圖片失效的問(wèn)題
下面小編就為大家分享一篇解決vue打包之后靜態(tài)資源圖片失效的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-02-02
Vue實(shí)現(xiàn)動(dòng)態(tài)顯示textarea剩余字?jǐn)?shù)
這篇文章主要為大家詳細(xì)介紹了Vue實(shí)現(xiàn)動(dòng)態(tài)顯示textarea剩余文字?jǐn)?shù)量,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05
vue項(xiàng)目實(shí)現(xiàn)中英文切換的詳細(xì)步驟
這篇文章主要給大家介紹了關(guān)于vue項(xiàng)目實(shí)現(xiàn)中英文切換的詳細(xì)步驟,項(xiàng)目中經(jīng)常有中英文切換的功能,接下來(lái)就簡(jiǎn)單實(shí)現(xiàn)以下這個(gè)功能,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考2023-11-11
利用vue+turn.js實(shí)現(xiàn)翻書(shū)效果完整實(shí)例
這篇文章主要給大家介紹了關(guān)于利用vue+turn.js實(shí)現(xiàn)翻書(shū)效果的相關(guān)資料,turn.js是使用了jquery書(shū)寫(xiě)的,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01
vant的Uploader?文件上傳,圖片數(shù)據(jù)回顯問(wèn)題
這篇文章主要介紹了vant的Uploader?文件上傳,圖片數(shù)據(jù)回顯問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10

