藉助百度地圖的 LocalSearch 和 Autocomplete 兩個方法 實現方式:通過promise以及百度地圖的callback回調函數 map.js 1 export function MP(ak) { 2 return new Promise(function (resolve, re ...
藉助百度地圖的 LocalSearch 和 Autocomplete 兩個方法
實現方式:通過promise以及百度地圖的callback回調函數
map.js
1 export function MP(ak) { 2 return new Promise(function (resolve, reject) { 3 window.init = function () { 4 resolve(BMap) 5 } 6 var script = document.createElement("script"); 7 script.type = "text/javascript"; 8 script.src = "http://api.map.baidu.com/api?v=2.0&ak="+ak+"&callback=init"; 9 script.onerror = reject; 10 document.head.appendChild(script); 11 }) 12 }
使用
1 <template> 2 <input type="text" id="suggestId" name="address_detail" placeholder="如門牌號等" v-model="address_detail" class="input_style"> 3 <div id="allmap"></div> 4 </template> 5 <script> 6 import {MP} from '../../map' 7 8 data(){ 9 return{ 10 address_detail: null, //詳細地址 11 userlocation:{lng:"",lat:""}, 12 } 13 }, 14 mounted(){ 15 this.$nextTick(function () { 16 MP("你的ak").then( BMap => { 17 var th = this 18 var map = new BMap.Map("allmap"); // 創建Map實例 19 var point = new BMap.Point(116.404, 39.915); // 創建點坐標 20 map.centerAndZoom(point,15); 21 map.enableScrollWheelZoom(); 22 var ac = new BMap.Autocomplete( //建立一個自動完成的對象 23 {"input" : "suggestId" 24 ,"location" : map 25 }) 26 var myValue 27 ac.addEventListener("onconfirm", function(e) { //滑鼠點擊下拉列表後的事件 28 var _value = e.item.value; 29 myValue = _value.province + _value.city + _value.district + _value.street + _value.business; 30 this.address_detail = myValue 31 setPlace(); 32 }); 33 34 function setPlace(){ 35 map.clearOverlays(); //清除地圖上所有覆蓋物 36 function myFun(){ 37 th.userlocation = local.getResults().getPoi(0).point; //獲取第一個智能搜索的結果 38 map.centerAndZoom(th.userlocation, 18); 39 map.addOverlay(new BMap.Marker(th.userlocation)); //添加標註 40 } 41 var local = new BMap.LocalSearch(map, { //智能搜索 42 onSearchComplete: myFun 43 }); 44 local.search(myValue); 45 } 46 }) 47 }) 48 }, 49 </script>