vue-amap生成坐标地址代码

vue-amap安装和使用

vue-amap 是饿了么开源的一套基于 Vue 2.0 和高德地图的地图组件。 数据状态与地图状态单向绑定,开发者无需关心地图的具体操作。

官方文档:https://elemefe.github.io/vue-amap/#/zh-cn/introduction/install

步骤如下:

npm install vue-amap --save
import VueAMap from "vue-amap"
Vue.use(VueAMap)
// 初始化vue-amap
VueAMap.initAMapApiLoader({
  key: "amapKey",
  plugin: ["AMap.Autocomplete", "AMap.Geocoder", "AMap.Geolocation"],
  v: "1.4.15",
  uiVersion: "1.1"
})

 实例需求描述:搜索并选择地址,选中后地图定位到该地址,并获取经纬度自动填入下方的输入框中。点击地图中的点也自动更新地址和坐标。

 

 定义地图搜索组件

<template>
    <div>
        <div class="search-box">
            <el-input
                    v-model="searchKey"
                    type="search"
                    id="search"
                    placeholder="请输入详细地址"
            ></el-input>
            <!--<button @click="searchByHand">搜索</button>-->
            <div class="tip-box" id="searchTip"></div>
        </div>
        <!--
          amap-manager: 地图管理对象
          vid:地图容器节点的ID
          zooms: 地图显示的缩放级别范围,在PC上,默认范围[3,18],取值范围[3-18];在移动设备上,默认范围[3-19],取值范围[3-19]
          center: 地图中心点坐标值
          plugin:地图使用的插件
          events: 事件
        -->
        <div class="amap-box">
            <el-amap
                    :amap-manager="amapManager"
                    :vid="'amap-vue'"
                    :zoom="zoom"
                    :plugin="plugin"
                    :center="center"
                    :events="events"
            >
                <!-- 标记 -->
                <el-amap-marker
                        v-for="(marker, index) in markers"
                        :position="marker"
                        :key="index"
                ></el-amap-marker>
            </el-amap>
        </div>
    </div>
</template>
<script>
import {AMapManager, lazyAMapApiLoaderInstance} from 'vue-amap'

let amapManager = new AMapManager()
export default {
  props: ['city', 'value', 'longitude', 'latitude', 'isEdit'],
  data() {
    let self = this
    return {
      address: null,
      searchKey: '',
      amapManager,
      markers: [],
      searchOption: {
        city: this.city ? this.city : '全国',
        citylimit: true
      },
      center: [121.329402, 31.228667],
      zoom: 17,
      lng: 0,
      lat: 0,
      loaded: false,
      events: {
        init() {
          lazyAMapApiLoaderInstance.load().then(() => {
            self.initSearch()
          })
        },
        // 点击获取地址的数据
        click(e) {
          self.markers = []
          let {lng, lat} = e.lnglat
          self.lng = lng
          self.lat = lat
          self.center = [lng, lat]
          self.markers.push([lng, lat])
          // 这里通过高德 SDK 完成。
          let geocoder
          AMap.plugin(['AMap.Geocoder'], function() {
            geocoder = new AMap.Geocoder({
              radius: 1000,
              extensions: 'all'
            })
          })
          geocoder.getAddress([lng, lat], function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
              if (result && result.regeocode) {
                self.address = result.regeocode.formattedAddress
                self.searchKey = result.regeocode.formattedAddress
                self.poiPicker.clearSearchResults()
                self.$emit('updateLocation', lng, lat, self.searchKey)
                self.$nextTick()
              }
            }
          })
        }
      },
      // 一些工具插件
      plugin: [
        {
          // 定位
          pName: 'Geolocation',
          events: {
            init(o) {
              // o是高德地图定位插件实例
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  if (self.isEdit) {
                    // 设置经度
                    self.lng = self.longitude
                    // 设置维度
                    self.lat = self.latitude
                    // 设置坐标
                    self.center = [self.longitude, self.latitude]
                    self.markers.push([self.longitude, self.latitude])
                  } else {
                    console.info('result-->', result)
                    var address = result.addressComponent.city
                    self.updateAddress(address, result.position.lng, result.position.lat)
                    self.poiPicker.searchByKeyword(self.searchKey)
                  }
                  // load
                  self.loaded = true
                  // 页面渲染好后
                  self.$nextTick()
                }
              })
            }
          }
        }
      ]
    }
  },
  created() {
    if (this.value) {
      this.searchKey = this.value
      this.address = this.value
    }
    if (this.longitude && this.latitude) {
      this.lng = this.longitude
      this.lat = this.latitude
      this.center = [this.longitude, this.latitude]
      this.markers.push([this.longitude, this.latitude])
    }
    AMap.plugin(['AMap.Geolocation'], () => {
      var geolocation = new AMap.Geolocation({
        enableHighAccuracy: true, // 是否使用高精度定位,默认:true
        timeout: 2000, // 超过2秒后停止定位,默认:无穷大
        zoomToAccuracy: false, // 定位成功后地图放最大,默认:false
        buttonPosition: 'LB', // 定位器左上下角
        buttonOffset: new AMap.Pixel(11, 20), // 定位器位置偏移
        showMarker: false
      })
      AMap.addControl(geolocation)
    })
  },
  methods: {
  // 选择地址后自动定位到当前地址附近
    updateAddress(value, longitude, latitude) {
      this.searchKey = value
      this.address = value
      this.lng = longitude
      this.lat = latitude
      this.center = [longitude, latitude]
      this.markers.push([longitude, latitude])
    },
    initSearch() {
      let vm = this
      let map = this.amapManager.getMap()
      AMapUI.loadUI(['misc/PoiPicker'], function(PoiPicker) {
        let poiPicker = new PoiPicker({
          input: 'search',
          placeSearchOptions: {
            map: map,
            pageSize: 8
          },
          suggestContainer: 'searchTip',
          searchResultsContainer: 'searchTip'
        })
        vm.poiPicker = poiPicker
        // 监听poi选中信息
        poiPicker.on('poiPicked', function(poiResult) {
          let source = poiResult.source
          let poi = poiResult.item
          if (source !== 'search') {
            poiPicker.searchByKeyword(poi.name)
          } else {
            poiPicker.clearSearchResults()
            vm.markers = []
            let lng = poi.location.lng
            let lat = poi.location.lat
            // let address = poi.name // poi.cityname + poi.adname + poi.name
            let address = poi.pname + poi.cityname + poi.adname + poi.address + poi.name
            vm.center = [lng, lat]
            vm.markers.push([lng, lat])
            vm.lng = lng
            vm.lat = lat
            vm.address = address
            vm.searchKey = address
            vm.$emit('updateLocation', lng, lat, vm.searchKey)
          }
        })
      })
    },
    searchByHand() {
      if (this.searchKey !== '' && this.poiPicker) {
        this.poiPicker.searchByKeyword(this.searchKey)
      }
    }
  }
}
</script>
<style scoped>
    .search-box {
        margin-top: 6px;
        width: 100%;
    }

    .search-box input {
        padding: 0 15px;
        width: 100%;
        height: 32px;
        line-height: 32px;
        color: #606266;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
    }

    .search-box input:focus {
        border-color: #409eff;
        outline: 0;
    }

    .search-box input::-webkit-input-placeholder {
        color: #c0c4cc;
    }

    .tip-box {
        width: 100%;
        max-height: 580px;
        position: absolute;
        top: 35px;
        z-index: 10000;
        overflow-y: auto;
        background-color: #fff;
    }

    .amap-ui-poi-picker-sugg,
    .amap_lib_placeSearch {
        border: 1px solid #eee;
        border-radius: 4px;
    }

    .amap-box {
        height: 400px;
    }
</style>

在组件中使用地图搜索组件,这里使用弹窗

<template>
    <el-dialog
            :title="title"
            :visible.sync="visible"
            :before-close="handleClose"
            width="60%"
            append-to-body
            :close-on-click-modal="false"
            :close-on-press-escape="false"
    >
        <div class="form-info">
            <el-form
                    :model="form"
                    ref="form"
                    :rules="rules"
                    size="small"
                    label-width="110px"
            >
                <el-form-item label="选择地址" prop="address">
                    <base-map-search
                            ref="mapSearch"
                            :city="form.city"
                            :value="form.address"
                            :longitude="form.lng"
                            :latitude="form.lat"
                            :isEdit="isEdit"
                            @updateLocation="updateLocation"
                    />
                </el-form-item>
                <el-row>
                    <el-col :span="12">
                        <el-form-item prop="lng" label="经度">
                            <el-input
                                    v-model.number="form.lng"
                                    :maxlength="15"
                                    placeholder="请输入经度"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" class="right-label-form-item">
                        <el-form-item prop="lat" label="纬度">
                            <el-input
                                    v-model.number="form.lat"
                                    :maxlength="15"
                                    placeholder="请输入纬度"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="handleClose">取消</el-button>
            <el-button type="success" @click="handleSave">保存</el-button>
        </div>
    </el-dialog>
</template>
<script>
import BaseMapSearch from '@/components/common/baseMapSearch'

export default {
  props: ['visible', 'isEdit', 'detail'],
  components: {
    BaseMapSearch
  },
  data() {
    return {
      title: '添加地址',
      form: {
        address: '',
        lng: '',
        lat: ''
      },
      rules: {
        address: [
          {
            required: true,
            message: '地址不为空',
            trigger: ['blur', 'change']
          }
        ],
        lng: [
          {
            required: true,
            message: '经度不为空',
            trigger: ['blur', 'change']
          }
        ],
        lat: [
          {
            required: true,
            message: '纬度不为空',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  created() {
    if (this.isEdit) {
      this.initForm()
    }
  },
  methods: {
    // 初始化表单
    initForm() {
      this.title = '修改地址'
      if (this.detail) {
        this.form = {...this.detail}
      }
    },
    // 地图搜索选址
    updateLocation(lng, lat, address) {
      this.form.lng = lng
      this.form.lat = lat
      this.form.address = address
    },
    handleClose() {
      this.$emit('closeVisible', false)
    },
    handleSave() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return
        }
        this.$emit('saveMap', this.form)
        this.$emit('closeVisible', false)
      })
    }
  }
}
</script>

如果项目中使用了ESlint,会报AMap、AMapUI未定义的错误,我们需要在.eslintrc.js文件中定义globals属性:

module.exports = {
    // ...
    globals: {
      AMap: false,
      AMapUI: false
    }
}

效果:

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
vue-amap是一个Vue插件,可以在Vue框架中使用高德地图实现地图搜索和地址定位功能。通过引入"vue-amap"插件,可以在Vue项目中使用高德地图的API来实现相关功能。 具体实现步骤如下: 1. 首先,在Vue项目中安装"vue-amap"插件,可以通过运行命令npm install vue-amap来安装。 2. 在需要使用地图的组件中,引入并注册"vue-amap"插件。可以在组件中使用Vue.use()方法来注册插件,并配置高德地图的API密钥和插件所需的其他参数。 3. 在组件模板中,使用"vue-amap"插件提供的组件来显示地图。可以使用<el-amap>标签来展示地图,并设置其相关属性,如中心点、缩放级别等。 4. 实现地图搜索功能,可以使用"vue-amap"插件提供的<el-amap-search>组件。通过监听用户输入的地址,在搜索框中输入地址后,通过调用插件提供的搜索方法,即可在地图上显示搜索结果的位置。 5. 实现点击定位功能,可以通过监听地图的点击事件,在用户点击地图后获取点击的位置坐标,并在地图上展示标记点。同时,可以通过控制标记点的显示和隐藏,实现上一个标记点消失的效果。 总结起来,通过使用vue-amap插件,可以在Vue框架中轻松实现地图搜索和地址定位功能。通过搜索框输入地址进行搜索,并在地图上显示搜索结果的位置,同时可以通过点击地图实现定位,并在地图上展示标记点。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [vue使用vue-amap插件(高德地图插件实现定位、搜索、marker标记点)](https://blog.csdn.net/ccyolo/article/details/115916371)[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^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [vue+高德地图实现地图搜索及点击定位操作](https://download.csdn.net/download/weixin_38624519/12923390)[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^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [“vue-amap“: “^0.5.10“, 高德地图 vue版本 H5地图 实现根据地名搜索坐标,经纬度](https://blog.csdn.net/Li_Ning21/article/details/121986013)[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^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值