<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>CanvasLayer</title>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=3.0&ak=Zdr818v0IP2c4CRrdIqsRNi4""></script>
<style type="text/css">
body, html,#container {width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微软雅黑";}
</style>
</head>
<body>
    <div id="container"></div>
</body>
</html>
<script type="text/javascript">
    var map = new BMap.Map("container");
    map.centerAndZoom(new BMap.Point(116.404, 39.915), 8);
    map.enableScrollWheelZoom();
            
    //100000个点单独绘制没有问题
    //基于Canvas的点击判断会引发大量计算
	var MAX = 10000;
	var data = [];
	for (i=0; i < MAX; i++) {
	   data.push(new BMap.Point(Math.random() * 50 + 85, Math.random() * 30 + 21));
    }

    var canvasLayer = new BMap.CanvasLayer({
        update: update
    });

    function update() {
        var ctx = this.canvas.getContext("2d");

        if (!ctx) {
            return;
        }

        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        ctx.fillStyle = "rgba(50, 50, 255, 0.7)";

        //绘制图片
        var img = new Image();
        img.onload = function(){
            for (var i = 0, len = data.length; i < len; i++) {
                var pixel = map.pointToPixel(data[i]);
                ctx.drawImage(img, pixel.x, pixel.y, 16, 39.12); 
                ctx.add
            }   
        };
        img.src = "https://www.easyicon.net/api/resizeApi.php?id=1223782&size=32";

        //绑定单击事件
        var self = this;
        self.canvas.onclick = function(e){
            var x= e.layerX;
            var y= e.layerY;
            console.log(x,y);
            //var x = e.pageX - self.canvas.getBoundingClientRect().left;
            //var y = e.pageY - self.canvas.getBoundingClientRect().top;
            for(var i = 0; i < data.length; i++){
                var pixel = map.pointToPixel(data[i]);
                ctx.rect(pixel.x, pixel.y, 16, 39.12);
                if(ctx.isPointInPath(x,y)){
                    alert('当前点击的点是:(' + data[i].lng + "," + data[i].lat + ")");
                    break;
                }
            }
        };
        
    }
    map.addOverlay(canvasLayer);
</script>

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.