vue-amap生成坐标地址代码

2023-10-23 15:50

本文主要是介绍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-inputv-model="searchKey"type="search"id="search"placeholder="请输入详细地址"></el-input><!--<button @click="searchByHand">搜索</button>--><div class="tip-box" id="searchTip"></div></div><!--amap-manager: 地图管理对象vid:地图容器节点的IDzooms: 地图显示的缩放级别范围,在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-markerv-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 = thisreturn {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.lnglatself.lng = lngself.lat = latself.center = [lng, lat]self.markers.push([lng, lat])// 这里通过高德 SDK 完成。let geocoderAMap.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.formattedAddressself.searchKey = result.regeocode.formattedAddressself.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.cityself.updateAddress(address, result.position.lng, result.position.lat)self.poiPicker.searchByKeyword(self.searchKey)}// loadself.loaded = true// 页面渲染好后self.$nextTick()}})}}}]}},created() {if (this.value) {this.searchKey = this.valuethis.address = this.value}if (this.longitude && this.latitude) {this.lng = this.longitudethis.lat = this.latitudethis.center = [this.longitude, this.latitude]this.markers.push([this.longitude, this.latitude])}AMap.plugin(['AMap.Geolocation'], () => {var geolocation = new AMap.Geolocation({enableHighAccuracy: true, // 是否使用高精度定位,默认:truetimeout: 2000, // 超过2秒后停止定位,默认:无穷大zoomToAccuracy: false, // 定位成功后地图放最大,默认:falsebuttonPosition: 'LB', // 定位器左上下角buttonOffset: new AMap.Pixel(11, 20), // 定位器位置偏移showMarker: false})AMap.addControl(geolocation)})},methods: {// 选择地址后自动定位到当前地址附近updateAddress(value, longitude, latitude) {this.searchKey = valuethis.address = valuethis.lng = longitudethis.lat = latitudethis.center = [longitude, latitude]this.markers.push([longitude, latitude])},initSearch() {let vm = thislet 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.sourcelet poi = poiResult.itemif (source !== 'search') {poiPicker.searchByKeyword(poi.name)} else {poiPicker.clearSearchResults()vm.markers = []let lng = poi.location.lnglet lat = poi.location.lat// let address = poi.name // poi.cityname + poi.adname + poi.namelet address = poi.pname + poi.cityname + poi.adname + poi.address + poi.namevm.center = [lng, lat]vm.markers.push([lng, lat])vm.lng = lngvm.lat = latvm.address = addressvm.searchKey = addressvm.$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-searchref="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-inputv-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-inputv-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 = lngthis.form.lat = latthis.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}
}

效果:

这篇关于vue-amap生成坐标地址代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/268851

相关文章

SpringBoot中四种AOP实战应用场景及代码实现

《SpringBoot中四种AOP实战应用场景及代码实现》面向切面编程(AOP)是Spring框架的核心功能之一,它通过预编译和运行期动态代理实现程序功能的统一维护,在SpringBoot应用中,AO... 目录引言场景一:日志记录与性能监控业务需求实现方案使用示例扩展:MDC实现请求跟踪场景二:权限控制与

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

利用Python调试串口的示例代码

《利用Python调试串口的示例代码》在嵌入式开发、物联网设备调试过程中,串口通信是最基础的调试手段本文将带你用Python+ttkbootstrap打造一款高颜值、多功能的串口调试助手,需要的可以了... 目录概述:为什么需要专业的串口调试工具项目架构设计1.1 技术栈选型1.2 关键类说明1.3 线程模

Python Transformers库(NLP处理库)案例代码讲解

《PythonTransformers库(NLP处理库)案例代码讲解》本文介绍transformers库的全面讲解,包含基础知识、高级用法、案例代码及学习路径,内容经过组织,适合不同阶段的学习者,对... 目录一、基础知识1. Transformers 库简介2. 安装与环境配置3. 快速上手示例二、核心模

Java的栈与队列实现代码解析

《Java的栈与队列实现代码解析》栈是常见的线性数据结构,栈的特点是以先进后出的形式,后进先出,先进后出,分为栈底和栈顶,栈应用于内存的分配,表达式求值,存储临时的数据和方法的调用等,本文给大家介绍J... 目录栈的概念(Stack)栈的实现代码队列(Queue)模拟实现队列(双链表实现)循环队列(循环数组

使用Python从PPT文档中提取图片和图片信息(如坐标、宽度和高度等)

《使用Python从PPT文档中提取图片和图片信息(如坐标、宽度和高度等)》PPT是一种高效的信息展示工具,广泛应用于教育、商务和设计等多个领域,PPT文档中常常包含丰富的图片内容,这些图片不仅提升了... 目录一、引言二、环境与工具三、python 提取PPT背景图片3.1 提取幻灯片背景图片3.2 提取

HTML5中的Microdata与历史记录管理详解

《HTML5中的Microdata与历史记录管理详解》Microdata作为HTML5新增的一个特性,它允许开发者在HTML文档中添加更多的语义信息,以便于搜索引擎和浏览器更好地理解页面内容,本文将探... 目录html5中的Mijscrodata与历史记录管理背景简介html5中的Microdata使用M

html5的响应式布局的方法示例详解

《html5的响应式布局的方法示例详解》:本文主要介绍了HTML5中使用媒体查询和Flexbox进行响应式布局的方法,简要介绍了CSSGrid布局的基础知识和如何实现自动换行的网格布局,详细内容请阅读本文,希望能对你有所帮助... 一 使用媒体查询响应式布局        使用的参数@media这是常用的

HTML5表格语法格式详解

《HTML5表格语法格式详解》在HTML语法中,表格主要通过table、tr和td3个标签构成,本文通过实例代码讲解HTML5表格语法格式,感兴趣的朋友一起看看吧... 目录一、表格1.表格语法格式2.表格属性 3.例子二、不规则表格1.跨行2.跨列3.例子一、表格在html语法中,表格主要通过< tab

Vue3组件中getCurrentInstance()获取App实例,但是返回null的解决方案

《Vue3组件中getCurrentInstance()获取App实例,但是返回null的解决方案》:本文主要介绍Vue3组件中getCurrentInstance()获取App实例,但是返回nu... 目录vue3组件中getCurrentInstajavascriptnce()获取App实例,但是返回n