vue-amap实现实现初始化并定位当前位置,搜索,定位,增加点标记

article/2025/7/11 17:02:59

实现如图展示,初始化并定位当前位置,搜索,定位,增加点标记
在这里插入图片描述
下载vue

1.vue页设置

  • 如果是新版web-js的密钥,有配套的安全秘钥,则需要另外在created加入,否则会报undefined
window._AMapSecurityConfig = {securityJsCode:'你的安全秘钥',}
<template><div class="bg-body" style="min-width: 1100px"><el-input class="mgt10" v-model="showName" placeholder="请选择地图" @change="searchLng"><template slot="suffix"><i @click="showDialog" class="el-icon-location-information"></i></template></el-input><el-dialog title="选择地点" :visible.sync="dialogFormVisible"><div style="height: 400px;width: 100%"><div class="flex-l-b"><el-amap-search-box class="search-box" :search-option="searchOption":on-search-result="onSearchResult"></el-amap-search-box><span class="mgl10">{{form.address}}{{form.longitude}},{{form.latitude}}</span><el-button type="primary" @click="sureMap">确定</el-button></div><div><base-map-searchref="mapSearch":city="form.city":value="form.address":longitude="form.longitude":latitude="form.latitude":isEdit="isEdit":center="center"@updateLocation="updateLocation"/></div></div></el-dialog></div>
</template><script>import BaseMapSearch from '@/components/pd/common/map'import axios from 'axios'import Vue from 'vue'import VueAMap from 'vue-amap';Vue.use(VueAMap);VueAMap.initAMapApiLoader({// 高德的keykey: '你的key',// 插件集合plugin: ['AMap.Autocomplete','AMap.Geolocation', 'AMap.AMapUI', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.CircleEditor','AMap.Geocoder','AMap.CitySearch'],// 高德 sdk 版本,默认为 1.4.4v: '1.4.4'});export default {name: "add-station",components: {BaseMapSearch,},data () {return {editPlantObj:{},editPlantId:'',//地图// tan:false,//地图判断是否isEdit:false,//地图判断是否center: [112.320331, 40.012928],form2:{province:'',city:'',county:'',imei:'',deviceType:"",plantName:"",address: '',lang:'zh',},form: {address: '',longitude: '',latitude: '',provinceCode:'',cityCode:'',countyCode:'',},dialogFormVisible: false,form1:{province:'',city:'',county:'',imei:'',deviceType:"",plantName:"",address: '',lang:'zh',},url:'https://www.baidu.com/',}},computed:{showName(){return this.form1.province + this.form1.city+this.form1.county}},//form的address是完整的,form1.address是详细地址methods: {//展示地图showDialog(){if(this.editPlantId){this.isEdit=truethis.searchLng()}this.dialogFormVisible=true},checkData(data){this.editPlantObj=datathis.form1=datathis.form1.address=data.addressthis.form.address=data.province+data.city+data.county+data.addressthis.secondTab=data.deviceList},//填写详细地址后,请求经纬度searchLng(){let key='你的key'axios.get(`https://restapi.amap.com/v3/geocode/geo?key=${key}&s=rsv3&city=35&address=${this.form.address}`).then( (response) => {// this.$alert('已根据填写信息定位,如有偏差,请自行点击地图选取!', '确认地址', {//   confirmButtonText: '确定',//   callback: action => {//     this.dialogFormVisible=true//   }// });}).catch( (error) => {console.log(error)// this.dialogFormVisible=false});},sureMap(){let key='你的key'axios.get(`https://restapi.amap.com/v3/geocode/regeo?key=${key}&s=rsv3&city=35&location=${this.form.longitude+','+this.form.latitude}`).then( (response) => {console.log(response)this.form1.address=response.data.regeocode.formatted_address.substring(this.showName.length)// //取出选择器// let item={//     cityCode:obj.adcode.substring(0,4),//     city:obj.city,//     countyCode:obj.adcode.substring(0,6),//     county:obj.district,//     index:0// }// //两种情况,一种选择地址后 地图取点。一种是直接取点,// this.reqNextArea(provinceCode,'cityList',item)//// //详细地址// let str=obj.province+obj.city+obj.district// this.formData.detailAddress=response.data.regeocode.formatted_address.substring(str.length)// console.log(response.data.geocodes);// let location=obj.location.split(',')// console.log(location)// this.form.longitude = location[0]// this.form.latitude = location[1]// this.form.address = this.showNamethis.center = [this.form.longitude, this.form.latitude]this.isEdit=false}).catch( (error) => {console.log(error);});this.dialogFormVisible=false},// 地图搜索选址updateLocation(lng, lat, address) {this.form.longitude = lngthis.form.latitude = latthis.form.address = addressthis.center = [lng, lat]},searchOption(pois) {console.log(pois)},onSearchResult(pois) {//点击搜索后触发的事件this.input = document.querySelector('.search-box-wrapper input').value//这边类似模糊查询 会返回一个数组,我就直接取第一个值了。this.center = [pois[0].lng, pois[0].lat]this.form.longitude = pois[0].lngthis.form.latitude = pois[0].latthis.form.address = pois[0].address},handleClick(tab, event) {console.log(tab, event);},onSubmit() {console.log('submit!');}},}
</script><style lang="scss">.search-box {margin-top: 6px;width: 100%;}.el-vue-search-box-container {/*width: 100% !important;*/margin-bottom: 10px;}.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:280px;position: absolute;top: 72px;z-index: 10000;overflow-y: auto;background-color: pink;}
</style>

子组件设置

<template><div style="height:300px"><!--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  type="text/javascript" src="https://webapi.amap.com/maps?v=2.0;key=你的key&plugin=AMap.Geolocation"></script>
//不记得是为什么添加这个了<script>import { AMapManager, lazyAMapApiLoaderInstance } from "vue-amap";let amapManager = new AMapManager();export default {props: ["city", "value", "longitude", "latitude", "isEdit", "center"],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) {console.log(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 = new AMap.Geocoder({radius: 10000,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.$emit("updateLocation", lng, lat, self.searchKey);self.$nextTick();}}});}},// 一些工具插件plugin: [{// 定位showMaker:true,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 {// 设置经度self.lng = result.position.lng;// 设置维度self.lat = result.position.lat;// 设置坐标self.center = [self.lng, self.lat];self.markers.push([self.lng, self.lat]);self.$emit("updateLocation", self.lng, self.lat, result.formattedAddress);}// loadself.loaded = true;// 页面渲染好后self.$nextTick();}});}}},{// 定位城市pName: "CitySearch",events: {init(o) {// o是高德地图定位插件实例o.getLocalCity(function(status, result) {if (status === "complete" && result.info === "OK") {// 查询成功,result即为当前所在城市信息console.log(result)}});}}},]};},created() {console.log(this.center)console.log(this.value)this.getLocation()if (this.value) {console.log(this.center)this.searchKey = this.value;this.address = this.value;this.markers.push(this.center);}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]);}if(this.center){this.markers.push(this.center);}},methods: {getLocation() {const that = this;AMap.plugin("AMap.Geolocation", function() {var geolocation = new AMap.Geolocation({// 是否使用高精度定位,默认:trueenableHighAccuracy: true,// 设置定位超时时间,默认:无穷大timeout: 10000,// 定位按钮的停靠位置的偏移量,默认:Pixel(10, 20)buttonOffset: new AMap.Pixel(10, 20),//  定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:falsezoomToAccuracy: true,//  定位按钮的排放位置,  RB表示右下buttonPosition: "RB"});geolocation.getCurrentPosition();AMap.event.addListener(geolocation, "complete", onComplete);AMap.event.addListener(geolocation, "error", onError);function onComplete(data) {// data是具体的定位信息console.log(data);}function onError(data) {// 定位出错console.log(data);// 失败之后调用这个方法,使用IP定位获取当前城市信息that.getLngLatLocation();}});},// IP定位获取当前城市信息getLngLatLocation() {AMap.plugin("AMap.CitySearch", function() {var citySearch = new AMap.CitySearch();citySearch.getLocalCity(function(status, result) {if (status === "complete" && result.info === "OK") {// 查询成功,result即为当前所在城市信息console.log(result)}});});},searchOption(pois){console.log(pois)},onSearchResult(pois){//点击搜索后触发的事件this.input = document.querySelector(".search-box-wrapper input").value//这边类似模糊查询 会返回一个数组,我就直接取第一个值了。this.center = [pois[0].lng, pois[0].lat];this.markers.push([pois[0].lng, pois[0].lat]);},// 选择地址后自动定位到当前地址附近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) {console.log(PoiPicker)let poiPicker = new PoiPicker({input: "search",placeSearchOptions: {map: map,pageSize: 10},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.namevm.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() {console.log('zh ')// if (this.searchKey !== "" && this.poiPicker) {this.poiPicker.searchByKeyword(this.searchKey);// }}},watch:{center:function(val) {this.markers.push(val);}}};
</script>
<style lang="scss">.search-box {margin-top: 6px;width: 100%;}.el-vue-search-box-container {/*width: 100% !important;*/margin-bottom: 10px;}.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:280px;position: absolute;top: 72px;z-index: 10000;overflow-y: auto;background-color: pink;}
</style>
<style>.amap-ui-poi-picker-sugg,.amap_lib_placeSearch {border: 1px solid #eee;border-radius: 4px;}.amap-box {height: inherit;}</style>

http://chatgpt.dhexx.cn/article/Y9Q5X5e9.shtml

相关文章

vue3定位当前位置,获取当前位置的经纬度

vue3定位当前位置&#xff0c;获取当前位置的经纬度 注意事项&#xff08;访问地址必须是https&#xff09;获取当前位置经纬度 注意事项&#xff08;访问地址必须是https&#xff09; 在vue.config.js文件内设置https:true&#xff0c;然后重启一下项目 获取当前位置经纬度 …

新建文本文档

使用百度地图&#xff0c;定位你当前位置并显示 1、准备 注册百度开发者账号到百度地图开放平台创建应用&#xff08;as获取SHA1值&#xff09; 2、将sdk整到你的项目中去 - 在你app的gradle.build中添加 dependencies {...... compile files(libs/baidumapapi_base_v4_0…

web端定位:获取当前地理位置

2019独角兽企业重金招聘Python工程师标准>>> 方法一:html5原生提供的定位: 讲解:在支持HTML5的浏览器下,navigator对象下有一个属性----geolocation,而geolocation属性又有个方法getCurrentPosition(回调函数1,回调函数2)可以通过浏览器向设备发起定位请求,浏…

uniapp 之定位当前位置 (uni.getLocation,腾讯地图,javascript)

第一种 uniapp uniapp 封装的方法可以拿到城&#xff0c;市&#xff0c;县&#xff0c;经纬度。 实例&#xff1a; //获取位置GetLOcation: function() {var that this;uni.getLocation({type: gcj02,success: (res) > {console.log(res)var latitude parseFloat(res.la…

爆款专栏《Python 黑科技》目录导航丨进度:12/50

《Python 快速入门专栏丨掌握基础》和《Python 黑科技丨练习应用》由 CSDN 博客专家丨全站排名 Top 8 的硬核博主 不吃西红柿 倾力打造&#xff0c;旨在帮助大家快速入门掌握 Python。 更有学习资料&#xff0c;简历和 PPT 模板&#xff0c;微信公众号 【信息技术智库】关注我&…

安卓12解除进程限制方法汇总

一、关于安卓12 使用VMOS PRO 借助电脑激活步骤 第一步&#xff0c;使用usb线将手机连接至电脑。 第二步&#xff0c;打开手机的“开发者选项”&#xff0c;打开USB调试开关&#xff0c;确保手机已进入USB调试模式。 第三步&#xff0c;将激活程序包&#xff08;vmos_activa…

电脑技巧:推荐五款非常棒的小众软件,值得收藏

目录 1、Foodie&#xff08;美食相机&#xff09; 2、黑阈APP 3、Sleep Cycle 睡眠助手APP 4、烧杯——化验APP 5、123看图器 今天小编给大家分享五款非常棒的小众软件&#xff0c;生活中非常实用&#xff0c;感兴趣的朋友欢迎收藏&#xff01; 1、Foodie&#xff08;美食相…

永恒之黑漏洞复现

永痕之黑 1. 永恒之黑漏洞相关信息 漏洞介绍 https://nvd.nist.gov/vuln/detail/CVE-2020-0796 漏洞影响版本&#xff1a; Windows 10 Version 1903 for 32-bit Systems Windows 10 Version 1903 for x64-based Systems Windows 10 Version 1903 for ARM64-based Systems Wi…

手机技巧:推荐一款手机省电、提升流畅度APP

目录 软件详情 基本介绍 软件功能 软件特色 使用方法 软件对比 结论 今天给大家推荐一款手机省电、提升流畅度APP&#xff0c;感兴趣的朋友可以下载一下&#xff01; 软件详情 黑阈app是一款非常实用的系统优化类手机APP。使用它能够禁止软件后台运行耗电&#xff0c;既…

linux usb 黑 白 名单_安卓手机如何一键提升手机性能?用黑阈

安卓手机现状 安卓现在的旗舰机并不比苹果差&#xff0c;但是依然对手机小白很不友好&#xff0c;安卓属于开源&#xff0c;自由度较大&#xff0c;可供发挥的空间更高。需要一定基础才能充分利用安卓的性能。而苹果依然是针对小白的&#xff0c;系统会自行优化&#xff0c;自由…

如何root安卓手机_安卓手机如何一键提升手机性能?用黑阈

安卓手机现状 安卓现在的旗舰机并不比苹果差&#xff0c;但是依然对手机小白很不友好&#xff0c;安卓属于开源&#xff0c;自由度较大&#xff0c;可供发挥的空间更高。需要一定基础才能充分利用安卓的性能。而苹果依然是针对小白的&#xff0c;系统会自行优化&#xff0c;自由…

黑阈使用方法

一、从各大应用市场载「 黑阈 」。 二、切换到「 使用 」的页面&#xff0c;选择「 进入黑阈 」 三、打开「 开发者选项 」跟 「 USB调试 」 四、连接 USB &#xff0c;允许 USB 调试 五、电脑打开下面这个网页&#xff0c;下载相应的 SDK。 https://developer.android.goo…

使用树莓派3b+作为黑阈激活器

黑阈&#xff08;y&#xff09;不需要 root 就能待机&#xff08;App Standby&#xff0c;Android 6.0 引入&#xff0c;部分设备不支持&#xff09;或强行停止应用&#xff0c;防止应用持续运行。 黑阈不处理非“黑阈清单”内应用。当您启动应用&#xff0c;使用完退出&#x…

枚举类型是什么

C语言详解 - 枚举类型 注&#xff1a;以下全部代码的执行环境为VC 6.0 在程序中&#xff0c;可能需要为某些整数定义一个别名&#xff0c;我们可以利用预处理指令#define来完成这项工作&#xff0c;您的代码可能是&#xff1a; #define MON 1 #define TUE 2 #define WED 3 …

ts枚举类

参考官方文档:https://www.tslang.cn/docs/handbook/enums.html 理解:枚举是列举固定几个值,直接定义变量的话的话可以随意定义&#xff0c;枚举只能使用你定义好的几个值,枚举是个类&#xff0c;定义的值是基本类型,类能有更多操作 例如你定义一个方法接收一个参数&#xff0…

Java 枚举类型原理分析为什么枚举比用静态变量多消耗两倍的内存

一 起源&#xff1a;枚举是一种特殊的数据类型&#xff0c;一般用来列举有限个、同类型的常量。它能保证参数的安全性&#xff0c;如方法声明传入的参数&#xff0c;必须是指定枚举中的常量。但是Android开发文档指出&#xff0c;使用枚举会比使用静态变量多消耗2倍内存。为什么…

java枚举转json

1、背景 java后端的枚举类型&#xff0c;要展示到前端&#xff0c;提供给用户进行下拉选择&#xff0c;java后端需要封装enum为json字符串提供给前端&#xff0c;需要首先将枚举类型转为list&#xff0c;然后再转为json字符串。 2、方案 方案也很简单&#xff0c;使用EnumSe…

枚举类的使用

文章目录 前言一、自定义枚举类二、使用enum定义枚举类1.Enum类的主要方法2.实现接口的枚举类 前言 1&#xff09; 类的对象只有有限个&#xff0c;确定的。举例如下&#xff1a; 星期&#xff1a;Monday(星期一)、…、Sunday(星期天) 性别&#xff1a;Man(男)、Woman(女) 季节…

用户名枚举

一. 漏洞描述 常存在于系统登录界面&#xff0c;由于错误配置或设计缺陷&#xff0c;当向系统提交有效账户和无效账户时&#xff0c;服务器会有不同的响应&#xff0c;利用服务器响应的不同&#xff0c;攻击者可以获取到系统已经存在的账户&#xff0c;可用于暴力破解&#xff…

c++枚举

一、枚举类型的定义 枚举类型的定义&#xff1a;枚举类型(enumeration)是 C 中的一种派生数据类型&#xff0c;它是由用户定义的若干枚举常量的集合。 定义格式&#xff1a;枚举类型的定义格式为&#xff1a;enum <类型名> {<枚举常量表>}; 例如&#xff1a; en…