美文网首页
vue百度地图 输入关键字 获取经纬度

vue百度地图 输入关键字 获取经纬度

作者: Rose_yang | 来源:发表于2020-12-02 18:35 被阅读0次
// template

 <a-input
     @pressEnter="(e) => {e.preventDefault()}"
      v-decorator="['address',{rules: [{ required: true, message: '请输入详细地址' }]}]"
      placeholder="请输入详细地址"
 />
 <a-button
     class="btn"
     @click="doSearchMap"
>搜索地图</a-button>
 <map-input v-decorator="['mapData']" @change="handleMapClick" ref="map" />
// script
import mapInput from 'components/map'
data () {
   return {
    // 地图功能参数
      addressKeyword: '',
      lng: '',
      lat: '',
   }
} ,
components: {
    mapInput
  },
methods:{
   // 通过输入的关键字查询地图
    doSearchMap () {
      let address = this.form.getFieldValue('address')
      console.log('address------', address)

      if (address) {
        this.addressKeyword = this.city + this.region + address
      } else {
        this.addressKeyword = ''
      }
      this.$refs.map.search(this.addressKeyword)

      console.log('关键字------', this.addressKeyword)
    },
   // 点击选择地图上的热点 给输入框回填数据,并获取经纬度 
    handleMapClick (value) {
      console.log('handleMapClick------', value)
      if (value && value.address && value.point) {
        this.form.setFieldsValue({
          address: value.address
        })

        this.lng = value.point.lng
        this.lat = value.point.lat
      }
    },
}

地图组件

<template>
  <div v-once class="bmap-container"></div>
</template>

<script>

export default {
  /**
   * 属性列表
   */
  props: {
    // v-model 属性
    value: {
      type: Object
    },
    // 使用授权
    ak: {
      type: String,
      default: 'gKgImcyCvlqHt5C3mGYFySeOwBaXOAr5'
    }
  }, // end props

  /**
   * 组件列表
   */
  components: {}, // end components

  /**
   * 数据列表
   */
  data() {
    return {
      BMap: null,
      // 地图指针
      map: null,
      // 搜索模块
      localSearch: null,
      // 逆向查询
      geocoder: null,
      // 导出数据
      stateValue: {
        // 建筑
        title: '',
        // 地址
        address: '',
        // 省
        province: '',
        // 市
        city: '',
        // 区
        district: '',
        // 街道
        street: '',
        // 纬度
        latitude: 0,
        // 经度
        longitude: 0
      },
      // 关键字检索结果
      searchResult: []
    }
  }, // end data

  /**
   * 计算数据列表
   */
  computed: {}, // end computed

  /**
   * 监视列表
   */
  watch: {
    value(value) {
      // 回显请根据数据情况写到这里
      console.warn(value)
    }
  }, // end watch

  /**
   * 在实例创建完成后被立即调用
   */
  created() {}, // end created

  /**
   * 实例被挂载后调用
   */
  mounted() {
    if ('BMap' in window) {
      this.$nextTick(() => this.handleReady())
    } else {
      this.loadBMap()
    }
  }, // end mounted

  /**
   * 方法列表
   */
  methods: {
    /**
     *
     */
    loadBMap() {
      const tag = document.createElement('script')
      tag.src =
        '//api.map.baidu.com/api?v=2.0&ak=' +
        this.ak +
        '&callback=handleBMapReady'
      tag.type = 'text/javascript'
      window.handleBMapReady = () => this.handleReady()
      document.body.appendChild(tag)
    },

    /**
     * 加载完成
     */
    async handleReady() {
      this.BMap = window.BMap
      this.map = new this.BMap.Map(this.$el)
      this.map.addEventListener('click', evnt => this.handleClick(evnt))
      this.map.enableScrollWheelZoom(true)
      // 导出变量
      const { longitude, latitude } = this.stateValue
      //  // 创建点坐标
      if (longitude === 0 && latitude === 0) {
        const ret = await this.toCurrentPosition()
        this.setCenter(ret.longitude, ret.latitude)
        // this.stateValue = this.getAddress(ret.longitude, ret.latitude)
        // this.$emit('input', this.stateValue)
        // this.$emit('change', this.stateValue)
      } else {
        this.setCenter(longitude, latitude)
      }

      // 添加带有定位的导航控件
      var navigationControl = new this.BMap.NavigationControl({
        // 靠左上角位置
        anchor: 'BMAP_ANCHOR_TOP_RIGHT',
        // LARGE类型
        type: 'BMAP_NAVIGATION_CONTROL_LARGE',
        // 启用显示定位
        enableGeolocation: true
      })
      this.map.addControl(navigationControl)
    },

    /**
     * 设置底图中心
     */
    setCenter(lng, lat) {
      if (this.map) {
        this.map.centerAndZoom(new this.BMap.Point(lng, lat), 15)
      }
    },

    /**
     * 关键词查询
     */
    search(keywords) {
      var local = new this.BMap.LocalSearch(this.map, {
        renderOptions: {
          map: this.map
        },
        onSearchComplete: async(rs) => {
          if (rs && rs.Ir instanceof Array && rs.Ir.length > 0) {
            console.log('rs----关键词查询---', rs)

            // this.stateValue = await this.getAddress(
            //   rs.Ir[0].point.lng,
            //   rs.Ir[0].point.lat
            // )
            this.searchResult = rs.Ir

            // 默认展示查询结果第一条数据
            this.stateValue = rs.Ir[0]

            this.$emit('input', this.stateValue)
            this.$emit('change', this.stateValue)
          } else {
            this.searchResult = []
          }
        }
        // onMarkersSet: (arr) => {
        //   console.log('关键词查询----标注添加完成后的回调函数---', arr)
        // }
      })
      local.search(keywords)
    },

    /**
     * 关键词查询,只获取数据,不展示地图
     */
    onlySearch(keywords) {
      var local = new this.BMap.LocalSearch(this.map, {
        renderOptions: {
          map: this.map
        },
        pageCapacity: 100, // 设置最大容量 一页
        onSearchComplete: async(rs) => {
          if (rs && rs.Ir instanceof Array && rs.Ir.length > 0) {
            console.log('rs----关键词查询---', rs)

            // this.stateValue = await this.getAddress(
            //   rs.Ir[0].point.lng,
            //   rs.Ir[0].point.lat
            // )
            this.searchResult = rs.Ir

            this.$emit('input', this.searchResult)
            this.$emit('change', this.searchResult)
          } else {
            this.searchResult = []
          }
        }
      })
      local.search(keywords)
    },

    /**
     * 清除最近一次检索的结果
     */
    clearResults() {
      var local = new this.BMap.LocalSearch(this.map, {
        renderOptions: {
          map: this.map
        }
      })
      local.clearResults()
    },

    /**
     * 设置当前城市
     */
    setCurrentCity(city) {
      if (this.map && city) {
        this.map.setCurrentCity(city)
      }
    },

    /**
     * 获得地址信息
     */
    getAddress(lng, lat) {
      if (!this.geocoder) {
        this.geocoder = new this.BMap.Geocoder()
      }
      return new Promise(resolve => {
        this.geocoder.getLocation(new this.BMap.Point(lng, lat), rs => {
          const obj = JSON.parse(JSON.stringify(rs.addressComponents))
          console.log('rs----获得地址信息---', rs)

          delete obj.streetNumber
          obj.longitude = lng
          obj.latitude = lat
          if (rs.surroundingPois.length > 0) {
            obj.address = rs.surroundingPois[0].address
            obj.title = rs.surroundingPois[0].title
          } else {
            obj.address = rs.address
            obj.title = ''
          }
          resolve(obj)
        })
      })
    },

    /**
     * 当点击地图
     */
    async handleClick(event) {
      // console.log('event----当点击地图---', event)
      // console.log('searchResult----当点击地图---', this.searchResult)

      // // 重置
      this.stateValue = {}
      //
      // this.searchResult.forEach(result => {
      //   if (event.point.lat === result.point.lat && event.point.lng === result.point.lng) {
      //     // 点击的标注点是查询结果中的标注点
      //     this.stateValue = result
      //     console.log('result----点击的标注点---', result)
      //   }
      // })
      if (event.overlay) {
        // console.log('event.overlay----点击的标注点---', event.overlay)

        this.searchResult.forEach(result => {
          if (event.overlay.ba === result.marker.ba && event.overlay.z.title === result.marker.z.title) {
            // 点击的标注点是查询结果中的标注点
            this.stateValue = result
            console.log('result----点击的标注点---', result)
          }
        })
      }

      // this.stateValue = await this.getAddress(event.point.lng, event.point.lat)

      this.$emit('input', this.stateValue)
      this.$emit('change', this.stateValue)
    },

    /**
     * 获得当前地址
     */
    toCurrentPosition() {
      return new Promise((resolve, reject) => {
        const geolocation = new this.BMap.Geolocation()
        geolocation.getCurrentPosition(ret => {
          console.log('ret----获得当前地址---', ret)
          if (geolocation.getStatus() === window.BMAP_STATUS_SUCCESS) {
            const mk = new this.BMap.Marker(ret.point)
            this.map.addOverlay(mk)
            resolve({
              province: ret.address.province,
              city: ret.address.city,
              district: ret.address.district || '',
              street: ret.address.street,
              streetNumber: ret.address.streetNumber || '',
              longitude: ret.point.lng,
              latitude: ret.point.lat
            })
          } else {
            reject(new Error('geolocation error'))
          }
        })
      })
    }
  } // end methods
} // end export
</script>

<style lang='scss'>
.bmap-container {
  width: 100%;
  height: 400px;
  margin-bottom: 25px;

  .BMap_cpyCtrl {
    display: none;
  }
  .anchorBL {
    display: none;
  }
}
</style>

相关文章

网友评论

      本文标题:vue百度地图 输入关键字 获取经纬度

      本文链接:https://www.haomeiwen.com/subject/hsqtzctx.html