通過Place suggestion API 獲取輸入的文本。
通過Geocoding API獲取用戶點擊的坐標轉換成地址
Js部分
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=你的AK"></script>
<script type="text/javascript">
//點Icon 創建一自定義的icon 裡邊的圖片可以自己換
var myIcon = new BMap.Icon("../Images/icon-map.png", new BMap.Size(32, 32));
// 百度地圖API功能
function G(id) {
return document.getElementById(id);
}
var map = new BMap.Map("l-map");
var oldoverlay = null;
map.centerAndZoom(new BMap.Point(120.750092, 31.255842), 15);// 初始化地圖,設置城市和地圖級別。
function showInfo(e) {
alert(point);
//獲取地圖上的坐標
var point = new BMap.Point(e.point.lng, e.point.lat);
var marker = new BMap.Marker(point, { icon: myIcon }); // 創建標注
map.addOverlay(marker); // 將標注添加到地圖中
map.centerAndZoom(point, 15);
if (oldoverlay != null) {
map.removeOverlay(oldoverlay);
}
oldoverlay = marker;
var lng = e.point.lng;
var lat = e.point.lat;
var url = "你的AK&callback=mapCallBack&location=" + lat + "," + lng +
"&output=json&pois=0";
$.ajax({
url: url,
type: 'GET',
dataType: 'jsonp',//here
async: false,
crossDomain: true,
success: function (data) {
console.log(data);
//訪問百度的逆序列接口
$("#suggestId").val(data.result.sematic_description);
}
});
}
map.addEventListener("click", showInfo);
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, 18);
map.addOverlay(new BMap.Marker(pp)); //添加標注
}
var local = new BMap.LocalSearch(map, { //智能搜索
onSearchComplete: myFun
});
local.search(myValue);
}
</script>
html部分
<div id="l-map"></div>
<input type="text" class="input-info" id="suggestId" placeholder="" />
<div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto;display: none;">
</div>