H5百度地图选择

1.引入

<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=DFCUDRBUeWLN0HKZFJEHocIkPrNVTZZvxDH"></script>

 2.新建组件

3.

 

 

 

<template>
   <van-overlay class="a-map" :show="isShow" :lock-scroll="false">  
    <van-button class="cancel-btn" @click="cancel">取消</van-button>
    <van-button v-if="currentAddress" round type="primary" class="comfirm-btn" @click="comfirm">确认选择</van-button> 
    <div id="mapContainer" class="map-container">
    </div>
    <div class="search">
      <van-search
        ref="search2Ref"
        v-model="queryString"
        background="#FFFFFF"
        placeholder="请输入地址搜索"
        clearable
        @input="onInput"
        right-icon="search"
      />
    </div>
    <div class="select-option">
      <template v-for="(item,index) in list">
        <div
          class="option" 
          :key="index"
          @click="choose(item,index)"
        >
          {{letters[index]}}.{{ item.title }} ({{item.address}})
          <div v-if="item.checked" class="check-btn"> 
            <van-icon size="24px" color="green" name="success" />
          </div>
        </div> 
      </template>
    </div>
  </van-overlay>
</template>

<script>
import { Toast } from "vant";
 let map = null
 let localSearch = null
 var marker = null
 let that
export default {
  name: 'Map', 
  components: { 
  },
  data() {
    return {  
      isShow:false,
      queryString:"",
      timer:null,
      list:[],
      currentAddress:null,
      letters:['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
    }
  },
  computed: {  

  },
  created() {
    
  },
  mounted() {
    that = this  
  },
  beforeDestroy(){
    // console.log('销毁地图')
    // if(map){ 
    //   map.destroy()
    // }
  },
  methods: {  
    firstSearch(){
      var geolocation = new BMap.Geolocation();
      if (geolocation) {
        // 开启SDK辅助定位
        geolocation.enableSDKLocation(); 
        geolocation.getCurrentPosition(function (res) {
          console.log("获取定位信息==", res); // 定位
          console.log(res.point)
          that.getLocationByPoint(res.point)
        });
      } 
    },
    initMap(){
      //  // 创建地图实例
      map = new BMap.Map("mapContainer"); 
      // 初始化地图,设置中心点坐标和地图级别
      let longitude = localStorage.getItem('longitude') || 113.93041
      let latitude = localStorage.getItem('latitude') || 22.53332 
      map.centerAndZoom(new BMap.Point(longitude, latitude), 18);  
      console.log(map,'-------')
      // 启用滚轮放大缩小
      map.enableScrollWheelZoom(true);  
      map.enableDragging()   
      this.firstSearch()
      localSearch = new BMap.LocalSearch(map, {
          renderOptions: {map: map, panel: "resultsPanel"},
          pageCapacity: 10,
          autoViewport: true,
          // selectFirstResult: true,
          onSearchComplete: (res)=> {
            console.log('搜索列表', res) 
            if(res && res.as){
              this.currentAddress = null
              this.list = res.as.map(item =>{  
                return { 
                  province:item.province,
                  city:item.city,
                  district:item.district,
                  title:item.title,
                  address:item.address,
                  point:item.point,
                  checked:false,  
                }
              }) 
            }else{
              this.list = []
            }
          },
          onMarkerClick : (res)=> {
            console.log(res)
          }
      }); 

      map.addEventListener("click", (e)=> {
        this.currentAddress = null
        for (var i = 0; i < this.list.length; i++) {
            this.list[i]['checked'] = false
        }
        if (e.overlay != null) { 
          let current = e.overlay.point
          for (var i = 0; i < this.list.length; i++) { 
            if(current.lat === this.list[i].point.lat && current.lng === this.list[i].point.lng){            
              console.log(current)  
              this.$set(this.list[i],'checked',true)
            }
          }
        } else{ 
          if(!this.queryString){
            console.log(e,'非标记地址')
            that.getLocationByPoint(e.point)
          }
        }
      })

       
      // map.addEventListener('click', function(e) {
      //     // 处理点击事件
      //     console.log(e)
      // }); 
    },
    getLocationByPoint(point){
      console.log(point,'point')
      var geocoder = new BMap.Geocoder();
        geocoder.getLocation(point, (rs)=> {
          console.log(rs) 
          let surroundingPois = rs.surroundingPois
          let addressComponents = rs.addressComponents
          this.currentAddress = null
          if(surroundingPois.length){ 
            this.list = surroundingPois.map(item =>{  
              return {   
                province:addressComponents.province,
                city:addressComponents.city,
                title:item.title,
                address:item.address,
                point:item.point,
                checked:false,  
              }
            })  
          }else{
            this.list = [{   
              province:addressComponents.province,
              city:addressComponents.city,
              title:rs.address,
              address:rs.address,
              point:rs.point,
              checked:false,  
            }]
          }
        }); 
    },
    show(){
      this.isShow = true
      this.initMap()
    },
    comfirm(){  
      this.$emit('address',this.currentAddress)
      this.cancel()
      console.log(this.currentAddress)
    },
    cancel(){
      this.isShow = false
    },
    choose(current,index){
      this.currentAddress = current
      for (var i = 0; i < this.list.length; i++) {
        this.list[i]['checked'] = false 
      }
      this.$set(this.list[index],'checked',true) 

      var geocoder = new BMap.Geocoder(); 
        // 根据坐标进行逆地址解析 
        geocoder.getLocation(this.currentAddress.point, (result)=> {
        if (result) {
          // 解析成功,获取地址信息
          var address = result.address; // 完整地址信息
          var addressComponents = result.addressComponents; // 结构化地址信息
          this.$set(this.list[index],'district',addressComponents.district) 
          console.log("完整地址: " + address);
          console.log("省份: " + addressComponents.province);
          console.log("城市: " + addressComponents.city);
          console.log("区县: " + addressComponents.district);
          console.log("街道: " + addressComponents.street);
          console.log("门牌号: " + addressComponents.streetNumber);
        } else {
            // 解析失败
            console.log("地址解析失败");
        }
      })
    },
    toBack(){ 
      this.$router.back()
    }, 
    onInput(e){
      this.timer && clearTimeout(this.timer)
      this.timer = setTimeout(()=>{ 
        console.log(e) 
        localSearch.search(e);   
      },200)

    }
  }
}
</script>

<style lang="less" scoped>
.a-map{
  position: fixed;
  top: 0;
  width: 100%;
  height: 100vh; 
  overflow: hidden;  
  display: flex;
  flex-direction: column; 
  .cancel-btn{
    position: absolute; 
    top: 12px;
    width: 80px;
    background-color: transparent;
    color: #07c160;
    z-index: 99999;
    height: 34px;
    width: 88px;
    text-align: left;
    border: none;
  }
  .comfirm-btn{
    position: absolute;
    right: 12px; 
    top: 12px;
    width: 80px;
    z-index: 99999;
    height: 34px;
    width: 88px;
    transform: translateX(-14px);
  }
  .map-container{
    height: 300px;
    width: 100%;
  }
  .select-option{
    flex: 1;
    background:#fff;
    max-height: 500px;
    overflow-y: auto;
    .option{
      position: relative;
      padding: 12px 50px 12px 12px;
      line-height: 16px;
      &::after{
        content: '';
        position: absolute;
        height: 1px;
        width: 351px;
        left: 0;
        bottom: 0;
        background: #e3e3e3; 
      }
      .check-btn{
        position: absolute;
        right: 12px;
        top: 12px;

      }
    }
  }
 
  
}
</style>

  

posted @ 2024-12-06 16:39  福超  阅读(59)  评论(0)    收藏  举报