vue 中結合百度地圖獲取當前城市


首先需要去百度地圖開發者平台申請 ak

http://lbsyun.baidu.com/index.php?title=%E9%A6%96%E9%A1%B5

在index.html 中引入script

<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=申請的ak"></script>

在 webpack.base.conf.js 中寫入一下代碼

module.exports = {
  // ...
  externals:{
    'BMap': 'BMap'
  },
  // ...
}

在我們需要使用的vue文件引入

import BMap from 'BMap';
export default {
    name: 'place',
    data() {
        return {
            LocationCity: '正在定位',
            success: false
        };
    },
    
    methods: {
        getLocation() {
            const geolocation = new BMap.Geolocation();
            var _this = this;
            _this.LocationCity = '正在定位';
            geolocation.getCurrentPosition(function getinfo(position){
                let city = position.address.city;             //獲取城市信息
                let province = position.address.province;    //獲取省份信息
                _this.LocationCity = city;
                _this.success = true;
            }, function(e) {
                _this.LocationCity = '定位失敗, 請點擊重試';
                this.success = false;
            }, {provider: 'baidu'});
        }
    },
    mounted() {
        this.getLocation();
    },
};
</script>

 


免責聲明!

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



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