vue+高德地图实现地图搜索及点击定位操作


Posted in Javascript onSeptember 09, 2020

首先需要在index.html中引入高德地图的js链接,key需要换成你自己的key

最近有个需求是实现一个使用地图搜索定位的功能,在网上参考了下其他的文章,感觉不是很完善,自己整理了一下,可以实现点击定位,搜索列表定位等功能,可能有些地方是多余的,需要的自己看着改下

<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.14&key=你的key"></script>

效果图如下

vue+高德地图实现地图搜索及点击定位操作

下边就是实现过程

html部分

<template>
  <div id="wrap">
    <div id="searchWrap">
      <div class="searchWrap">
        <input type="text" v-model="address" @input="search"><button @click="search">搜索</button>
      </div>
      <div id="result" class="amap_lib_placeSearch" v-show="hide">
        <div class="amap_lib_placeSearch_list amap-pl-pc" v-for="(item,index) in poiArr"
           @click="openMarkerTipById(index,$event)"
           @mouseout="onmouseout_MarkerStyle(index+1,$event)"
           :key="index">
          <div class="poibox" style="border-bottom: 1px solid #eaeaea">
            <div class="amap_lib_placeSearch_poi poibox-icon" :class="index==selectedIndex?'selected':''">{{index+1}}</div>
            <div class="poi-img" v-if="item.url" :style="'background-image:url('+item.url+'?operate=merge&w=90&h=56&position=5)'"
            ></div>
            <h3 class="poi-title" >
              <span class="poi-name">{{item.name}}</span>
            </h3>
            <div class="poi-info">
              <p class="poi-addr">地址:{{item.address}}</p>
              <p class="poi-tel">电话:{{item.tel}}</p>
            </div>
            <div class="clear"></div>
          </div>
        </div>
      </div>
    </div>
    <div id="iCenter"></div>
    <button class="btn" @click="fetAddressName">获取当前位置和名字</button>
  </div>
</template>

js部分

<script>
 export default {
  props:['newAddress','dataObj'],// 父组件传过来的地址和地址经纬度信息,
  data() {
   return {
    address:this.newAddress ? this.newAddress : '郑州',//保存地址的汉字名字
    map1: '',
    map:'',//保存地址的经纬度
    poiArr: [],//左边搜索出来的数组
    windowsArr: [],//信息窗口的数组
    marker: [],
    mapObj: "",//地图对象
    selectedIndex: -1,
    hide: false,
    clickType: 1,
    location:{
     P:this.dataObj.lat,
     Q:this.dataObj.lng,
    }
   };
  },
  mounted() {
   console.log(333,this.dataObj,this.location)
   this.mapInit()
   this.placeSearch(this.address)

  },
  methods: {
   showToast(address){
    this.placeSearch(address.address)
    console.log(444,address)
    this.location.P =address.lat
    this.location.Q =address.lng
    this.address = address.address
    let that = this;
    new AMap.InfoWindow({
     content:"<h3>" + '当前选中地址' + "</h3>" + that.address,
     size: new AMap.Size(300, 0),
     autoMove: true,
     offset: new AMap.Pixel(-4, -10)
    }).open(that.mapObj,that.location)
   },
   cancelSave(){
    eventBus.$emit('cancelSave')
   },
   saveAddress(){
    let addressName,location;
    if(this.clickType==1){
     let address = this.poiArr[this.selectedIndex]
     addressName = address.name+address.address;
     location = address.location
     console.log(address.name+address.address,address.location)

    }else if(this.clickType==2){
     console.log(this.address,this.map)
     addressName = this.address;
     location = this.map;
    }else if(this.clickType==3){
     console.log(this.address,this.map1)
     addressName = this.address;
     location = this.map1;
    }
    eventBus.$emit('saveAddress',[addressName,location])
   },
   // 经纬度转化为详细地址
   getAddress(){
    let that = this;
    AMap.plugin('AMap.Geocoder',function(){
     let geocoder = new AMap.Geocoder({
      radius: 100,
      extensions: "all"
     });
     geocoder.getAddress([that.map1.lng,that.map1.lat], function(status, result) {
      if (status === 'complete' && result.info === 'OK') {
       let address = result.regeocode.formattedAddress;
       console.log(result.regeocode);
       that.address = result.regeocode.formattedAddress;
       // that.placeSearch(that.address)
      }
     });
    })
   },
   // 地图点击事件
   testevent(){
    let that = this;
    this.clickType = 3
    // var map=new AMap.Map('iCenter');//重新new出一个对象,传入参数是div的id
    AMap.event.addListener(this.mapObj,'click',function (e) { //添加点击事件,传入对象名,事件名,回调函数
     that.map1 = e.lnglat;
     that.getAddress();
     setTimeout(()=>{
      new AMap.InfoWindow({
       content:"<h3>" + '当前选中地址' + "</h3>" + that.address,
       size: new AMap.Size(300, 0),
       autoMove: true,
       offset: new AMap.Pixel(-4, -10)
      }).open(that.mapObj,e.lnglat)
     },100)
    })
   },
   //创建一个map
   mapInit() {
    this.mapObj = new AMap.Map("iCenter", {
     resizeEnable: true,
     zoom: 10,
    })
    this.testevent();
   },
   //根据名字地址去搜索结果
   placeSearch(name) {
    let that = this;
    this.hide = true
    var MSearch;
    this.mapObj.plugin(
     ["AMap.PlaceSearch", "AMap.ToolBar", "AMap.Scale"],
     () => {
      this.mapObj.addControl(new AMap.ToolBar())
      this.mapObj.addControl(new AMap.Scale())
      MSearch = new AMap.PlaceSearch({
       //构造地点查询类
       city: that.address //城市
      });
      AMap.event.addListener(MSearch,"complete",this.keywordSearch_CallBack) //返回地点查询结果
      MSearch.search(name); //关键字查询
     }
    );
   },
   //结果的回调
   keywordSearch_CallBack(data) {
    console.log(111,data)
    var poiArr = data.poiList.pois
    var resultCount = poiArr.length
    this.poiArr = poiArr; //左边要渲染的数据
    for (var i = 0; i < resultCount; i++) {
     this.addmarker(i, poiArr[i])
     console.log(poiArr[i])
     this.poiArr[i].url = this.poiArr[i].photos? this.poiArr[i].photos[0]? this.poiArr[i].photos[0].url: "": ""
    }
    this.mapObj.setFitView()
   },
   //添加marker&infowindow
   addmarker(i, d) {
    var lngX = d.location.getLng();
    var latY = d.location.getLat();
    console.log(lngX,latY)
    var markerOption = {
     map: this.mapObj,
     position: new AMap.LngLat(lngX, latY)
    };
    var mar = new AMap.Marker(markerOption);
    this.marker.push(new AMap.LngLat(lngX, latY));
    var infoWindow = new AMap.InfoWindow({
     content: "<h3>" +'当前选中位置:'+ d.name + "</h3>" + this.TipContents(d.name, d.address),
     size: new AMap.Size(300, 0),
     autoMove: true,
     offset: new AMap.Pixel(0, -30)
    });
    console.log()
    this.windowsArr.push(infoWindow);
    var _this = this;
    var aa = (e) => {
     this.clickType = 2
     var obj = mar.getPosition();
     this.map = obj //这里保存的地址经纬度
     this.address = d.name + d.address //这里保存的是地址名字
     infoWindow.open(_this.mapObj, obj);
    }
    AMap.event.addListener(mar, "click", aa)
   },
   TipContents(name, address) {
    //窗体内容
    if (
     name == "" ||
     name == "undefined" ||
     name == null ||
     name == " undefined" ||
     typeof name == "undefined"
    ) {
     type = "暂无";
    }
    if (
     address == "" ||
     address == "undefined" ||
     address == null ||
     address == " undefined" ||
     typeof address == "undefined"
    ) {
     address = "暂无";
    }
    var str = `地址:${address}`
    return str
   },
   openMarkerTipById(pointid, event) {
    //根据id 打开搜索结果点tip
    this.clickType = 1
    event.currentTarget.style.background = "#CAE1FF";
    this.selectedIndex = pointid
    // this.map = this.marker[pointid]
    this.map1 = this.poiArr[pointid].location
    console.log(222,this.mapObj, this.marker[pointid])
    console.log(this.marker[pointid],this.poiArr[pointid])
    this.address = this.poiArr[pointid].address + this.poiArr[pointid].name
    this.windowsArr[pointid].open(this.mapObj, this.marker[pointid])


   },
   onmouseout_MarkerStyle(pointid, event) {
    //鼠标移开后点样式恢复
    event.currentTarget.style.background = ""
   },
   search() {
    this.windowsArr = []
    this.marker = []

    this.mapObj=''
    this.mapInit()
    this.placeSearch(this.address)
   }
  },
 };
</script>

css部分

<style lang="scss">
  #wrap{
    width:100%;
    display: flex;
    #iCenter {
      height: 600px;
      position: relative;
      display: flex;
      flex: 1;
    }
    #searchWrap{
      width:300px;
      position: relative;
      height:600px;
      .searchWrap{
        position: absolute;
        width:300px;
        z-index: 9;
        display: flex;
        align-items: center;
        input{
          width:260px;
          height:24px;
        }
        button{
          width:36px;
          height:28px;
        }
      }
      #result {
        width: 300px;
        position: absolute;
        top:30px;
        height: 570px;
        z-index: 8;
        overflow-y: scroll;
        border-right: 1px solid #ccc;
      }
    }
    .amap_lib_placeSearch {
      height: 100%;
      overflow-y: scroll;
      .poibox {
        border-bottom: 1px solid #eaeaea;
        cursor: pointer;
        padding: 5px 0 5px 10px;
        position: relative;
        min-height: 35px;
        .selected {
          background-image: url(https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png) !important;
        }
        &:hover {
          background: #f6f6f6;
        }
        .poi-img {
          float: right;
          margin: 3px 8px 0;
          width: 90px;
          height: 56px;
          overflow: hidden;
        }
        .poi-title {
          margin-left: 25px;
          font-size: 13px;
          overflow: hidden;
        }
        .poi-info {
          word-break: break-all;
          margin: 0 0 0 25px;
          overflow: hidden;
          p {
            color: #999;
            font-family: Tahoma;
            line-height: 20px;
            font-size: 12px;
          }
        }
        .poibox-icon {
          margin-left: 7px;
          margin-top: 4px;
        }
        .amap_lib_placeSearch_poi {
          background: url(https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png)
          no-repeat;
          height: 31px;
          width: 19px;
          cursor: pointer;
          left: -1px;
          text-align: center;
          color: #fff;
          font: 12px arial, simsun, sans-serif;
          padding-top: 3px;
          position: absolute;
        }
      }
    }
    .btn{
      position: fixed;
      bottom:20px;
      left:50%;
      padding:10px;
    }
  }
</style>

补充知识:vue-amap 高德地图定位 点击获取经纬度和具体地址的使用

官方文档地址: 点这里!!

vue+高德地图实现地图搜索及点击定位操作

经纬度获取只要通过点击事件就可以通过e.lnglat来获取,然后就是插件Geocoder使用了。在main.js中initAMapApiLoader中写入:AMap.Geocoder,注意 官方文档中有提示:

vue+高德地图实现地图搜索及点击定位操作

所以插件中使用的依然是AMap,与导入名无关

vue+高德地图实现地图搜索及点击定位操作

不然会报错,Geocoder无法使用。

定位文档 照着文档写就行 注意在main.js中注册AMap.Geolocation插件,

另外使用到地图的.vue页面 不能使用scoped对样式进行局域化。

以上这篇vue+高德地图实现地图搜索及点击定位操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
javaScript parseInt字符转化为数字函数使用小结
Nov 05 Javascript
js setTimeout opener的用法示例详解
Oct 23 Javascript
jquery实现邮箱自动补全功能示例分享
Feb 17 Javascript
JavaScript实现垂直向上无缝滚动特效代码
Nov 23 Javascript
js实现点击每个li节点,都弹出其文本值及修改
Dec 15 Javascript
Node做中转服务器转发接口
Oct 18 Javascript
web前端vue之CSS过渡效果示例
Jan 10 Javascript
实现vuex与组件data之间的数据同步更新方式
Nov 12 Javascript
微信公众号服务器验证Token步骤图解
Dec 30 Javascript
JavaScript使用canvas绘制随机验证码
Feb 17 Javascript
原生Js 实现的简单无缝滚动轮播图的示例代码
May 10 Javascript
vue项目中的支付功能实现(微信支付和支付宝支付)
Feb 18 Vue.js
vue实现几秒后跳转新页面代码
Sep 09 #Javascript
JS异步宏队列微队列原理详解
Sep 09 #Javascript
vue 项目软键盘回车触发搜索事件
Sep 09 #Javascript
基于原生JS封装的Modal对话框插件的示例代码
Sep 09 #Javascript
vue监听浏览器原生返回按钮,进行路由转跳操作
Sep 09 #Javascript
JS实现斐波那契数列的五种方式(小结)
Sep 09 #Javascript
JavaScript代码简化技巧实例解析
Sep 09 #Javascript
You might like
jquery获取多个checkbox的值异步提交给php的方法
2015/06/24 PHP
PHP中的静态变量及static静态变量使用详解
2015/11/05 PHP
Ajax和PHP正则表达式验证表单及验证码
2016/09/24 PHP
常见效果实现之返回顶部(结合淡入、淡出、减速滚动)
2012/01/04 Javascript
关于jQuery参考实例2.0 用jQuery选择元素
2013/04/07 Javascript
JS 实现Table相同行的单元格自动合并示例代码
2013/08/27 Javascript
js实现图片放大和拖拽特效代码分享
2015/09/05 Javascript
jquery中checkbox使用方法简单实例演示
2015/11/24 Javascript
AngularJS入门教程引导程序
2016/08/18 Javascript
React实践之Tree组件的使用方法
2017/09/30 Javascript
Node.js学习教程之HTTP/2服务器推送【译】
2017/10/31 Javascript
vue实现导航栏效果(选中状态刷新不消失)
2017/12/13 Javascript
nodejs结合socket.io实现websocket通信功能的方法
2018/01/12 NodeJs
详解如何在webpack中做预渲染降低首屏空白时间
2018/08/22 Javascript
Vue2 监听属性改变watch的实例代码
2018/08/27 Javascript
Javascript之高级数组API的使用实例
2019/03/08 Javascript
[48:37]EG vs OG 2018国际邀请赛小组赛BO2 第一场 8.17
2018/08/18 DOTA
重命名批处理python脚本
2013/04/05 Python
python翻译软件实现代码(使用google api完成)
2013/11/26 Python
记录Django开发心得
2014/07/16 Python
有趣的python小程序分享
2017/12/05 Python
Python实现的简单读写csv文件操作示例
2018/07/12 Python
Django配置celery(非djcelery)执行异步任务和定时任务
2018/07/16 Python
pyqt 实现在Widgets中显示图片和文字的方法
2019/06/13 Python
Python-Seaborn热图绘制的实现方法
2019/07/15 Python
python图片剪裁代码(图片按四个点坐标剪裁)
2020/03/10 Python
使用CSS3来实现滚动视差效果的教程
2015/08/24 HTML / CSS
凯特方迪化妆品官网:Kat Von D Beauty
2016/11/15 全球购物
阿联酋手表和配饰购物网站:Rivolishop
2019/11/25 全球购物
艺术应用与设计个人的自我评价
2013/11/23 职场文书
安全事故检讨书
2014/01/18 职场文书
ktv好的活动方案
2014/08/15 职场文书
党员干部反四风对照检查材料思想汇报
2014/09/14 职场文书
解除租房协议书
2014/12/03 职场文书
2019感恩宣传标语!
2019/07/05 职场文书
创业计划书之健康营养产业
2019/10/15 职场文书