1. 申請百度key
然後百度會讓你輸入你的地址,我是本地訪問麼,我就寫的是127.0.0.1,然後在修改配置檔案中的host,把localHost修改成127.0.0.1 然後在index.html中新增
<script src="http://api.map.baidu.com/api?v=2.0&ak=key"></script>
複製程式碼
可以在webpack的配置檔案中新增
externals:{
"BMap":"BMap"
},
複製程式碼
也可以不新增,這個看你自己使用的方式
2. 獲取瀏覽器的經緯度
這個地方參考了一篇博文,但是忘記在哪裡看到的了,如果作者看到的話評論一下,我加上鍊接
export default class Location {
static getLocation(callback) {
console.log(navigator.geolocation);
if (navigator.geolocation) {
let options = {
enableHighAccuracy: true,
maximumAge: 1000
};
navigator.geolocation.getCurrentPosition(
(res) => {
let location = {};
location.longitude = res.coords.longitude;
location.latitude = res.coords.latitude;
callback.success(location);
},
(res) => {
callback.error(res);
},
options
);
} else {
callback.error("Geo location not supported.");
}
}
}
複製程式碼
這樣瀏覽器進入這個頁面就直接定位到當前位置
<script>
import BMap from 'BMap';
import LocationSDK from "../../common/locationSDK";
export default {
name: "findComponent",
data(){
return{
location:{
latitude:"-1",
longitude:"-1"
}
}
},
mounted() {
let that = this;
this.getLocation((res)=>{that.ready(res)});
},
methods:{
ready(res){
let map = new BMap.Map("allmap");
console.log(res);
let point = new BMap.Point(res.longitude,res.latitude);
console.log(point);
map.centerAndZoom(point,11);
map.setCurrentCity("上海");
map.enableScrollWheelZoom(true)
let local = new BMap.LocalSearch(map,
{ renderOptions:{map: map, autoViewport: true}});
local.searchNearby("電影院","浦東新區");
},
getLocation(callback){
LocationSDK.getLocation({
success:(res)=>{
this.location = res;
callback(this.location)
},
error:(err)=>{
console.log(err)
}
})
}
}
}
</script>
複製程式碼
這個地方注意要在mounted裡面初始化地圖,要不然會報錯