vue3+高德地图天气预报

今天更新一下如何利用vue3和高德地图中的天气api来实现点击某个地区获取其天气情况及未来几天的天气预报效果。强调一下本次是通过vue3实现的具体效果。

1.搭建vue3框架,这个不进行详细说明

2.NPM 安装 Loader 

npm i @amap/amap-jsapi-loader --save

3.新建 map.vue 文件,这里我放置在名为views的文件夹中,说明一下需要用到router路由

4.创建地图容器:在 map.vue 地图组件中创建 <div> 标签作为地图容器 ,并设置地图容器的 id 属性为 container。

<template>
    <div id="container"></div>
</template>

5.设置地图容器样式

<style lang='less' scoped>
#container{
    width: 100%;
    height: 600px;
    margin: 0;
    padding: 0;
    position: relative;
}
</style>

6.引入JS API  Loader :在地图组件 map.vue 中引入 amap-jsapi-loader 

import AMapLoader from "@amap/amap-jsapi-loader"

7.初始化并创建地图

import { onMounted, shallowRef} from 'vue'
const map = shallowRef(null);//定义一个map对象
//初始化地图
const initMap=()=>{
    window._AMapSecurityConfig = {
            securityJsCode:'你自己的安全密钥',//安全密钥
    }
    AMapLoader.load({
        key:'你的密钥',  //设置密钥
        version:"2.0",//版本
        plugins:['AMap.Weather','AMap.Marker'],
    }).then((AMap)=>{
    map.value = new AMap.Map("container",{
            viewMode:"3D",//地图模式
            pitch:20,//角度
            zoom:11,//缩放,缩放级别在3-15
            zooms:[2,22],
            mapStyle: 'amap://styles/blue', //设置地图的显示样式
            center:[118.88064,32.11352],//初始化地图中心点位置
    });
}).catch(e=>{
        console.log(e);
})
onMounted(()=>{
    initMap()
})

8.获取天气

<div class="info" v-show="showFore">
        <h4>预报天气</h4>
        <p id='forecast'></p>
</div>

 第一种方式

AMap.plugin('AMap.Weather', ()=>{
            let weather = new AMap.Weather();//引入地图插件
            weather.getLive('栖霞区', (err, data)=> {
                // console.log(err, data);
                if (!err) {
                    let str = [];
                    str.push("<h4 >实时天气</h4>");
                    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>');
                    console.log(str)
                    let marker = new AMap.Marker({
                        map: map, 
                        position: map.value.getCenter(),
                        icon: 'https://webapi.amap.com/images/car.png',
                        autoRotation: true, // 自动旋转
                        angle: 90 // 图片旋转角度
                    });
                    marker.on('mouseover', (e)=> {
                        let infoWin = new AMap.InfoWindow({
                            content:'<div class="info" style="position:inherit;margin-bottom:0;width:240px;height:180px;background: rgba(40, 101, 215,0.5);color:#fff;border-radius: 5px;display:flex;flex-direction: column;justify-content: space-around;">'
                                +str.join('')+'</div>',
                            isCustom:true,
                            offset: new AMap.Pixel(0, -20)
                        });
                        infoWin.open(map.value, e.target.getPosition());
                        showFore.value=true
                    });
                    marker.on('mouseout',()=>{
                        // timer = setTimeout(()=> {
                        // }, 500)
                    })
                    map.value.add(marker);
                }
            })
            // console.log(weather)
            //未来4天天气预报
            weather.getForecast('栖霞区', (err, data)=>{
                console.log(err, data)
                if (err) {return;}
                let str = [];
                for (let i = 0,dayWeather; i < data.forecasts.length; i++) {
                    dayWeather = data.forecasts[i];
                    str.push(dayWeather.date+' <span class="weather">'+dayWeather.dayWeather+'</span> '+ dayWeather.nightTemp + '~' + dayWeather.dayTemp + '℃');
                }
                console.log(str,'未来天气')
                document.getElementById('forecast').innerHTML = str.join('<br>');
            });
        })

 第二种方式

AMap.plugin('AMap.Weather', ()=>{
            let weather = new AMap.Weather();//引入地图插件
            weather.getLive('栖霞区', (err, data)=> {
                // console.log(err, data);
                if (!err) {
                    let str = [];
                    str.push("<h4 >实时天气</h4>");
                    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>');
                    console.log(str)
                    //添加标记
                    let marker = new AMap.Marker({
                        map: map, 
                        position: map.value.getCenter(),
                        icon: 'https://webapi.amap.com/images/car.png',
                        autoRotation: true, // 自动旋转
                        angle: 90 // 图片旋转角度
                    });
                    //自定义信息窗体
                    let infoWin = new AMap.InfoWindow({
                            content:'<div class="info" style="position:inherit;margin-bottom:0;width:240px;height:180px;background: rgba(40, 101, 215,0.5);color:#fff;border-radius: 5px;display:flex;flex-direction: column;justify-content: space-around;">'
                                +str.join('')+'</div>',
                            isCustom:true,
                            offset: new AMap.Pixel(0, -20)
                    });
                    marker.on('mouseover', infoOpen);//鼠标经过打开信息窗体
                    marker.on('mouseout', infoClose);//鼠标离开关闭信息窗体
                    function infoOpen(e){
                        infoWin.open(map.value, e.target.getPosition());
                        showFore.value=true
                    }
                    function infoClose(e){
                        infoWin.close(map.value, e.target.getPosition());
                        showFore.value=false
                    }
                    map.value.add(marker);
                }
            })
            //未来4天天气预报
            weather.getForecast('栖霞区', (err, data)=>{
                console.log(err, data)
                if (err) {return;}
                let str = [];
                for (let i = 0,dayWeather; i < data.forecasts.length; i++) {
                    dayWeather = data.forecasts[i];
                    str.push(dayWeather.date+' <span class="weather">'+dayWeather.dayWeather+'</span> '+ dayWeather.nightTemp + '~' + dayWeather.dayTemp + '℃');
                }
                console.log(str,'未来天气')
                document.getElementById('forecast').innerHTML = str.join('<br>');
            });
        })

9.全部代码

<template>
    <div id="container"></div>
    <div class="info" v-show="showFore">
        <h4>预报天气</h4>
        <p id='forecast'></p>
    </div>
</template>

<script setup>
import AMapLoader from "@amap/amap-jsapi-loader"
import { onMounted, shallowRef,ref} from 'vue'
const showFore=ref(false)
const map = shallowRef(null);//定义一个map对象
//初始化地图
const initMap=()=>{
    window._AMapSecurityConfig = {
            securityJsCode:'a500c9a70ad5d03db8bf3897fd9990f9',//安全密钥
    }
    AMapLoader.load({
        key:'489d0a338a7a792a72327d1fbd470c8a',  //设置密钥
        version:"2.0",//版本
        // plugins:['AMap.Geolocation','AMap.ToolBar','AMap.HawkEye','AMap.MapType','AMap.Weather','AMap.Marker'],
    }).then((AMap)=>{
        map.value = new AMap.Map("container",{
            viewMode:"3D",//地图模式
            pitch:20,//角度
            zoom:11,//缩放,缩放级别在3-15
            zooms:[2,22],
            mapStyle: 'amap://styles/blue', //设置地图的显示样式
            center:[118.88064,32.11352],//初始化地图中心点位置
        });
        AMap.plugin('AMap.Weather', ()=>{
            let weather = new AMap.Weather();//引入地图插件
            weather.getLive('栖霞区', (err, data)=> {
                // console.log(err, data);
                if (!err) {
                    let str = [];
                    str.push("<h4 >实时天气</h4>");
                    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>');
                    console.log(str)
                    //添加标记
                    let marker = new AMap.Marker({
                        map: map, 
                        position: map.value.getCenter(),
                        icon: 'https://webapi.amap.com/images/car.png',
                        autoRotation: true, // 自动旋转
                        angle: 90 // 图片旋转角度
                    });
                    //自定义信息窗体
                    let infoWin = new AMap.InfoWindow({
                            content:'<div class="info" style="position:inherit;margin-bottom:0;width:240px;height:180px;background: rgba(40, 101, 215,0.5);color:#fff;border-radius: 5px;display:flex;flex-direction: column;justify-content: space-around;">'
                                +str.join('')+'</div>',
                            isCustom:true,
                            offset: new AMap.Pixel(0, -20)
                    });
                    marker.on('mouseover', infoOpen);//鼠标经过打开信息窗体
                    marker.on('mouseout', infoClose);//鼠标离开关闭信息窗体
                    function infoOpen(e){
                        infoWin.open(map.value, e.target.getPosition());
                        showFore.value=true
                    }
                    function infoClose(e){
                        infoWin.close(map.value, e.target.getPosition());
                        showFore.value=false
                    }
                    map.value.add(marker);
                }
            })
            //未来4天天气预报
            weather.getForecast('栖霞区', (err, data)=>{
                console.log(err, data)
                if (err) {return;}
                let str = [];
                for (let i = 0,dayWeather; i < data.forecasts.length; i++) {
                    dayWeather = data.forecasts[i];
                    str.push(dayWeather.date+' <span class="weather">'+dayWeather.dayWeather+'</span> '+ dayWeather.nightTemp + '~' + dayWeather.dayTemp + '℃');
                }
                console.log(str,'未来天气')
                document.getElementById('forecast').innerHTML = str.join('<br>');
            });
        })
    }).catch(e=>{
        console.log(e);
    })
}
onMounted(()=>{
    initMap()
})
</script>

<style lang='less' scoped>
#container{
    width: 100%;
    height: 600px;
    margin: 0;
    padding: 0;
    position: relative;
}
.info{
    width:220px;
    height:140px;
    background: rgba(40, 101, 215,0.5);
    color:#fff;
    border-radius: 5px;
    display:flex;
    flex-direction: column;
    justify-content: space-around;
    position: absolute;
    top: 10%;
    left: 60%;
    h4{
        font-size: 16px;
        text-align: center;
        height: 16px;
        &::after{
            content: '';
            width: 200px;
            height: 1px;
            border-bottom: 1px solid #fff;
            display: inline-block;
        }
    }
    p{
        font-size: 14px;
    }
}
</style>

10.效果展示

  • 1
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用高德地图 JavaScript API 中的 AMap.Geolocation 对象来确认用户当前的位置。具体步骤如下: 1. 引入高德地图 JavaScript API: ```html <script src="https://webapi.amap.com/maps?v=1.4.15&key=您的高德地图API Key"></script> ``` 2. 创建地图实例: ```javascript var map = new AMap.Map('map-container', { zoom: 13 }); ``` 3. 创建 AMap.Geolocation 实例: ```javascript var geolocation = new AMap.Geolocation({ enableHighAccuracy: true, // 是否使用高精度定位,默认为false timeout: 10000, // 超过10秒后停止定位,默认为5s maximumAge: 0, // 定位结果缓存0毫秒,默认值为0 convert: true, // 是否使用坐标转换服务,默认为true showButton: true, // 是否显示定位按钮,默认为false buttonPosition: 'RB', // 定位按钮的位置,默认为'LB',左下角 buttonOffset: new AMap.Pixel(10, 10), // 定位按钮距离地图边缘的偏移量 showMarker: true, // 是否显示定位点,默认为true markerOptions: { icon: new AMap.Icon({ size: new AMap.Size(24, 24), image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png', imageSize: new AMap.Size(24, 24) }) }, // 定位点的图标样式 showCircle: true, // 是否显示定位精度圆,默认为true circleOptions: { strokeColor: '#0093FF', fillColor: '#0093FF', strokeWeight: 1, fillOpacity: 0.3 } // 定位精度圆的样式 }); ``` 4. 调用 AMap.Geolocation 的 getCurrentPosition 方法进行定位: ```javascript geolocation.getCurrentPosition(function(status, result) { if (status === 'complete') { // 定位成功 var position = result.position; // 获取定位结果的经纬度信息 map.setCenter(position); // 将地图中心移动到定位结果的位置 } else { // 定位失败 console.log('定位失败:' + result.message); } }); ``` 以上代码将会在地图中心显示当前位置的定位点,并在定位精度圆内显示精度范围。 注意:在使用高德地图 JavaScript API 进行地图开发时,需要在高德开放平台申请 API Key 并进行授权。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值