1.html 首页要有注册的高德地图KEY    申请注册的方式百度一下就OK啦  我这个vue 是针对3.0以后的cli3 以后的  默认进入 是自动定位获取当前位置 和 经纬度的。

1.  <script type="text/javascript" src="http://webapi.amap.com/maps?v=1.4.15&key=你的key&plugin=AMap.Geocoder"></script>

效果图是下面的,写这个功能花了一天半的时间  有引入过别人的代码 然后自己再优化了一部分。 

2.下载安装amp  main.js配置     还要vue.config.js 的配置

npm install -S vue-amap

// 下面是main.js配置  

import AMap from 'vue-amap'
Vue.use(AMap)
AMap.initAMapApiLoader({
    key: 你的key,
    plugin: ['AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PlaceSearch', 'AMap.Geolocation', 'AMap.Geocoder'],
    v: '1.4.4',
})
// 这是vue.config.js 配置 将AMap作为全局变量

module.exports = {

    publicPath: "./",
    chainWebpack: (config) => {
        config.resolve.alias
            .set('@', resolve('src'))
            .set('@components', resolve('src/components'))
            .set('@img', resolve('src/assets/imgs'))
    },
    configureWebpack: {
        externals: {
            'AMap': 'AMap'
        }
    }
}

 3.然后写子组件 父组件调用     这是一个完整子组件  可以直接调用 

<template>
  <div class="map-box" :style="{ width: width, height: height }">
    <div id="amap" class="amap"></div>
    <div class="detail">
      <p>经度:{{point ? point[0] : '-'}}</p>
      <p>纬度:{{point ? point[1] : '-'}}</p>
      <p>地址:{{address}}</p>
      <button size="mini" class="btnmap" @click="commit">确定</button>
    </div>
  </div>
</template>

<script>
import AMap from "AMap";
export default {
  props: {
    width: { type: String, default: "100%" },
    height: { type: String, default: "400px" }
  },
  data() {
    return { address: "", point: this.lnglat, marker: "" };
  },
  mounted() {
    this.init(this.point);
  },
  methods: {
    // 初始化
    init() {
      // 地图实例对象 (amap 为容器的id)
      let amap = new AMap.Map("amap", {
        resizeEnable: true,
        zoom: 15
      });

      // 注入插件(定位插件,地理编码插件)
      amap.plugin(["AMap.Geolocation", "AMap.Geocoder"]);
      // 定位

      this.currentPosition(amap);
      let that = this;
      amap.on("click", function(e) {
        //地图被点击的时候
        amap.remove(that.marker);
        let lnglat = [e.lnglat.lng, e.lnglat.lat];
        amap.setCenter(lnglat);
        that.addMark(amap, lnglat);
        that.point = [e.lnglat.lng, e.lnglat.lat];
        that.getAddress([e.lnglat.lng, e.lnglat.lat]);
      });
    },

    // 定位
    currentPosition(map) {
      // 获取地图的位置
      // 没有传入坐标点,则定位到当前所在位置
      let geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,
        timeout: 10000,
        zoomToAccuracy: true,
        buttonPosition: "RB"
      });
      geolocation.getCurrentPosition((status, result) => {
        if (status === "complete") {
          let points = [result.position.lng, result.position.lat];
          map.setCenter(points); // 设置中心点
          this.addMark(map, points); // 添加标记
          // 存下坐标与地址
          this.point = points; // 复制给展示html页面
          this.getAddress(points); // 传入坐标  获取地址
        } else {
          console.log("定位失败", result);
        }
      });
    },

    // 添加标记  就是感叹号标记
    addMark(map, points) {
      this.marker = new AMap.Marker({
        map: map,
        position: points,
        draggable: true, // 允许拖动
        cursor: "move",
        raiseOnDrag: true,
        title: "中心"
      });
      this.marker.on("dragend", e => {
        console.log(e);
        let position = this.marker.getPosition();
        // 存下坐标与地址
        this.point = [position.lng, position.lat];
        this.getAddress([position.lng, position.lat]);
      });
    },

    // 根据坐标返回地址(逆地理编码)
    getAddress(points) {
      let geocoder = new AMap.Geocoder({ radius: 1000 });
      geocoder.getAddress(points, (status, result) => {
        if (status === "complete" && result.regeocode) {
          let s_addr =
            result.regeocode.addressComponent.province +
            "-" +
            result.regeocode.addressComponent.city +
            "-" +
            result.regeocode.addressComponent.district;
          let addreesd = result.regeocode.formattedAddress; // 全部地址名称
          let houzhi = addreesd.substring(s_addr.length); // 获取具体街道
          console.log(s_addr);
          console.log(houzhi);
          console.log(addreesd);
          this.address = s_addr + "," + houzhi;
        }
      });
    },

    commit() {
      this.$emit("location", this.point, this.address);
    }
  }
};
</script>

<style lang="scss" >
.map-box {
  box-sizing: border-box;
  background-color: #ddd;
  padding-top: 10px;
  &:after {
    content: "";
    display: block;
    clear: both;
  }
  .amap,
  .detail {
    float: left;
    height: 100%;
  }
  .amap {
    width: 100%;
  }

  .detail {
    width: 100%;
    background-color: #fff;
    padding: 0 15px;
    border-left: 1px solid #eee;
    box-sizing: border-box;
    word-wrap: break-word;
    height: 20%;
    top: 0px;
    position: absolute;
    p {
      margin-top: 10px;
    }
  }
  .btnmap {
    width: 100%;
    padding: 5px 0;
    color: #fff;
    cursor: pointer;
    background-color: #409eff;
    border: none;
    border-radius: 3px;
    margin-top: 5px;
    &:hover {
      background-color: #66b1ff;
    }
  }
}
</style>

4.写父组件调用的代码  引入子组件  子组件在父组件里面显示。

 // 这个是地图显示  isditu 控制是否展示地图 
 <div class="box" v-show="isditu">
      <xmap width="100%" height="100%" @location="location"></xmap>
    </div>


// 这个是点击事件 触发 控制地图显示 
       <div class="dandee">
          <div class="danone">所在区域</div>
          <div class="dantwo">
            <el-input v-model="s_addr" placeholder="请选择所在区域" @click="xuanzeditu"></el-input>
          </div>
          <img src="../../assets/imgs/xingxing.png" class="xingxing" />
          <img src="../../assets/imgs/jinru.png" @click="xuanzeditu" class="jinrud" />
        </div>


   <div class="dandee">
          <div class="danone">详细地址</div>
          <div class="dantwo">
            <el-input v-model="s_house_number" @change="changedd" placeholder="请输入街道门牌号"></el-input>
          </div>
          <img src="../../assets/imgs/xingxing.png" class="xingxing" />
        </div>
      </div>


//js 写法

import xmap from "./ceshimap";   //引入子组件
import axios from "axios";    // vue axios安装我就不说了

export default {
  components: {
    xmap
  },

  data() {
    return {
      isditu: false,
      provinceValue: "",
      cityValue: "",
      regionValue: "",
      s_addr:"",
      s_house_number: "",
      s_latitude :"",
      s_longitude :"",
    };
  },
 
 methods: {
    // 这个是点击子组件里面的确定
     location(point, address) {
      this.isditu = false;
      this.s_latitude = point[1];       
      this.s_longitude = point[0];
      let s_addrs = address.split(",")[0];
      this.provinceValue = s_addrs.split("-")[0];  //省会
      this.cityValue = s_addrs.split("-")[1];   // 城市
      this.regionValue = s_addrs.split("-")[2]; // 区域
      this.s_addr = this.provinceValue + this.cityValue + this.regionValue; //省市区 拼接
      console.log(address.split(",")[1]);
      this.s_house_number = address.split(",")[1];   // 门牌号
    },
  // 这个是点击父组件选择区域 显示地图
    xuanzeditu() {
      this.isditu = true;
    },

   // 注意如果 客户修改具体的门牌号 那么我们需要重新获取经纬度   
      changedd() {
      axios
        .get("https://restapi.amap.com/v3/geocode/geo", {   //这个但是调用官方的方法  将地址解析成经纬度
          params: {
            key: 你的key,
            address:
              this.provinceValue +
              this.cityValue +
              this.regionValue +
              this.s_house_number
          }
        })
        .then(response => {
          console.log(response.data.geocodes[0].location.split(","));
          let shuzu = response.data.geocodes[0].location.split(",");
          this.s_latitude = shuzu[1];
          this.s_longitude = shuzu[0];
        })
        .catch(function(error) {
          // 请求失败处理
          console.log(error);
        });
    },


}

}

 

Logo

前往低代码交流专区

更多推荐