vue 高德地图 天气预报 自动获取用户ip进行定位

<template>
  <div>
    <Card :style="{height : panelHeight + 'px'}">
      <div class="weather-contain">
        <img :src="weatherIcon" style="margin-left:10px;height:55px;width:55px;" />
        <div class="weather-right-panel">
          <div class="weather-simple">
            <div class="weather-temperature" @click="linkToOther()">{{weatherInfo.temperature}}</div>
            <div style="padding-top:3px;line-height:1.3;">
              <div>℃</div>
              <div>{{weatherInfo.weather}}</div>
            </div>
            <div class="weather-quality">{{weatherInfo.city}}</div>
          </div>
          <!-- <div class="weather-desc">{{weatherInfo.nightTemp}}℃ ~ {{weatherInfo.dayTemp}}℃ {{weatherInfo.weather}} {{weatherInfo.windDirection}}风{{weatherInfo.windPower}}级 空气湿度{{weatherInfo.humidity}}</div> -->
          <div class="weather-desc">{{weatherInfo.nightTemp}}℃ ~ {{weatherInfo.dayTemp}}℃ {{weatherInfo.windDirection}}风{{weatherInfo.windPower}}级</div>
        </div>
      </div>
    </Card>
  </div>
</template>
<script>
import AMap from 'AMap'
export default {
  data() {
    return {
      sun: require('@/assets/images/common/weather-sun.png'),
      cloud: require('@/assets/images/common/weather-cloud.png'), // 多云
      cloudy: require('@/assets/images/common/weather-cloudy.png'), // 阴
      dust: require('@/assets/images/common/weather-dust.png'), // 沙尘
      haze: require('@/assets/images/common/weather-haze.png'), // 雾霾
      hail: require('@/assets/images/common/weather-hail.png'), // 冰雹
      rain: require('@/assets/images/common/weather-rain.png'), // 雨
      rainsnow: require('@/assets/images/common/weather-rainsnow.png'), // 雨夹雪
      ray: require('@/assets/images/common/weather-ray.png'), // 雷雨
      snow: require('@/assets/images/common/weather-snow.png'), // 雪
      weatherIcon: null,
      weatherInfo: {
        temperature: '', // 温度
        weather: '', // 天气
        city: '', // 城市
        nightTemp: '', // 夜间温度
        dayTemp: '', // 日间温度
        windDirection: '', // 风向
        windPower: '', // 风力
        humidity: '' // 湿度
      }
    }
  },
  props: {
    panelHeight: {
      type: Number,
      default: 350
    }
  },
  mounted() {
    this.initWeather()
  },
  methods: {
    // 高德地图的写法,首先获取定位,因为天气是基于用户定位的
    getCity() {
      return new Promise(function(resolve, reject) {
        AMap.plugin('AMap.CitySearch', function() {
          var citysearch = new AMap.CitySearch()
          // 自动获取用户IP,返回当前城市
          citysearch.getLocalCity(function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
              if (result && result.city && result.bounds) {
                resolve(result.city)
              }
            } else {
              this.$Message.error('定位当前城市失败')
              reject(result.info)
            }
          })
        })
      })
    },
    async initWeather() {
      // 获取天气
      let $self = this
      let countyInfo = await $self.getCity() // 获取定位的城市
      AMap.plugin('AMap.Weather', function() {
        var weather = new AMap.Weather()
        // 查询实时天气信息, 查询的城市到行政级别的城市,如朝阳区、杭州市
        weather.getLive(countyInfo, function(err, data) {
          if (!err) {
            $self.weatherInfo.city = data.city
            $self.weatherInfo.humidity = data.humidity
            $self.weatherInfo.temperature = data.temperature
            $self.weatherInfo.weather = data.weather
            $self.weatherInfo.windDirection = data.windDirection
            $self.weatherInfo.windPower = data.windPower
            $self.getWeatherIcon(data.weather)
          } else {
            this.$Message.error('未查询到相关天气信息')
          }
        })
        weather.getForecast(countyInfo, function(err, data) {
          if (!err) {
            $self.weatherInfo.nightTemp = data.forecasts[0].nightTemp
            $self.weatherInfo.dayTemp = data.forecasts[0].dayTemp
          }
        })
      })
    },
    getWeatherIcon(item) {
      if(item === '晴') {
        this.weatherIcon = this.sun
      }else if(item === '多云') {
        this.weatherIcon = this.cloud
      }else if(item === '阴') {
        this.weatherIcon = this.cloudy
      }else if(!(item.indexOf('沙') === -1) || !(item.indexOf('尘') === -1)) {
        this.weatherIcon = this.dust
      }else if(!(item.indexOf('雾') === -1) || !(item.indexOf('霾') === -1)) {
        this.weatherIcon = this.haze
      }else if(!(item.indexOf('雹') === -1)) {
        this.weatherIcon = this.hail
      }else if(!(item.indexOf('雨') === -1) && item.indexOf('雪') === -1) {
        this.weatherIcon = this.rain
      }else if(!(item.indexOf('雪') === -1) && item.indexOf('雨') === -1) {
        this.weatherIcon = this.snow
      }else if(!(item.indexOf('雨') === -1) && !(item.indexOf('雪') === -1)) {
        this.weatherIcon = this.rainsnow
      }else { // 其他情况
        this.weatherIcon = this.cloudy
      }
      if(!(item.indexOf('雷') === -1)) {
        this.weatherIcon = this.ray
      }
    },
    linkToOther() {
      let link = document.createElement('a')
      link.href = 'http://www.weather.com.cn/weather1d/101120101.shtml'
      link.setAttribute('target', '_blank')
      document.body.appendChild(link)
      link.style.display = 'none'
      link.click()
      document.body.removeChild(link)
    }
  }
}
</script>
<style lang="less" scoped>
.weather-contain {
  display: flex;
  vertical-align: middle;
  .weather-right-panel {
    width: 70%;
    margin-left: 30px;
  }
  .weather-simple {
    display: inline-flex;
    justify-content: middle;
    font-size: 14px;
    font-family: MicrosoftYaHei;
    font-weight: 400;
    color: rgba(102, 102, 102, 1);
    .weather-temperature {
      cursor: pointer;
      margin-right: 8px;
      font-size: 44px;
      font-family: Arial-BoldMT;
      font-weight: bold;
      color: #00A0E9;
      &:hover {
        text-decoration: underline;
      }
    }
    .weather-quality {
      margin-left: 8px;
      margin-top: 25px;
      padding: 2px;
      background: #00A0E9;
      color: #fff;
      border-radius: 2px;
    }
  }
  .weather-desc {
    margin-top: 10px;
    font-size: 14px;
    font-family: MicrosoftYaHei;
    font-weight: 400;
    color: rgba(102, 102, 102, 1);
    // max-width: 80%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
.todoli {
  position: relative;
  margin-left: 70px;
  list-style: none;
  height: 90px;
  padding-top: 20px;
  padding-bottom: 20px;
  .todo-text {
    float: left;
    width: 70%;
    .todo-title {
      font-size: 14px;
      font-family: MicrosoftYaHei;
      font-weight: 400;
      color: rgba(68, 68, 68, 1);
      margin-bottom: 8px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .todo-subtitle {
      font-size: 12px;
      font-family: MicrosoftYaHei;
      font-weight: 400;
      color: rgba(153, 153, 153, 1);
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
}
.todoli + .todoli {
  border-top: 1px solid rgba(225, 226, 226, 1);
}
.will1:before {
  content: '';
  background: url('~assets/images/common/will1.png') no-repeat center;
  height: 55px;
  width: 55px;
  position: absolute;
  left: -70px;
  top: 13px;
  background-position: 0px 0px;
}
.will2:before {
  content: '';
  background: url('~assets/images/common/will2.png') no-repeat center;
  height: 55px;
  width: 55px;
  position: absolute;
  left: -70px;
  top: 13px;
  background-position: 0px 0px;
}
.will3:before {
  content: '';
  background: url('~assets/images/common/will3.png') no-repeat center;
  height: 55px;
  width: 55px;
  position: absolute;
  left: -70px;
  top: 13px;
  background-position: 0px 0px;
}
.will4:before {
  content: '';
  background: url('~assets/images/common/will4.png') no-repeat center;
  height: 55px;
  width: 55px;
  position: absolute;
  left: -70px;
  top: 13px;
  background-position: 0px 0px;
}
</style>

需要注意的是 这里用到了amap,你们需要找相应的js  <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=toekn钥匙"></script> 

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Vue2中,可以使用高德地图API来获取当前定位。首先,需要引入高德地图的SDK,并在Vue组件中使用AMap.Geolocation来获取当前位置的经纬度信息。以下是一个示例代码: 首先,在utils文件夹中创建一个名为getLocation.js的文件,用于封装获取经纬度的公用方法。该方法使用了Promise来确保在获取到经纬度信息后再进行后续操作。具体代码如下: ```javascript function loadSDK() { if (window.AMap) return; return new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = 'http://webapi.amap.com/maps?v=1.4.6&key=*****************'; // ***为申请的高德key document.head.appendChild(script); script.onload = resolve; script.onerror = reject; }); } export default async () => { await loadSDK(); return new Promise((resolve) => { AMap.plugin('AMap.Geolocation', () => { const geolocation = new AMap.Geolocation({ enableHighAccuracy: false }); geolocation.getCurrentPosition((status, result) => { const res = status === 'complete' ? result.position : { lat: 39.909187, lng: 116.397451 }; // 默认北京 116.397451、39.909187 console.log('定位结果', res); resolve(res); }); }); }); } ``` 然后,在Vue组件中,可以通过调用上述封装的方法来获取当前定位的经纬度信息。具体代码如下: ```javascript import getLocation from '@/utils/getLocation'; export default { methods: { async getCurrentLocation() { try { const position = await getLocation(); // 在这里可以使用获取到的经纬度信息进行后续操作 console.log('当前定位经纬度', position); } catch (error) { console.error('获取定位失败', error); } }, }, mounted() { this.getCurrentLocation(); }, }; ``` 以上代码中,通过调用`getLocation`方法来获取当前定位的经纬度信息,并在`getCurrentLocation`方法中进行后续操作。在Vue组件的`mounted`钩子函数中调用`getCurrentLocation`方法来获取当前定位信息。 请注意,上述代码中的高德地图SDK的引入地址和申请的key需要根据实际情况进行修改。 #### 引用[.reference_title] - *1* *2* [(2023进阶版)vue+h5 通过高德地图(原生) 获取当前位置定位](https://blog.csdn.net/yangzixiansheng/article/details/131308415)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [vue使用高德地图获取当前经纬度](https://blog.csdn.net/V_AYA_V/article/details/105275063)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值