來自:https://www.2cto.com/kf/201701/587448.html 侵刪
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
body, html{width: 100%;height: 100%;margin:0;font-family:"微軟雅黑";font-size:14px;}
#l-map{height:300px;width:100%;}
#r-result{width:100%;}
</style>
<!-- <script type="text/javascript" src="https://api.map.baidu.com/api?v=1.4"></script> -->
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=密匙"></script>
<title>關鍵字輸入提示詞條</title>
</head>
<body>
<p id="l-map">
</p>
</body>
</html>
<script type="text/javascript">
// 百度地圖API功能
function G(id) {
return document.getElementById(id);
}
var map = new BMap.Map("l-map");
map.centerAndZoom(new BMap.Point(120.714537, 30.122469), 9); // 初始化地圖,設置城市和地圖級別。
// 定義一個控件類,即function
function ZoomControl() {
this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
this.defaultOffset = new BMap.Size(10, 10);
}
// 經過JavaScript的prototype屬性繼承於BMap.Control
ZoomControl.prototype = new BMap.Control();
// 自定義控件必須實現本身的initialize方法,而且將控件的DOM元素返回
// 在本方法中建立個p元素做爲控件的容器,並將其添加到地圖容器中
ZoomControl.prototype.initialize = function(map){
// 建立一個DOM元素
var p = document.createElement("p");
p.innerHTML = '<p id="r-result">搜索地址:<input type="text" id="suggestId" size="20" value="百度" style="width:150px;" /></p><p id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></p>';
// 添加DOM元素到地圖中
map.getContainer().appendChild(p);
// 將DOM元素返回
return p;
}
// 建立控件
var myZoomCtrl = new ZoomControl();
// 添加到地圖當中
map.addControl(myZoomCtrl);
var ac = new BMap.Autocomplete( //創建一個自動完成的對象
{"input" : "suggestId"
,"location" : map
});
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, 14);
console.log('pp',pp)
map.addOverlay(new BMap.Marker(pp)); //添加標註
}
var local = new BMap.LocalSearch(map, { //智能搜索
onSearchComplete: myFun
});
local.search(myValue);
}
</script>