vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vue高德地图获取点击位置信息

vue使用高德地图实现添加点标记和获取点击位置信息的示例代码

作者:浮桥

这篇文章主要介绍了vue使用高德地图实现添加点标记和获取点击位置信息的示例代码,文中补充介绍了高德vue-amap使用(一)标记点位获取地址及经纬度,本文结合示例代码给大家介绍的非常详细,需要的朋友参考下吧

vue项目中使用高德地图实现添加点标记和获取点击位置信息

<template>
    <div class="container">
        <div id="map-container">地图</div>
    </div>
</template>
<script>
export default {
  name: '',
  components: {},
  data () {
    return {
      map: null,
      markers: [],
      markersPosition: [],
      geoCoder: null
    }
  },
  mounted () {
    this.mapInit()
  },
  methods: {
    mapInit () {
      // eslint-disable-next-line no-undef
      this.map = new AMap.Map('map-container', {
        zoom: 11, // 级别
        // center: [116.397428, 39.90923], // 中心点坐标
        // layers: [ // 使用多个图层
        //   // 卫星
        //   new AMap.TileLayer.Satellite(),
        //   // 路网
        //   new AMap.TileLayer.RoadNet()
        // ],
        resizeEnable: true
        // viewMode: '3D'// 使用3D视图
      })
      // eslint-disable-next-line no-undef
      this.geoCoder = new AMap.Geocoder()
      this.handlerMapClick()
    },
    handlerMapClick () {
      this.map.on('click', (e) => {
        // 点击坐标
        this.markersPosition = [e.lnglat.lng, e.lnglat.lat]
        this.removeMarker()
        // 设置新的标记
        this.setMapMarker()
        // eslint-disable-next-line no-undef
        // 根据坐标获取位置信息
        this.geoCoder.getAddress(this.markersPosition, (status, result) => {
          if (status === 'complete' && result.regeocode) {
            this.address = result.regeocode.formattedAddress
            console.log('点击位置信息:', result.regeocode.formattedAddress)
            // id
            let adcode = result.regeocode.addressComponent.adcode
            //   let reg = /.+?(省|市|自治区|自治州|县|区)/g
            let provinceId = parseInt(adcode.substr(0, 2) + '0000')
            let cityId = parseInt(adcode.substr(0, 4) + '00')
            let areaId = adcode
            console.log('点击位置的省市区id:', provinceId, cityId, areaId)
          }
        })
      })
    },
    // 设置点击位置的标记
    setMapMarker () {
      let marker = new AMap.Marker({
        map: this.map,
        position: this.markersPosition
      })
      // 将 markers 添加到地图
      this.markers.push(marker)
    },
    // 添加标记
    addMarker () {
      //   经度 纬度
      let lng = Math.random() * 135.05 + 73.3
      let lat = Math.random() * 53.33 + 3.51
      console.log('添加标记', [lng, lat])
      // 添加标记
      this.map.setFitView()
      let marker = new AMap.Marker({
        map: this.map,
        position: [lng, lat]
        // content: markerContent
        // eslint-disable-next-line
                // offset: new AMap.Pixel(-13, -30)
      })
      // 将 markers 添加到地图
      this.markers.push(marker)
      this.map.setFitView()`在这里插入代码片`
      // 鼠标点击marker弹出自定义的信息窗体
      // eslint-disable-next-line no-undef
      AMap.event.addListener(marker, 'click', function (e) {
        console.log('点击marker', e)
      })
    },
    // 删除之前后的标记点
    removeMarker () {
      if (this.markers) {
        this.map.remove(this.markers)
      }
    }
  }
}
</script>
<style scoped lang="scss">
#map-container {
    width: 70vw;
    height: 70vh;
}
</style>

高德vue-amap使用(一)标记点位获取地址及经纬度

图片示例

准备工作

高德开放平台:https://lbs.amap.com/

注册登录后进入控制台,在应用管理下我的应用里创建应用添加key,就可以看到你的安全密钥了

安装与配置

npm安装

npm install vue-amap --save

main.js配置

import VueAMap from 'vue-amap'; //引入高德地图
Vue.use(VueAMap);
VueAMap.initAMapApiLoader({
  key: '14efe7b9c0a51017c1ee7c641758ba69',
  plugin: [ // 这里根据自己项目按需引入插件
    'AMap.Autocomplete', 
    'AMap.PlaceSearch', 
    'AMap.Scale',
    'AMap.OverView', 
    'AMap.ToolBar',
    'AMap.MapType',
    'AMap.PolyEditor', 
    'AMap.CircleEditor',// 圆形编辑器插件
	"AMap.Geolocation", // 定位控件,用来获取和展示用户主机所在的经纬度位置
	"AMap.Geocoder", // 地理编码与逆地理编码服务,用于地址描述与坐标间的相互转换
	"AMap.CitySearch",
  ]
});
window._AMapSecurityConfig = {
  securityJsCode:'你的安全密钥',
}
// 解决高德地图刷新显示不出来
const amapKeys = Object.keys(localStorage).filter(key => key.match(/^_AMap_/))
amapKeys.forEach(key => { localStorage.removeItem(key) })

使用

父组件

1.html部分

<el-form-item label="设备位置">
  <el-button class="dev-product" @click="openMap()">
    <span class="text"  :class="mapInfo.lat?'active':''">{{addressTip}}</span><i class="el-icon-more"></i>
  </el-button>
  <div v-if="mapInfo.lat&&mapInfo.lng">经度:{{mapInfo.lng}},纬度:{{mapInfo.lat}}</div>
</el-form-item>
<el-dialog title="设备位置" :visible.sync="map" width="900px" id="map">
   <amap @mapDing="getCoordinate" :Nowlnglat="Nowlnglat"></amap>
   <div slot="footer" class="dialog-footer">
     <el-button @click="map = false" class="button-minwidth">{{$t('Base.cancels')}}</el-button>
     <el-button type="primary" @click="submitMap" class="button-minwidth">{{$t('Base.confirms')}}</el-button>
   </div>
</el-dialog>

2.js部分

<script>
import amap from "../map.vue"
export default {
  components: {amap},
  data() {
    return {
      addressTip:'请选择设备位置',
      map:false,
      mapInfo:{},
      Nowlnglat:[],//经纬度传值
      lng:113.03,
      lat:28.13
    }
  },
  methods: {
    openMap(){
      this.map=true
      if(this.lng&&this.lat){
        this.mapInfo={
          lng:this.lng,
          lat:this.lat
        }
        this.Nowlnglat=[this.lng,this.lat]
      }
    },
    getCoordinate(map){
      this.mapInfo=map
    },
    submitMap(){
      this.map=false
      this.addressTip=this.mapInfo.address
    }
  }
</script>

3.css部分

<style lang="scss" scoped>
  .dev-product{
    width: 300px;
    height: 32px;
    padding: 0 8px;
    display: flex;
    align-items: center;
  ::v-deep span{
    width: 100%;
    overflow: hidden;
    display: flex;
    justify-content: space-between;
    padding-left: 5px;
    .text{
      width: 92%;
      color: #c0c4cc;
    }.active{
      width: 92%;
      color: #303133 ;
    }
    i{
      color:#D8D8D8
    }
  }
}
</style>              

子组件

1.html部分

 <template>
  <div class="map-container">
    <div class="amap-page-container">
      <div class="input-search">
        <el-input class="inpu" placeholder="请输入检索地址" v-model="address">
        <template #suffix>
          <el-button icon="el-icon-search"  @click="searchMap()"></el-button>
        </template>
        </el-input>
      </div>
      <el-amap vid="amap" :plugin="plugin" class="amap-demo" :center="center" :zoom="zoom" :events='events'>
        <!-- 点击显示标记 -->
        <el-amap-marker v-for="(marker, index) in markers" :key="marker.index" :position="marker.position"
          :icon="marker.icon" :title="marker.title" :events="marker.events" :visible="marker.visible"
          :draggable="marker.draggable" :vid="index"></el-amap-marker>
      </el-amap>
      <div class="map-address">详细地址:{{address}}</div>
      <div class="map-mark">
        <div class="mark-item">
          <span>经度</span>
          <el-input placeholder="请输入经度" v-model="lng" maxlength="20"></el-input>
        </div>
        <div class="mark-item">
          <span>纬度</span>
          <el-input placeholder="请输入纬度" v-model="lat" maxlength="20"></el-input>
        </div> 
        <el-button class="mark" @click="handelQuery">查询</el-button>
      </div>
    </div>
  </div>
</template>

2.js部分

<script>
  export default {
    name: "v-map",
    props: ["Nowlnglat"],
    data() {
      let self = this;
      return {
        map:{
          address:'',
          lng:'',
          lat:''
        },
        tishi: '',
        //地图相关
        address: '', //获取的位置
        zoom: 13, // 地图缩放
        center: [122.59996, 26.197646], // 初始中心
        lng: 0, //经纬度
        lat: 0,
        loaded: false,
        markers: [],// 点击显示的标记默认的定位
        //  自动定位到当前位置
        plugin: [
          {
          timeout: 1000, //超过10秒后停止定位
          panToLocation: true, //定位成功后将定位到的位置作为地图中心点
          zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见
          pName: 'Geolocation',
          events: {
            init(o) {
              // o 是高德地图定位插件实例
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  self.address = result.formattedAddress;
                  self.lng = result.position.lng;
                  self.lat = result.position.lat;
                  self.map.address= self.address
                  self.map.lng=self.lng
                  self.map.lat=self.lat
                  if(self.Nowlnglat[0] != null && self.Nowlnglat[1] != null){
                    let  Clnglat =self.Nowlnglat
                    self.center =  Clnglat 
                    self.markers = [{position: Clnglat,}]
                    let geocoder = new AMap.Geocoder({radius: 1000});
                    //根据坐标获取位置  将经纬度 转换后成 地址信息 放在 输入框展示
                    geocoder.getAddress(Clnglat,function (status, result) {
                      if (status === "complete" && result.info === "OK") {
                        self.address=result.regeocode.formattedAddress
                        self.lng=self.Nowlnglat[0]
                        self.lat=self.Nowlnglat[1]
                        self.map.address= self.address
                        self.map.lng=self.lng
                        self.map.lat=self.lat
                      }
                    });
                  }else{
                    self.center = [self.lng, self.lat];
                    self.markers = [{position: self.center}]
                  }
                  self.loaded = true;
                  self.$nextTick();
                } else {
                  o.getCityInfo((status, result) => {
                    if (result && result.center) {
                      self.address = result.province+result.city;
                      self.lng = result.center[0];
                      self.lat = result.center[1];
                      self.map.address= self.address
                      self.map.lng=self.lng
                      self.map.lat=self.lat
                      if(self.Nowlnglat[0] != null && self.Nowlnglat[1] != null){
                        let  Clnglat =self.Nowlnglat
                        self.center =  Clnglat 
                        self.markers = [{position: Clnglat,}]
                        let geocoder = new AMap.Geocoder({radius: 1000});
                        //根据坐标获取位置  将经纬度 转换后成 地址信息 放在 输入框展示
                        geocoder.getAddress(Clnglat,function (status, result) {
                          if (status === "complete" && result.info === "OK") {
                            self.address=result.regeocode.formattedAddress
                            self.lng=self.Nowlnglat[0]
                            self.lat=self.Nowlnglat[1]
                            self.map.address= self.address
                            self.map.lng=self.lng
                            self.map.lat=self.lat
                          }
                        });
                      }else{
                        self.center = result.center;
                        self.markers = [{position: self.center,}]
                      }
                      self.loaded = true;
                      self.$nextTick();
                    }
                  });
                }
              });
            }
          }
        }
        ],
        // 点击地图获取当前位置并显示标记
        events: {
          click(e) {
            self.chaadd(e.lnglat)
          }
        }
      }
    },
    created() {
      this.$emit('mapDing', this.map);
    },
    methods: {
      searchMap() {
        let that = this;
        let address = this.address;
        that.map.address=that.address
        var geocoder = new AMap.Geocoder({
          city: "", //城市设为北京,默认:“全国”
        });
        geocoder.getLocation(address, function(status, result) {
          if (status === 'complete' && result.geocodes.length) {
            var lnglat = result.geocodes[0].location;
            that.center = [lnglat.lng, lnglat.lat]
            that.lng = lnglat.lng;
            that.lat = lnglat.lat;
            that.markers = [{
              position: that.center,
            }]
            that.map.lng=that.lng
            that.map.lat=that.lat
          } else {
            that.address=undefined
            that.lng=undefined
            that.lat=undefined
            that.$message({
              type: "error",
              message: "根据地址查询位置失败",
            });
          }
        });
        that.$emit('mapDing', that.map);
      },
      chaadd(e) {
        let self = this;
        let { lng, lat} = e;
        self.lng = lng;
        self.lat = lat;
        self.map.lng=self.lng
        self.map.lat=self.lat
        self.center = [self.lng, self.lat];
        self.loaded = true;
        self.markers = [{position: self.center,}]
        var geocoder = new AMap.Geocoder({
          radius: 1000 //范围,默认:500
        });
        var marker = new AMap.Marker();
        function regeoCode() {
          var lnglat = [lng, lat]
          geocoder.getAddress(lnglat, function(status, result) {
            if (status === 'complete' && result.regeocode) {
              self.address = result.regeocode.formattedAddress;
              self.map.address=self.address
            } else {
              self.address=undefined
              self.lng=undefined
              self.lat=undefined
              self.$message({
                type: "error",
                message: "根据经纬度查询地址失败",
              });
            }
          });
        }
        regeoCode();
         self.$emit('mapDing', self.map);
      },
      handelQuery(){
        let self =this
        self.map.lng=parseFloat(self.lng)
        self.map.lat=parseFloat(self.lat)
        self.center = [parseFloat(self.lng), parseFloat(self.lat)];
        self.loaded = true;
        self.markers = [{
          position: self.center,
        }]
        var geocoder = new AMap.Geocoder({
          radius: 1000 //范围,默认:500
        });
        // var marker = new AMap.Marker();
        function regeoCode() {
          var lnglat = [parseFloat(self.lng), parseFloat(self.lat)]
          geocoder.getAddress(lnglat, function(status, result) {
            if (status === 'complete' && result.regeocode) {
              self.address = result.regeocode.formattedAddress;
              self.map.address=self.address
            } else {
              self.address=undefined
              self.lng=undefined
              self.lat=undefined
              self.$message({
                type: "error",
                message: "根据经纬度查询地址失败",
              });
            }
          });
        }
        regeoCode();
        self.$emit('mapDing', self.map);
      }
    }
  }
</script>

3.css部分

<style lang="scss" scoped>
.map-container{
  height: 526px;
  width: 100%;
  padding: 20px;
  display: flex;
  justify-content: center;
  .amap-page-container {
    height: 400px;
    width: 100%;
    position: relative;
    .input-search {
      position: absolute;
      top: 10px;
      right: 0px;
      z-index: 5;
      width: 400px;
      ::v-deep .el-input__inner{
        width: 271px !important;
        padding: 0 10px;
      }
      .inpu {
        width: calc(100% - 10px);
      }
      ::v-deep .el-input__suffix{
        position: absolute;
        height: 100%;
        right: 0 !important;
        top: 0;
      }
      .el-button--medium{
        height: 32px;
        width: 120px;
        background: #f2f6fc;
        display: flex;
        padding: 0;
        align-items: center;
        justify-content: center;
      }
    }
  }
  .map-address{
    margin-top: 15px;
    margin-bottom: 15px;
  }
  .map-mark{
    display: flex;
    flex-direction: row;
    .mark-item{
      width: 248px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-right: 20px;
      span{
        white-space: nowrap;
        margin-right: 20px;
      }
      ::v-deep .el-input__inner{
        width: 200px !important;
      }
      ::v-deep .el-input-number__decrease{
        display: none;
      }
      ::v-deep .el-input-number__increase{
        display: none;
      }
    }
    .mark{
      width: 80px;
      height: 32px;
      background: #087CF2;
      color: #ffffff;
      border: 1px solid #087cf2;
      padding: 0;
    }
  }
}
</style>                

到此这篇关于vue项目中使用高德地图实现添加点标记和获取点击位置信息的文章就介绍到这了,更多相关vue高德地图获取点击位置信息内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文