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>