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

首先須要去百度地圖開發者平臺申請 akjavascript

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

在index.html 中引入scripthtml

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

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

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

在咱們須要使用的vue文件引入java

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>
相關文章
相關標籤/搜索