代码目录结构(图片按对应命名保存)
1.png
pin.png
效果
代码
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>百度地图 API marker</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.3, user-scalable=no">
<meta name="description" content="百度地图 API marker">
<meta name="keywords" content="百度 API">
<meta name="author" content="wg">
<style>
html,body,#map{
height: 100%;
width: 100%;
margin: 0;
}
</style>
<script src="http://api.map.baidu.com/api?v=1.4"></script>
<script src="http://api.map.baidu.com/library/LuShu/1.2/src/LuShu_min.js"></script>
<body>
<div id="map"></div>
<script>
var map = new BMap.Map("map");//创建Map实例
map.enableScrollWheelZoom(true);//开启鼠标滚轮缩放
map.centerAndZoom(new BMap.Point(108.99059, 34.27563), 15);//声明地图中心点和缩放级别
var data = [//假设这个数据是从后台获取的json数据
{latitude: 34.27563, longitude: 108.99059,stationType: 01,message:'123',address:'康复路'},
{latitude: 34.276365, longitude: 108.980291,stationType: 00,message:'234',address:'朝阳门'},
{latitude: 34.276361, longitude: 108.969296,stationType: 00,message:'345',address:'五路口'},
{latitude: 34.276164, longitude: 108.953575,stationType: 00,message:'456',address:'北大街'},
{latitude: 34.287457, longitude: 108.953593,stationType: 00,message:'567',address:'安远门'}
];
for(var i=0;i<data.length;i++){//遍历数据
if (data[i].stationType==01){
addIcon(data[i].longitude,data[i].latitude,'1.png',data[i].message,data[i].address);
}else if(data[i].stationType==00){
addIcon(data[i].longitude,data[i].latitude,'pin.png',data[i].message,data[i].address);
}
}
//参数坐标、图片(这里写的相对路径,图片和html在相同路径,只写图片名)、需要的信息
function addIcon(lat,lng,img,msg,address){
//创建Point实例
var point = new BMap.Point(lat,lng);
//创建Icon实例
var icon = new BMap.Icon(img, new BMap.Size(50, 32), {
anchor: new BMap.Size(10, 30)
});
//创建Marker实例,并添加Point和Icon
var mkr =new BMap.Marker(point, {
icon: icon
});
var opts = {
width : 200, // 信息窗口宽度
height: 100, // 信息窗口高度
title : '<h4>地址:</h4>' , // 信息窗口标题
enableMessage:false,//设置允许信息窗发送短息
message: msg
}
//创建信息窗口实例
var infoWindow = new BMap.InfoWindow(address,opts);
mkr.addEventListener("click", function(){
map.openInfoWindow(infoWindow,point); //开启信息窗口
});
map.addOverlay(mkr);//添加Marker到地图上
}
</script>
</body>
</html>