1.你需要安装npm,然后安装插件npm install angular2-baidu-map --save
2.你需要在项目中注册插件。
一般情况下,实在app.module.ts中引入。
import { BaiduMapModule } from ‘angular2-baidu-map’;
@NgModule({
imports: [
BaiduMapModule.forRoot({ ak: ‘yourAK’ }),
]
})
在html中引入
<baidu-map [options]="opts" (loaded)="search($event)">
<control type="navigation" [options]="navOptions"></control>
</baidu-map>
4.在component层
import {ControlAnchor,MapOptions,NavigationControlOptions,NavigationControlType,} from 'angular2-baidu-map';
declare var BMap: any;
public opts: MapOptions;
public markers: any[] = [];
local: any;
navOptions: NavigationControlOptions;
constructor() {
this.opts = { //设置地图初始化中心点及其他设置
currentCity: '青岛',
minZoom: 1,
maxZoom: 18,
enableScrollWheelZoom: true,
centerAndZoom: {
lat: 36,
lng: 120,
zoom: 16
},
enableKeyboard: true
};
this.navOptions = {
anchor: ControlAnchor.BMAP_ANCHOR_TOP_RIGHT,
type: NavigationControlType.BMAP_NAVIGATION_CONTROL_PAN
};
}
search(e: any) { // 对应baidu-map中loaded事件即地图加载时运行的方法 官方介绍e可以是map实例
let _this = this;
//创建一个搜索类实例
this.local = new BMap.LocalSearch(e, {
renderOptions: {map: e, autoViewport: true, selectFirstResult: false},
pageCapacity: 10
});
// 设置查询完成时的回调函数
this.local.setSearchCompleteCallback(async (searchResults) => {
let markeSize = this.markers.length; //每次搜索都会在地图上留下标记,这是去除以前留下的标记
for (let i = 0; i < markeSize; i++) {
e.removeOverlay(this.markers[i]);
}
this.markers = [];
if (typeof(searchResults) == "undefined") { // 检验搜索结果
alert("百度API没有搜索到该地址");
return;
}
let searchResult = [];
searchResult = searchResults.Lq; // 查询结果存在searchResults.Lq中
let size = searchResult.length;
let temp;
let myIcon = new BMap.Icon("http://api.map.baidu.com/img/markers.png", new BMap.Size(23, 25), { // 设置地图标记的icon
offset: new BMap.Size(10, 25),
imageOffset: new BMap.Size(0, 0 - 10 * 25)
});
let contents = [];
for (let i = 0; i < size; i++) {
_this.markers[i] = new BMap.Marker(new BMap.Point(searchResult[i].point.lng, searchResult[i].point.lat), {icon: myIcon});//在地图上添加标识
//点击标识后显示的内容
contents[i] = "你要查找的地方:【" + searchResult[i].title + "】地址:" + searchResult[i].address;// 经纬度在searchResult[i].point.lng, searchResult[i].point.lat中
_this.markers[i].title = contents[i];
//添加点击事件监听
_this.markers[i].addEventListener("click", () => {
var infoWindow = new BMap.InfoWindow("<p style='font-size:14px;'>" + contents[i] + "</p>");
_this.markers[i].openInfoWindow(infoWindow);
});// 在点击标识的时候显示标识点信息
e.addOverlay(_this.markers[i]);// 添加标识
if (i == 0) { // 默认显示查询结果第一条
var infoWindow = new BMap.InfoWindow("<p style='font-size:14px;'>" + contents[0] + "</p>");
_this.markers[0].openInfoWindow(infoWindow);
}
}
}
);
}
// 地址搜索
getAddress() {
this.local.search(“青岛五四广场”); // 你需要搜索的地方
}
参考文档
1. https://leftstick.github.io/angular2-baidu-map/#/apidoc/baidu-map
2. http://lbsyun.baidu.com/cms/jsapi/reference/jsapi_reference.html#a0b0