近期新項目使用了vue,由於涉及到物流配送,須要獲取用戶的位置座標,要藉助百度地圖的 LocalSearch 和 Autocomplete 兩個方法
實現方式:經過promise以及百度地圖的callback回調函數javascript
export function MP(ak) { return new Promise(function (resolve, reject) { window.init = function () { resolve(BMap) } var script = document.createElement("script"); script.type = "text/javascript"; script.src = "http://api.map.baidu.com/api?v=2.0&ak="+ak+"&callback=init"; script.onerror = reject; document.head.appendChild(script); }) }
<template> <input type="text" id="suggestId" name="address_detail" placeholder="如門牌號等" v-model="address_detail" class="input_style"> <div id="allmap"></div> </template> <script> import {MP} from '../../map' data(){ return{ address_detail: null, //詳細地址 userlocation:{lng:"",lat:""}, } }, mounted(){ this.$nextTick(function () { MP("你的ak").then( BMap => { var th = this var map = new BMap.Map("allmap"); // 建立Map實例 var point = new BMap.Point(116.404, 39.915); // 建立點座標 map.centerAndZoom(point,15); map.enableScrollWheelZoom(); var ac = new BMap.Autocomplete( //創建一個自動完成的對象 {"input" : "suggestId" ,"location" : map }) var myValue ac.addEventListener("onconfirm", function(e) { //鼠標點擊下拉列表後的事件 var _value = e.item.value; myValue = _value.province + _value.city + _value.district + _value.street + _value.business; this.address_detail = myValue setPlace(); }); function setPlace(){ map.clearOverlays(); //清除地圖上全部覆蓋物 function myFun(){ th.userlocation = local.getResults().getPoi(0).point; //獲取第一個智能搜索的結果 map.centerAndZoom(th.userlocation, 18); map.addOverlay(new BMap.Marker(th.userlocation)); //添加標註 } var local = new BMap.LocalSearch(map, { //智能搜索 onSearchComplete: myFun }); local.search(myValue); } }) }) }, </script>