Vue中腾讯地图-自动获取当前城市位置+搜索功能

<script>
export default {
    data() {
        return {
   //搜索关键字
            adressKeywords:'',
            coordinatesValue: {
                longitude: '', //经度
                latitude: '', //纬度
            }
        };
    },
 

 

    methods: {
 
  getCoordinates() {
 
          // 获取当前地理位置信息
          let data = {
            key: "XXX" //密钥,需要在腾讯位置服务官网(https://lbs.qq.com/)申请自己的密钥。
          };
 
          let url = "https://apis.map.qq.com/ws/location/v1/ip"; //地理位置信息接口(根据IP自动获取当前城市位置信息)
 
          let secondUrl = "https://apis.map.qq.com/ws/geocoder/v1/?address=" + this.adressKeywords; //根据输入地址获取对应的经纬度信息 (根据搜索关键字获取当前城市位置信息)
 
          data.output = "jsonp";
 
   //判断用户是否输入了搜索关键字,若没有输入搜索关键字则调用根据IP自动获取当前城市位置信息的接口。
          this.$jsonp(this.adressKeywords == '' ? url : secondUrl, data)
 
            .then(res => {
              this.coordinatesValue.longitude = res.result.location.lng // 经度
              this.coordinatesValue.latitude = res.result.location.lat // 纬度
            })
            .catch(error => {
              console.log(error);
            });
        },
};
</script>

 

posted @ 2022-01-06 15:36  麦田与星空  阅读(3755)  评论(0)    收藏  举报