vue高德地圖獲取當前位置


前言:官網申請密鑰:https://lbs.amap.com
參考vue-amap

一:安裝依賴

npm install vue-amap --save

二:main.js中的配置

key申請地址教程:https://lbs.amap.com/api/javascript-api/guide/abc/prepare

import VueAMap from 'vue-amap';

Vue.use(VueAMap);
VueAMap.initAMapApiLoader({
  key: 'd6eabbd08f89ccfb74278b36ab6342567', // 自己到官網申請,我隨便寫的
  plugin: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.CircleEditor','AMap.Geolocation','Geocoder'],//plugin所要用到的模塊功能,按需添加
  v: '1.4.4',//高德 sdk 版本為 1.4.4
});

template中使用

<template>
  <div class="page">
    <el-amap vid="amapDemo" :center="center" :zoom="zoom" class="amap-demo" :events="events"></el-amap>
    <div class="toolbar" >position: [{{ lng }}, {{ lat }}] address: {{ address }},個人location:{{location}}</div>
  </div>
</template>

<script>
import location from "../../utils/positionLocation.js";
export default {
  name: "page",
  data() {
    let self = this;
    return {
      title: "標題",
      zoom: 12,
      center: [120.011574, 30.286369],
      address: "",
      events: {
        click(e) {
          let { lng, lat } = e.lnglat;
          self.lng = lng;
          self.lat = lat;
          // 這里通過高德 SDK 完成。
          var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
          });
          geocoder.getAddress([lng, lat], function(status, result) {
            // console.log(status, result);
            if (status === "complete" && result.info === "OK") {
              if (result && result.regeocode) {
                console.log(result);
                self.address = result.regeocode.formattedAddress;
                self.$nextTick();
              }
            }
          });
        }
      },
      lng: 0,
      lat: 0,
      location: ""
    };
  },
  components: {},
  mounted() {
    this.getLocation();
  },
  methods: {
    getLocation() {
      let _that = this;
      let geolocation = location.initMap("map-container"); // 定位
      AMap.event.addListener(geolocation, "complete", result => {
        console.log(result);
        let { lng, lat } = result.position;
        _that.lat = result.position.lat;
        _that.lng = result.position.lng;
        _that.location = result.formattedAddress; 
      });
    }
  }
};
</script>

<style scoped>

</style>

主要獲取定位:

var map, geolocation;
      //加載地圖,調用瀏覽器定位服務   高德地圖
      map = new AMap.Map("container", {
        resizeEnable: true
      });
      map.plugin("AMap.Geolocation", function() {
        geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, //是否使用高精度定位,默認:true
          timeout: 10000, //超過10秒后停止定位,默認:無窮大
          buttonPosition: "RB"
        });
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, "complete", function onComplete(
          data
        ) {
          console.log(data);
          var lng = data.position.getLng();
          var lat = data.position.getLat();
          // alert(getLongitude + "," + getLatitude); //彈出獲得的經緯度
          // that.item.address = getLongitude + "," + getLatitude;
          var address = data.formattedAddress;
          console.log(lng, lat, address);
          var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
          });
          geocoder.getAddress([lng, lat], function(status, result) {
            console.log(status, result);
            if (status === "complete" && result.info === "OK") {
              if (result && result.regeocode) {
                console.log(result);
                let data = result.regeocode.addressComponent;
                that.item.address = data.province + data.city + data.district;
                // self.$nextTick();
                Indicator.close();
              }
            }
          });
        }); //返回定位信息
      });

另一種方式

創建一個名為positionLocation.js的文件,文件內容如下:

/**
 * 高德地圖定位
 * @type {{}}
 */
const location = {
  initMap(id) {
    let mapObj = new AMap.Map(id, {})
    let geolocation;
    mapObj.plugin(['AMap.Geolocation'], function() {
      geolocation = new AMap.Geolocation({
        enableHighAccuracy: true, //  是否使用高精度定位,默認:true
        timeout: 10000, //  超過10秒后停止定位,默認:無窮大
        maximumAge: 0, // 定位結果緩存0毫秒,默認:0
        convert: true, // 自動偏移坐標,偏移后的坐標為高德坐標,默認:true
        showButton: true, //  顯示定位按鈕,默認:true
        buttonPosition: 'LB', // 定位按鈕停靠位置,默認:'LB',左下角
        buttonOffset: new AMap.Pixel(10, 20), //  定位按鈕與設置的停靠位置的偏移量,默認:Pixel(10, 20)
        showMarker: true, //  定位成功后在定位到的位置顯示點標記,默認:true
        showCircle: true, //  定位成功后用圓圈表示定位精度范圍,默認:true
        panToLocation: true, //  定位成功后將定位到的位置作為地圖中心點,默認:true
        zoomToAccuracy: true //  定位成功后調整地圖視野范圍使定位位置及精度范圍視野內可見,默認:false
      })
      mapObj.addControl(geolocation)
      geolocation.getCurrentPosition()
    })
    return geolocation;
  }
}
export default location

在要用到相關定位功能的頁面引入該js文件

import AMap from 'AMap'
import location from '../../javascript/positionLocation.js'
export default {
    data() {
        return {
            // 高德地圖獲取當前位置
            location: '',
            lat: 0,
            lng: 0,
      }
  },
        
    mounted() {
      this.getLocation(); // 調用獲取地理位置
    },
    methods: {  
      /** 獲取高德地圖定位 */
      getLocation() {
        let _that = this
        let geolocation = location.initMap('map-container') // 定位
        AMap.event.addListener(geolocation, 'complete', result => {
          console.log(result)
          _that.lat = result.position.lat
          _that.lng = result.position.lng
          _that.location = result.formattedAddress
        })
      },
}

注意key的時效性,過時了formattedAddress可能會獲取不到


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM