流程如下:
1、安装百度地图
先在根目录上(或者public中)的index.html文件的body标签中加入
<script src="https://api.map.baidu.com/api?v=3.0&ak=你在百度地图申请的Ak"></script>
<script type="text/javascript"
src="https://webapi.amap.com/maps?v=1.3&key=你申请的key"></script>
在使用let myCity = new BMap.LocalCity();的时候报错了,BMap找不到,也试过了网上说的
let myCity = new window.BMap.LocalCity()还是不行;但是在网上找到了个方法给解决了,
const BMap = (window as any).BMapGL;
就可以了,
然后,新建一个bmap.js文件,放入以下内容,并且在你要使用的页面中引入,
export default {
init: function () {
const AK = "5ieMMexWmzB9jivTq6oCRX9j&callback"; //AK
const BMap_URL =
"https://api.map.baidu.com/api?v=2.0&ak=" +
AK +
"&s=1&callback=onBMapCallback";
return new Promise((resolve, reject) => {
// 如果已加载直接返回
if (typeof BMap !== "undefined") {
resolve(BMap);
return true;
}
// 百度地图异步加载回调处理
window.onBMapCallback = function () {
resolve(BMap);
};
// 插入script脚本
let scriptNode = document.createElement("script");
// scriptNode.setAttribute(type, 'text/javascript');
scriptNode.setAttribute("src", BMap_URL);
document.body.appendChild(scriptNode);
});
},
};
2、结合浏览器获取你所在城市位置
3、通过位置获取城市ID
4、通过城市ID获取城市天气状况(这三个步骤都在一个页面实现的,所以就直接上代码了)
<script lang="ts">
import myBMap from "./bmap.js"; // 引入刚才创建的bmap.js文件
import axios from "axios";
import { defineComponent, ref, onMounted } from "vue";
export default defineComponent({
setup() {
let weather = ref(""); // 天气
let temperature = ref(""); // 温度
// 结合浏览器获取城市位置(我只需要获取省和市,具体看个人需求)
const getCity = () => {
const BMap = (window as any).BMapGL;
myBMap.init().then((BMap) => {
let myCity = new BMap.LocalCity();
myCity.get(
(result) => {
let geoc = new BMap.Geocoder();
geoc.getLocation(result.center, (res) => {
// 位置信息
console.log("位置", res.addressComponents);
getLocationId(
res.addressComponents.province,
res.addressComponents.city
);
});
},
{ enableHighAccuracy: true }
);
});
};
// 获取城市id
const getLocationId = (province, city) => {
axios({
method: "get",
url:
"https://geoapi.qweather.com/v2/city/lookup?key=56a14978f76747a8897384f7bef56c20&adm=" +
province +
"&location=" +
city,
}).then((res) => {
getWeather(res.data.location[0].id);
});
};
// 获取天气
const getWeather = (id) => {
axios({
method: "get",
url:
"https://devapi.qweather.com/v7/weather/now?key=56a14978f76747a8897384f7bef56c20&location=" +
id,
}).then((res) => {
temperature.value = res.data.now.temp;
weather.value = res.data.now.text;
});
};
onMounted(() => {
getCity(); // 获取城市
});
return {
getWeather,
getLocationId,
getCity,
weather,
temperature,
};
},
});
</script>
位置信息打印出来是这样的