由於suggestion返回的是地址資料,並沒有point經緯度的資訊。我們需要自己在回撥函式,或者其他地方通過地址解析來打點。
// 百度地圖API功能
var map = new BMap.Map("allmap");
map.enableScrollWheelZoom(true);
var point = new BMap.Point(116.331398,39.897445);
var marker = new BMap.Marker(point);
map.addOverlay(marker);
map.centerAndZoom(point, 15);
// 新增帶有定位的導航控制元件
var navigationControl = new BMap.NavigationControl({
// 靠左上角位置
anchor: BMAP_ANCHOR_TOP_LEFT,
// LARGE型別
type: BMAP_NAVIGATION_CONTROL_LARGE,
// 啟用顯示定位
enableGeolocation: true
});
map.addControl(navigationControl);
// 新增定位控制元件
var geolocationControl = new BMap.GeolocationControl();
geolocationControl.addEventListener("locationSuccess", function(e){
// 定位成功事件
point = map.getCenter();
geoCoder();
});
geolocationControl.addEventListener("locationError",function(e){
// 定位失敗事件
alert(e.message);
});
map.addControl(geolocationControl);
//建立一個自動完成的物件
var ac = new BMap.Autocomplete({"input" : "mapSearch","location" : map});
//todo .....
function setPlace() {
function myFun() {
point = local.getResults().getPoi(0).point; //獲取第一個智慧搜尋的結果
$('#mapSearch').attr('data-x', point.lng);
$('#mapSearch').attr('data-y', point.lat);
map.centerAndZoom(point, 15);
geoCoder();
}
var local = new BMap.LocalSearch(map, { //智慧搜尋
onSearchComplete: myFun
});
local.search(myValue);
}
function makeList(pois, key) {
$searchAddressList.empty();
for (var i = 0; i < pois.length; i++) {
var poi = pois[i];
var name = poi.name;
var addr = poi.addr;
if (!key || (key && key.length > 0 && poi.name.indexOf(key) > -1)) {
$searchAddressList.append('<li data-x="' + poi.point.x + '" data-y="' + poi.point.y + '"><p class="place-name">' + poi.name + '</p><p class="details">' + addr + '</p></li>');
}
}
if ($searchAddressList.children().length == 2) {
$searchAddressList.children().last().remove();
}
var $lis = $searchAddressList.children();
if ($lis.length == 2) {
var name1 = $lis.eq(0).find('.place-name');
var name2 = $lis.eq(1).find('.place-name');
if (name1 == name2) {
$searchAddressList.children().last().remove();
}
}
}
function geoCoder() {
marker.setPosition(point);
var send = {
ak: "{:C('BAIDU_MAP_AK')}",
location: point.lat + ',' + point.lng,
output: 'json',
pois: 1
};
$.ajax({
url: 'http://api.map.baidu.com/geocoder/v2/',
dataType: 'jsonp',
data: send,
success: function (data) {
if (data.status == 0 && data.result) {
var pois = data.result.pois;
addressList = pois;
makeList(pois);
}
}
})
}