赞
踩
流程如下:
1、安装百度地图
先在根目录上(或者public中)的index.html文件的body标签中加入
<script src="https://api.map.baidu.com/api?v=3.0&ak=你在百度地图申请的Ak"></script>
然后,新建一个bdmap.js文件,放入以下内容,并且在你要使用的页面中引入,
- export default {
- init: function () {
- const AK = "EAG3waLsHfeWew8ZjxlvQgvxuqXY5moB"; //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获取城市天气状况
- <template>
- <div></div>
- </template>
-
- <script>
- import { ref, reactive, onMounted } from "vue";
- import myBMap from "./bmap.js"; // 引入刚才创建的bmap.js文件
- import axios from "axios";
- export default {
- //props: {},
- components: {},
- 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);
- console.log(res.data.location[0]);
- });
- };
-
- // 获取天气
- 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;
- console.log(res.data, 1213);
- });
- };
-
- onMounted(async () => {
- getCity(); // 获取城市
- // var result = await axios.get(
- // "http://wthrcdn.etouch.cn/weather_mini?city=" + "杭州"
- // );
- // console.log(result.data.data.forecast);
- });
-
- return {
- getWeather,
- getLocationId,
- getCity,
- weather,
- temperature,
- };
- },
- };
- </script>
-
- <style scoped lang="less"></style>
可以尝试复制代码 去获取你想要得到的信息
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。