Vue利用高德地图API实现实时天气

 更新时间:2023年12月27日 11:44:41   作者:快乐是Happy  
这篇文章主要为大家详细介绍了Vue如何利用高德地图API实现实时天气,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

前言

闲来无事,利用摸鱼时间实现实时天气的小功能

目录

  • 登录 高德开放平台控制台,如果没有开发者账号,请 注册开发者
  • 创建 key,进入应用管理,创建新应用,新应用中添加 key,服务平台选择 Web端(JS API)。
  • 获取 key 和密钥
  • 获取当前城市定位
  • 通过定位获取城市名称、区域编码,查询目标城市/区域的实时天气状况

效果图

这里样式我就不做处理了,地图可以不用做展示,只需要拿到获取到天气的结果,结合自己的样式展示就可以了,未来天气可以结合echarts进行展示,页面效果更佳

实现

1.登录高德开放平台控制台

2.创建 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.  调用AMapLoader.load方法,通过传入一个对象作为参数来指定加载地图时的配置信息。
   *  -   key: 申请好的Web端开发者Key,是必填项,用于授权您的应用程序使用高德地图API。
   *  -   version: 指定要加载的JSAPI版本,不指定时默认为1.4.15。
   *  -   plugins: 需要使用的插件列表,如比例尺、缩放控件等。
   */
  function initMap() {
  AMapLoader.load({
    key: "申请好的Web端开发者Key", // 申请好的Web端开发者Key,首次调用 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, //定位成功后是否自动调整地图视野到定位点
  });
  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.通过定位获取城市名称、区域编码,查询目标城市/区域的实时天气状况

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>城市/区:" + 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>发布时间:" + 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端开发者Key", // 申请好的Web端开发者Key,首次调用 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, //定位成功后是否自动调整地图视野到定位点
  });
  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>城市/区:" + 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>发布时间:" + 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}&nbsp&nbsp${dayWeather.dayWeather}&nbsp&nbsp${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实现实时天气的文章就介绍到这了,更多相关Vue实时天气内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 解决vue打包之后静态资源图片失效的问题

    解决vue打包之后静态资源图片失效的问题

    下面小编就为大家分享一篇解决vue打包之后静态资源图片失效的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-02-02
  • 详解vue 中 scoped 样式作用域的规则

    详解vue 中 scoped 样式作用域的规则

    这篇文章主要介绍了vue 中 scoped 样式作用域的规则,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-09-09
  • Vue实现动态显示textarea剩余字数

    Vue实现动态显示textarea剩余字数

    这篇文章主要为大家详细介绍了Vue实现动态显示textarea剩余文字数量,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-05-05
  • element-ui中按需引入的实现

    element-ui中按需引入的实现

    这篇文章主要介绍了element-ui中按需引入的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-12-12
  • vue3 hook自动导入原理及使用

    vue3 hook自动导入原理及使用

    最近学习了hooks,特地写一篇文章加深一下印象,下面这篇文章主要给大家介绍了关于vue3 hook自动导入原理及使用的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-10-10
  • 教你一招解决vue页面自适应布局

    教你一招解决vue页面自适应布局

    在前端开发的时候经常会遇到这样的困惑,设计师给你的设计稿的尺寸和页面的尺寸不一致,导致了页面无法正常显示,下面这篇文章主要给大家介绍了关于一招解决vue页面自适应布局的相关资料,需要的朋友可以参考下
    2022-07-07
  • vue项目实现中英文切换的详细步骤

    vue项目实现中英文切换的详细步骤

    这篇文章主要给大家介绍了关于vue项目实现中英文切换的详细步骤,项目中经常有中英文切换的功能,接下来就简单实现以下这个功能,文中通过代码介绍的非常详细,需要的朋友可以参考
    2023-11-11
  • 利用vue+turn.js实现翻书效果完整实例

    利用vue+turn.js实现翻书效果完整实例

    这篇文章主要给大家介绍了关于利用vue+turn.js实现翻书效果的相关资料,turn.js是使用了jquery书写的,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2024-01-01
  • vue 系列——vue2-webpack2框架搭建踩坑之路

    vue 系列——vue2-webpack2框架搭建踩坑之路

    本文从零搭建vue项目,给大家分享了我的vue2-webpack2框架搭建踩坑之路,需要的朋友可以参考下
    2017-12-12
  • vant的Uploader 文件上传,图片数据回显问题

    vant的Uploader 文件上传,图片数据回显问题

    这篇文章主要介绍了vant的Uploader 文件上传,图片数据回显问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-10-10

最新评论