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

相关文章

Java 接口定义变量的示例代码

《Java接口定义变量的示例代码》文章介绍了Java接口中的变量和方法,接口中的变量必须是publicstaticfinal的,用于定义常量,而方法默认是publicabstract的,必须由实现类... 在 Java 中,接口是一种抽象类型,用于定义类必须实现的方法。接口可以包含常量和方法,但不能包含实例

使用Redis实现会话管理的示例代码

《使用Redis实现会话管理的示例代码》文章介绍了如何使用Redis实现会话管理,包括会话的创建、读取、更新和删除操作,通过设置会话超时时间并重置,可以确保会话在用户持续活动期间不会过期,此外,展示了... 目录1. 会话管理的基本概念2. 使用Redis实现会话管理2.1 引入依赖2.2 会话管理基本操作

mybatis-plus分表实现案例(附示例代码)

《mybatis-plus分表实现案例(附示例代码)》MyBatis-Plus是一个MyBatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生,:本文主要介绍my... 目录文档说明数据库水平分表思路1. 为什么要水平分表2. 核心设计要点3.基于数据库水平分表注意事项示例

Nginx服务器部署详细代码实例

《Nginx服务器部署详细代码实例》Nginx是一个高性能的HTTP和反向代理web服务器,同时也提供了IMAP/POP3/SMTP服务,:本文主要介绍Nginx服务器部署的相关资料,文中通过代码... 目录Nginx 服务器SSL/TLS 配置动态脚本反向代理总结Nginx 服务器Nginx是一个‌高性

HTML5的input标签的`type`属性值详解和代码示例

《HTML5的input标签的`type`属性值详解和代码示例》HTML5的`input`标签提供了多种`type`属性值,用于创建不同类型的输入控件,满足用户输入的多样化需求,从文本输入、密码输入、... 目录一、引言二、文本类输入类型2.1 text2.2 password2.3 textarea(严格

JAVA项目swing转javafx语法规则以及示例代码

《JAVA项目swing转javafx语法规则以及示例代码》:本文主要介绍JAVA项目swing转javafx语法规则以及示例代码的相关资料,文中详细讲解了主类继承、窗口创建、布局管理、控件替换、... 目录最常用的“一行换一行”速查表(直接全局替换)实际转换示例(JFramejs → JavaFX)迁移建

Go异常处理、泛型和文件操作实例代码

《Go异常处理、泛型和文件操作实例代码》Go语言的异常处理机制与传统的面向对象语言(如Java、C#)所使用的try-catch结构有所不同,它采用了自己独特的设计理念和方法,:本文主要介绍Go异... 目录一:异常处理常见的异常处理向上抛中断程序恢复程序二:泛型泛型函数泛型结构体泛型切片泛型 map三:文

Java使用Spire.Barcode for Java实现条形码生成与识别

《Java使用Spire.BarcodeforJava实现条形码生成与识别》在现代商业和技术领域,条形码无处不在,本教程将引导您深入了解如何在您的Java项目中利用Spire.Barcodefor... 目录1. Spire.Barcode for Java 简介与环境配置2. 使用 Spire.Barco

MyBatis中的两种参数传递类型详解(示例代码)

《MyBatis中的两种参数传递类型详解(示例代码)》文章介绍了MyBatis中传递多个参数的两种方式,使用Map和使用@Param注解或封装POJO,Map方式适用于动态、不固定的参数,但可读性和安... 目录✅ android方式一:使用Map<String, Object>✅ 方式二:使用@Param

SpringBoot返回文件让前端下载的几种方式

《SpringBoot返回文件让前端下载的几种方式》文章介绍了开发中文件下载的两种常见解决方案,并详细描述了通过后端进行下载的原理和步骤,包括一次性读取到内存和分块写入响应输出流两种方法,此外,还提供... 目录01 背景02 一次性读取到内存,通过响应输出流输出到前端02 将文件流通过循环写入到响应输出流