Uso simple del mapa de Gaode: haga clic en la marca para obtener la latitud y longitud y la dirección detallada

Preparación

1. Primero ingrese a la plataforma de desarrollo Gaode para registrarse e iniciar sesión inserte la descripción de la imagen aquí
2. Ingrese a la Api map js y siga los pasos para solicitar una clave
3 Use npm para instalar el paquete de dependencia npm i @amap/amap-jsapi-loader --save
4. Gaode api tiene instrucciones y vea a continuación La función y el código que implementé

mapa emergente

1. Inicialice el mapa y cárguelo. El mapa ubicará y mostrará automáticamente su ciudad. Haga clic en el mapa para obtener la latitud, longitud y dirección detallada.
inserte la descripción de la imagen aquí
2. Mensaje de entrada
inserte la descripción de la imagen aquí
El complemento de mensaje de entrada se utiliza en el módulo de servicio de la API de Map JS.
3. Todos los códigos del componente de ventana emergente.

<template>
  <div class="app-container">
    <el-dialog
      title="打点"
      :append-to-body="true"
      :visible.sync="isShow"
      width="940px"
      top="15px"
      :close-on-click-modal="false"
      :before-close="beforeClose"
      :class="{textAlign:'center'}"
    >
      <div class="flex-ar mb15">
        <span>经度: {
    
    {
    
     form.lng }}</span><span> 纬度 {
    
    {
    
     form.lat }}</span><span> 地址 {
    
    {
    
     form.address }}</span>
      </div>
      <div id="container">

      </div>
      <div class="flex-bt" style="width: 400px;position: absolute;top:125px;left: 50px">
        <el-select v-model="address" clearable placeholder="请输入关键词" style="width: 400px;"
                   :remote-method="remoteMethod"
                   filterable
                   remote
                   @change="currentSelect"
                   class="one-text"
                   :loading="loading"
        >
          <el-option v-for="(item,index) in options" :key="index" :label="item.district+item.name"
                     :value="item.district + item.name"
          >
            <span>{
    
    {
    
     item.district }}</span> <span>{
    
    {
    
     item.name }}</span>

          </el-option>

        </el-select>
        <el-button type="primary" size="mini" class="ml20" @click="saveInfo">打点保存</el-button>
      </div>

      <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="confirmForDestroy">关 闭</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'

window._AMapSecurityConfig = {
    
    
  // 安全密钥
  securityJsCode: 'edf079xxxxb1fxxxxxx737fe816d'
}
export default {
    
    
  name: 'amapDialog',
  data() {
    
    
    return {
    
    
      map: null,
      marker: '',
      form: {
    
    
        lng: '',
        lat: '',
        address: '',
        adcode: '' //地区编码
      },
      isShow: false,
      address: '',
      options: [],
      loading: false
    }
  },
  mounted() {
    
    

  },
  methods: {
    
    

    initMap(arr) {
    
    
      AMapLoader.load({
    
    
        key: 'xxxxx',             // 申请好的Web端开发者Key,首次调用 load 时必填
        version: '2.0',      // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
        plugins: ['AMap.AutoComplete',
          'AMap.PlaceSearch',
          'AMap.CitySearch',
          'AMap.Geocoder',
          'AMap.Geolocation']
      }).then((AMap) => {
    
    
        this.map = new AMap.Map('container', {
    
      //设置地图容器id
          viewMode: '3D',    //是否为3D地图模式
          zoom: 12,
          center:arr
        })
        // 地址逆向解析插件
        this.geoCoder = new AMap.Geocoder({
    
    
          city: '010', //城市设为北京,默认:“全国”
          radius: 1000 //范围,默认:500
        })
        // 正向地理编码
        this.geocoder = new AMap.Geocoder({
    
    
          city: this.address
        })
        //搜所提示插件
        this.AutoComplete = new AMap.AutoComplete({
    
     city: '全国' })

        this.map.on('click', (e) => {
    
    
          if (!e && !e.lnglat) {
    
    
            return
          }
          this.form.lng = e.lnglat.lng
          this.form.lat = e.lnglat.lat
          this.removeMarker()
          this.setMapMarker()
        })

      }).catch(e => {
    
    
        console.log(e)
      })
    },


    // 标记点
    setMapMarker() {
    
    
      if (this.form.lng == '' && this.form.lat == '') {
    
    
        return
      }
      // 自动适应显示想显示的范围区域
      this.map.setFitView()
      this.marker = new AMap.Marker({
    
    
        map: this.map,
        position: [this.form.lng, this.form.lat],
      })
      this.toGetAddress()
      this.map.setFitView()
      this.map.add(this.marker)
    },
    //清除点
    removeMarker() {
    
    
      if (this.marker) {
    
    
        this.map.remove(this.marker)
      }
    },
    // 逆解析地址
    toGetAddress() {
    
    
      let lnglat = [this.form.lng, this.form.lat]
      this.geoCoder.getAddress(lnglat, (status, result) => {
    
    
        if (status === 'complete' && result.regeocode) {
    
    
          this.form.address = result.regeocode.formattedAddress
        }
      })
    },
    //搜索
    remoteMethod(query) {
    
    
      if (query !== '') {
    
    
        this.loading = true
        let that = this
        setTimeout(() => {
    
    
          that.loading = false
          that.AutoComplete.search(query, (status, result) => {
    
    
            console.log(result)
            that.options = result.tips
          })
        }, 200)
      } else {
    
    
        this.options = []
      }
    },
    // 选中提示
    currentSelect(val) {
    
    
      // 清空时不执行后面代码
      if (!val) {
    
    
        return
      }
      this.toGetCoordinate(val)

    },

    //正向解析
    toGetCoordinate(address) {
    
    
      let that = this
      this.geocoder.getLocation(address, function(status, result) {
    
    
        if (status === 'complete' && result.info === 'OK') {
    
    
          that.initMap([result.geocodes[0].location.lng, result.geocodes[0].location.lat])
          console.log(result)
          that.form.lng = result.geocodes[0].location.lng
          that.form.lat = result.geocodes[0].location.lat
          that.form.address = result.geocodes[0].formattedAddress
        }
      })
    },

    saveInfo() {
    
    
      console.log(this.form.address)
      if (this.form.address === '') {
    
    
        this.$message.error('打点失败,请手动抓取点')
        return
      }
      this.$emit('genAddressInfo', this.form)
    },
    confirmForDestroy() {
    
    
      this.isShow = false
      this.beforeDestroy()

    },
    beforeDestroy() {
    
    
      this.map.destroy() //销毁地图
    },
    beforeClose(done){
    
    
      done()
      this.beforeDestroy()
    }

  }

}
</script>

<style scoped lang="scss">
#container {
    
    
  padding: 0px;
  margin: 0px;
  width: 900px;
  height: 650px;
}

</style>

Ven aquí primero y completa la próxima vez. Esta es una ventana emergente. Cuando cierras la ventana emergente, necesitas destruir el mapa. Usa la llamada de referencia al método beforeDestroy() para destruir el mapa. De lo contrario, es fácil informar un error.

Supongo que te gusta

Origin blog.csdn.net/weixin_45753588/article/details/129579606
Recomendado
Clasificación