百度地图调用加载显示Marker,并添加点击事件
-
注册百度开发者账号,申请应用AK
百度地图开发平台官网 -
点击右上角控制台,选择创建应用
-
创建应用,勾选浏览器端,白名单填写*
注:如上线更改为公网IP,如浏览器端显示调用选择浏览器端,如服务端调用数据接口开发则选择服务端,按需创建即可。此处为浏览器端加载显示地图,故选择浏览器端 -
点击确认,获取AK
返回控制台-我的应用即可查看应用AK -
网页端标签引入
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=申请的ak"></script>
- 页面声明
声明div容器加载显示地图,注div要有宽高,id为加载绑定地图的要素
<div class="map-box" id="map" ></div>
- 调用api加载显示地图
var map; //Map实例
//地图中心坐标
var mapCenterX = 126.534943;
var mapCenterY = 45.808585;
//加载显示marker数组
var markerArr;
function map_init() {
//传入绑定的地图容器id
map = new BMap.Map("map");
//初始化地图,设置中心点坐标和地图级别。
map.centerAndZoom(new BMap.Point(mapCenterX, mapCenterY),12);
//启用滚轮放大缩小
map.enableScrollWheelZoom(true);
//向地图中添加缩放控件
var ctrlNav = new window.BMap.NavigationControl({
anchor: BMAP_ANCHOR_TOP_LEFT,
type: BMAP_NAVIGATION_CONTROL_LARGE
});
//地图缩放控件
map.addControl(ctrlNav);
//向地图中添加缩略图控件
var ctrlOve = new window.BMap.OverviewMapControl({
anchor: BMAP_ANCHOR_BOTTOM_RIGHT,
isOpen: 1
});
map.addControl(ctrlOve);
//添加鹰眼
var overviewControl = new BMap.OverviewMapControl({
anchor: BMAP_ANCHOR_BOTTOM_RIGHT,
isOpen: true
});
map.addControl(overviewControl);
//向地图中添加比例尺控件
var ctrlSca = new window.BMap.ScaleControl({
anchor: BMAP_ANCHOR_BOTTOM_LEFT
});
map.addControl(ctrlSca);
}
$(document).ready(function() {
//页面初始化
/*$.ajax({
type: "POST",
url: "",
data: {
},
dataType: "json",
success: function(data){
markerArr = data.result.markerArr;
initData();
}
});*/
markerArr = [{
markerId: 1,
title: "marker1",
point: "126.526607,45.802051",
state: 0
},
{
markerId: 2,
title: "marker2",
point: "126.559952,45.810997",
state: 0
}
];
initData();
});
- 初始化加载显示marker,可根据状态不同显示不同marker
function initMaker() {
//绘制marker
for(var i = 0; i < markerArr.length; i++) {
idArr.push(markerArr[i].markerId);
var p0 = markerArr[i].point.split(",")[0];
var p1 = markerArr[i].point.split(",")[1];
var state = markerArr[i].state;
var maker = addMarker(new window.BMap.Point(p0, p1), i, markerArr[i].title, idArr, state);
}
}
// 添加marker
function addMarker(point, index, title, idArr, state) {
var myIcon;
//状态1
if(state == 0) {
myIcon = new BMap.Icon("本地自定义图标路径", new BMap.Size(30, 30));
}
//状态2
if(state == 1) {
myIcon = new BMap.Icon("本地自定义图标路径", new BMap.Size(30, 30));
}
var marker = new BMap.Marker(point, {
icon: myIcon
});
var label = new window.BMap.Label(title, {
offset: new window.BMap.Size(20, -10)
});
label.setStyle({
backgroundColor: "#fff",
maxWidth: "none",
color: "#000",
fontSize: "12px",
height: "20px",
lineHeight: "20px",
fontFamily: "微软雅黑"
});
marker.setLabel(label);
//marker点击触发事件
marker.addEventListener("click", function() {
//此处添加marker点击事件
});
map.addOverlay(marker);
//跳动的动画
marker.setAnimation(BMAP_ANIMATION_BOUNCE);
return marker;
}
来源:CSDN
作者:sophieLV1993
链接:https://blog.csdn.net/sophieLV1993/article/details/103476224