图片示例

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

准备工作

高德开放平台: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>                
Logo

前往低代码交流专区

更多推荐