前端学习笔记-百度地图自定义标注

本文记录了在前端开发中如何使用百度地图API创建自定义标注的过程,包括添加样式、设置ak、定义覆盖物、初始化地图、实现绘制和显示方法,最终在地图上成功展示了一个红色方块。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.添加样式,引入ak等

<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
	<title></title>
	<style type="text/css">
		body{margin:0px;padding:0px;}
		html,body,#container{height:100%;width:100%;}
	</style>
	<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=fpy9xZxIMzHzWb0G17Hwcuj2Ifh8Wq7u"></script>

2.定义自定义覆盖物

	var map = new BMap.Map("container");
	var point = new BMap.Point(116.490,39.543);
	map.centerAndZoom(point,15);
// 定义自定义覆盖物的构造函数  
function SquareOverlay(center, length, color){
    this._center = center;
    this._length = length;
    this._color = color;
}
// 继承API的BMap.Overlay
SquareOverlay.prototype = new BMap.Overlay();

3.初始化

SquareOverlay.prototype.initialize = function(map){
    // 保存map对象实例
    this._map = map;
    // 创建div元素,作为自定义覆盖物的容器
    var div = document.createElement("div");
    div.style.position = "absolute";
    // 可以根据参数设置元素外观
    div.style.width = this._length + "px";
    div.style.height = this._length + "px";
    div.style.background = this._color;
    // 将div添加到覆盖物容器中
    map.getPanes().markerPane.appendChild(div);
    // 保存div实例
    this._div = div;
    // 需要将div元素作为方法的返回值,当调用该覆盖物的show、
    // hide方法,或者对覆盖物进行移除时,API都将操作此元素。
    return div;
}

4.实现绘制方法

SquareOverlay.prototype.draw = function(){    
// 根据地理坐标转换为像素坐标,并设置给容器    
    var position = this._map.pointToOverlayPixel(this._center);    
    this._div.style.left = position.x - this._length / 2 + "px";    
    this._div.style.top = position.y - this._length / 2 + "px";    
}

5.实现显示方法

// 实现显示方法    
SquareOverlay.prototype.show = function(){    
    if (this._div){    
        this._div.style.display = "";    
    }    
}      
// 实现隐藏方法  
SquareOverlay.prototype.hide = function(){    
    if (this._div){    
        this._div.style.display = "none";    
    }    
}

6.添加自定义覆盖物

	// 初始化地图  
	var map = new BMap.Map("container");    
	var point = new BMap.Point(116.404, 39.915);    
	map.centerAndZoom(point, 15);    
	// 添加自定义覆盖物   
	var mySquare = new SquareOverlay(map.getCenter(), 100, "red");    
	map.addOverlay(mySquare);

在地图中添加了一个红色的方块

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值