VUE中使用高德地图

608 阅读1分钟

1、安装:npm install --save vue-amap

2、在main.js文件中:

import VueAMap from 'vue-amap'

Vue.use(VueAMap);

VueAMap.initAMapApiLoader({
  key: 'xxx',//申请的高德地图的key
  plugin: ['AMap.Autocomplete','AMap.Geocoder', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.AMapManager','AMap.Geolocation'],
  v: '1.4.4',
  uiVersion: '1.0.11'
});

3、在index.html中加入

<script type="text/javascript">
      window._AMapSecurityConfig = {
          securityJsCode:'xx',//申请的密钥
      }
    </script>

4、 在components文件夹下创建 getLocation文件,文件代码如下

<template>
<el-dialog
  title="获取位置信息"
  :visible.sync="getPositionFlag"
  width="30%"
  :before-close="handleClose">
  <div
    class="amap-page-container"
    style="width: 80%; position: relative; height: 500px; margin: 30px 10%"
  >
    <el-amap-search-box
      class="search-box"
      :search-option="searchOption"
      :on-search-result="onSearchResult"
    ></el-amap-search-box>
    <el-amap
      ref="map"
      vid="amapDemo"
      :amap-manager="amapManager"
      :center="center"
      :zoom="zoom"
      :plugin="plugin"
      :events="events"
      class="amap-demo"
    >
    </el-amap>
    <div style="display:flex;justify-content:space-between;">
    <div>
    <p>{{ address }}</p>
    <p>{{ center }}</p>
    </div>
    <el-button type='success' size='mini' @click="handleClose" style="height:40px;margin-top:20px">确定</el-button>
    </div>
  </div>
 
</el-dialog>
</template>
<script>
import { AMapManager } from "vue-amap";
 
let amapManager = new AMapManager();
export default {
  name:'getPosition',
// 接收父组件传过来的信息
  props:{
    getPositionFlag:{
      type:Boolean,
      default:false
    },
    center:{
      type:Array,
      default: [ 118.76979, 32.066336 ]
    }
  },
    data() {
    const self = this;
    return {
      locationMsg:{},
      searchOption: {
        // city: "北京", //搜索范围
        // citylimit: true, //限制搜索范围
        city: "",
        citylimit: false, // 不限制搜索范围搜索,比如想全国搜索
      },
      lng: "",
      lat: "",
      address: "",
      marker: "",
      amapManager,
      zoom: 12,
      // center: [121.59996, 31.197646],
      events: {
        init: (o) => {
          o.getCity((result) => {
            let par = document.getElementsByClassName("search-box-wrapper")[0];
            par.firstChild.setAttribute(
              "placeholder",
              "您可以在这里输入要搜索的地址"
            );
            //todo 定位到搜索位置
           
            this.searchOption.city = result.city;
          });
        },
        moveend: () => {},
        zoomchange: () => {},
        click: (e) => {
          self.lng = e.lnglat.lng;
          self.lat = e.lnglat.lat;
          self.center = [self.lng, self.lat];
          let o = amapManager.getMap();
          if (!self.marker) {
            self.marker = new AMap.Marker({
              position: e.lnglat,
            });
            self.marker.setMap(o);
          }
          self.marker.setPosition(e.lnglat);
          let geocoder = new AMap.Geocoder({});
          geocoder.getAddress(e.lnglat, function (status, result) {
            if (status === "complete" && result.regeocode) {
              self.address = result.regeocode.formattedAddress;
            } else {
              console.log.error("根据经纬度查询地址失败");
            }
          });
        },
      },
      plugin: [
        "ToolBar",
        {
          pName: "MapType",
          defaultType: 0,
          events: {
            init(o) {
            },
          },
        },
        {
          pName: "Geolocation",
          events: {
            init(o) {
              // o 是高德地图定位插件实例
              o.getCurrentPosition((status, result) => {
                // console.log(JSON.stringify(result));
                if (result && result.position) {
                  self.lng = result.position.lng;
                  self.lat = result.position.lat;
                  self.address = result.formattedAddress;
                  self.center = [self.lng, self.lat];
                  //   console.log(self.center, 99666);
                  let o = amapManager.getMap();
                  if (!self.marker) {
                    self.marker = new AMap.Marker({
                      position: self.center,
                    });
                    self.marker.setMap(o);
                  }
                  self.marker.setPosition(self.center);
                }
              });
            },
          },
        },
      ],
    };
  },
  methods: {
      handleClose() {
        console.log(this.center,this.address)
        this.locationMsg.name=this.address
        this.locationMsg.location={
          lng:this.center[0],
          lat:this.center[1]
        }

        this.$emit('getLocation',this.locationMsg)
        this.$emit('close')
      },
    onSearchResult(pois) {
      if (pois.length > 0) {
        let { lng, lat, name, location,address } = pois[0];
        //?显示
        this.address=address+name
        this.center=location
        this.locationMsg.name=address+name
        this.locationMsg.location=location
        let center = [lng, lat];
        this.lng = lng;
        this.lat = lat;
        this.center = [lng, lat];
        let o = amapManager.getMap();
        if (!this.marker) {
          this.marker = new AMap.Marker({
            position: center,
          });
          this.marker.setMap(o);
        }
        this.marker.setPosition(center);
      }
    },
  },
};
</script>
<style scoped>
::v-deep .el-dialog{
  width: 60% !important;
}
.amap-page-container{
 margin: 0 100px 100px 100px !important; 
}
.search-box {
  position: absolute;
  top: 25px;
  right: 120px;
}
.amap-page-container {
  position: relative;
}
</style>

5、在页面使用组件 getLocation

-- import getLocation from "@/components/getLocation";

-- 组件命名

components: {

getLocation

},

-- data中声明需要的数据

    	address:'',
      longitude:'',
      latitude:'',
      gpsLocation:'',
      getLocationFlag: false,
      center: [118.76979, 32.066336],

--html结构中使用

<el-input v-model="address" placeholder="请输入具体地址" :style="{width: '20%'}">
            <i
              class="el-icon-location"
              @click="getLocationFlag=true"
              style="font-size:20px"
              slot="suffix"
              type="text"
            ></i>
          </el-input>
          <get-location
            :get-position-flag="getLocationFlag"
            :center="center"
            @close="closePosition"
            @getLocation="getLocation"
            
          />

--methods中:

getLocation(data) {
      this.address = data.name;
      this.longitude = data.location.lng;
      this.latitude = data.location.lat;
      this.gpsLocation =
      this.latitude + "/" + this.longitude;
      this.$forceUpdate();
    },
   // 关闭地图方法
    closePosition() {
      this.getLocationFlag = false;
    },

--如果需求是通过选择的省市区来进行地图联动,添加下面代码

/*
    @ function : 根据选择的地址获取经纬度 进行地图的联动显示
    @ param : data 选择的地址  如深圳市宝安区
    */
    changeLocation(data) {
      var _this = this;
      var geocoder = new AMap.Geocoder({
        radius: 1000,
        extensions: "all"
      });
      geocoder.getLocation(data, function(status, result) {
        if (status === "complete" && result.info === "OK") {
          if (result && result.geocodes) {
            _this.center = [
              result.geocodes[0].location.lng,
              result.geocodes[0].location.lat
            ];
          }
        }
      });
    },