微信小程序----map组件实现(获取定位城市天气或者指定城市天气数据)

2021-02-01 11:20:38 浏览数 (2)

效果图

实现原理

采用高德地图微信小程序开发API(getWeather),如果 city 属性的值为空(或者没有city属性),默认返回定位位置的天气数据;如果 city 不为空,则返回 city 指定位置的天气数据。

WXML

代码语言:javascript复制
<view class="map-weather">
  <view><text>城市:</text>{{address}}</view>
  <view><text>天气:</text>{{weather}}</view>
  <view><text>温度:</text>{{temperature}}℃</view>
  <view><text>风力:</text>{{windpower}}级</view>
  <view><text>湿度:</text>{{humidity}}%</view>
  <view><text>风向:</text>{{winddirection}}</view>
</view>

JS

代码语言:javascript复制
const app = getApp();
const amap = app.data.amap;
const key = app.data.key;
Page({
  data: {
    address:'',
    weather:'',
    temperature:'',
    humidity:'',
    windpower:'',
    winddirection:''
  },
  onLoad(){
    var _this = this;
    var myAmap = new amap.AMapWX({ key: key });
    myAmap.getWeather({
      type: 'live',
      success(data) {
        if(data.city){
          _this.setData({
            address: data.liveData.city,
            humidity: data.liveData.humidity,
            temperature: data.liveData.temperature,
            weather: data.liveData.weather,
            winddirection: data.liveData.winddirection,
            windpower: data.liveData.windpower
          })
        }
      },
      fail() {
        wx.showToast({ title: '失败!' })
      }
    })
  }
})

WXSS

代码语言:javascript复制
page{
  width: 100%;
  height: 100%;
  background-color: lightseagreen;
  color:#fff;
}
.map-weather{
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translateY(-50%) translateX(-50%);
}
.map-weather view{
  height: 100rpx;
  line-height: 100rpx;
  font-size: 30rpx;
}

0 人点赞