需求:先使用關鍵字輸入提示選擇地址,地址不准確的情況下可以拖動定位點移動坐標
問題:拖拽后,拖拽后的地址賦值給了文本框,會不停觸發頁面下拉
解決方式:文檔有hide方法
具體代碼如下:
initMap(){ var that = this; var isHide = true; // 百度地圖API功能 function G(id) { return document.getElementById(id); } var map = new BMap.Map("l-map"); map.centerAndZoom("北京",12); // 初始化地圖,設置城市和地圖級別。 var ac = new BMap.Autocomplete( //建立一個自動完成的對象 {"input" : "suggestId" ,"location" : map, "onSearchComplete": function (data) { if(!isHide){ ac.hide() isHide = true; } } }); ac.addEventListener("onhighlight", function(e) { //鼠標放在下拉列表上的事件 var str = ""; var _value = e.fromitem.value; var value = ""; if (e.fromitem.index > -1) { value = _value.province + _value.city + _value.district + _value.street + _value.business; } str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value; value = ""; if (e.toitem.index > -1) { _value = e.toitem.value; value = _value.province + _value.city + _value.district + _value.street + _value.business; } str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value; G("searchResultPanel").innerHTML = str; }); var myValue; ac.addEventListener("onconfirm", function(e) { //鼠標點擊下拉列表后的事件 var _value = e.item.value; myValue = _value.province + _value.city + _value.district + _value.street + _value.business; G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue; setPlace(); }); function setPlace(){ map.clearOverlays(); //清除地圖上所有覆蓋物 function myFun(){ var pp = local.getResults().getPoi(0).point; //獲取第一個智能搜索的結果 map.centerAndZoom(pp, 18); map.addOverlay(new BMap.Marker(pp)); //添加標注 //添加代碼 var marker = new BMap.Marker(pp); map.addOverlay(marker); //添加標注 var geoc = new BMap.Geocoder(); marker.enableDragging(); // console.log(marker); marker.addEventListener("dragend", function(e) { // that.lon = e.point.lng; // that.lat = e.point.lat; var myGeo = new BMap.Geocoder(); // 根據坐標得到地址描述 myGeo.getLocation( new BMap.Point(e.point.lng, e.point.lat), function(result) { if (result) { $("#suggestId").val(result.address) // $("#suggestId").blur(); isHide = false; } } ); }); //添加代碼結束 } var local = new BMap.LocalSearch(map, { //智能搜索 onSearchComplete: myFun }); local.search(myValue); } }