web前端开发

uniapp小程序获取定位和天气

2020-08-08  本文已影响0人  爱学习的新一
<template>
    <view>
        <!-- 定位城市 -->
        <view class="addr">{{ city }}</view>
        <!-- 温度 -->
        <view class="temperature">{{ temperature }}℃</view>
    </view>
</template>
<script>
//高德SDKjs
import amap from '@/common/SDK/amap-wx.js';
export default {
    data() {
        return {
            key:'自己申请的key',//小程序定位key
            webkey:'自己申请的key',//获取天气key,key的服务不同所以用两个
            city: '',//城市
            temperature:''//气温
        };
    },
    methods:{
        tian(e){
              uni.request({
                  url: 'https://restapi.amap.com/v3/weather/weatherInfo',//高德地图查询天气
                  method :'GET',
                  data:{
                      key:this.webkey,
                      city:e,
                       },
                  success: (res) => {
                      this.temperature = res.data.lives[0].temperature
                      console.log(this.temperature)
                  }
              });
        }
    },
    onLoad() {
        this.amapPlugin = new amap.AMapWX({
            //高德地图小程序KEY,替换为自己的KEY,参考:http://ask.dcloud.net.cn/article/35070
                        //https://lbs.amap.com/api/wx/gettingstarted
            key: this.key
        });
        //定位地址
        this.amapPlugin.getRegeo({
            success: (res)=> {
                //this.city = data[0].regeocodeData.addressComponent.city.replace(/市/g, ''); //把"市"去掉
                this.city = res[0].regeocodeData.addressComponent.city; 
                let adData = res[0].regeocodeData.addressComponent.adcode//拿到城市的编码用于查寻天气
                //使用说明https://lbs.amap.com/api/webservice/guide/api/weatherinfo/#instructions
                console.log( adData) 
                 this.tian(adData)
            }
        });
    }
}
</script>
<style>



</style>

如果你有更好的方式欢迎给我留言

上一篇 下一篇

猜你喜欢

热点阅读