js 百度地图加载大量点

这段代码展示了如何使用JavaScript和百度地图API在网页上加载并显示大量点。通过创建自定义覆盖物(ComplexCustomOverlay),实现了在地图上绘制5000个随机点,并且对鼠标点击和移动事件进行了响应,提供了交互体验。

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

<html>
<head>
    <title>xApp</title>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=K3yDzvlwWbDlvSQyvwCLd0l5"></script>

    <style type="text/css">
        html,body{height:100%;margin:0 auto;}
        #map,#maps{height:100%;width:100%;}
    </style>
</head>
<body>
    <div id="maps"></div>
    <!--<canvas id="map"></canvas>-->

    <script type="text/javascript" language="javascript">

        var map = new BMap.Map("maps", {});                        // 创建Map实例
        map.centerAndZoom(new BMap.Point(116.404, 39.915), 3);     // 初始化地图,设置中心点坐标和地图级别
        map.enableScrollWheelZoom();                            //启用滚轮放大缩小
        if (document.createElement('canvas').getContext) {
            //var mapStyle = {
            //    features: ["road", "building", "water", "land"],//隐藏地图上的poi
            //    style: "dark"  //设置地图风格为高端黑
            //}
            //map.setMapStyle(mapStyle);


            var canvas;
            // 复杂的自定义覆盖物
            function ComplexCustomOverlay(point) {
                this._point = point;
                this.car = [];
            }
            function Star(x,y,ctx,pt)
            {
                this.bx = this.x = x;
                this.by = this.y = y;
                this.pt = pt;
                this.ctx = ctx;
                this.size = 8;
                if (x == 0 && y == 0) {
                    var b = 3;
                }
                this.render = function(size)
                {
                    var ctx = this.ctx;
                    var p = this;
                    if (p.x == 0 && p.y == 0)
                    {
                        var b = 3;
                    }
                    p.size = size;
                    p.isVisible = false;
                    var x = p.x  , y = p.y ;
                    if (x < 0 || y < 0)
                        return false;
                    if (x > ctx.canvas.width || y > ctx.canvas.height)
                        return false;
                  //  console.log(x, y, ctx.canvas.width, ctx.canvas.height);
                    ctx.beginPath();
                    
                    var gradient = ctx.createRadialGradient(p.x  , p.y , 0, p.x  , p.y  , p.size);
                    gradient.addColorStop(0, "rgba(7,120,249,1)");
                    gradient.addColorStop(1, "rgba(7,120,249,0.3)");
                    ctx.fillStyle = gradient;

                   // ctx.fillRect( p.x  , p.y  , 10, 10);

                    ctx.arc(p.x , p.y , p.size, Math.PI * 2, false);
                    ctx.fill();
                    p.isVisible = true;
                    return true;
                }
            }
            ComplexCustomOverlay.prototype = new BMap.Overlay();
            ComplexCustomOverlay.prototype.initialize = function (map) {
                this._map = map;
                canvas = this.canvas = document.createElement("canvas");
                canvas.style.cssText = "position:absolute;left:0;top:0;";
                ctx = this.ctx = canvas.getContext("2d");
                var size = map.getSize();
                canvas.width = BW = size.width;
                canvas.height = BH = size.height;
                map.getPanes().labelPane.appendChild(canvas);

                this.car.length = 0;

                var bound = map.getBounds();
                var project = map.getMapType().getProjection();
                var sw = bound.getSouthWest();
                var ne = bound.getNorthEast();
                var lat = ne.lat - sw.lat;
                var lng = ne.lng - sw.lng;
                for (var i = 0; i < 5000; i++) {
                    // var pt = project.lngLatToPoint();
                    var p = new BMap.Point(Math.random() * lng + (sw.lng), Math.random() * lat + (sw.lat));
                  //  var py = map.pointToOverlayPixel(p);
                    var py = project.lngLatToPoint(p);
                    this.car.push(new Star(py.x, py.y, ctx,p));
                }

                var p = this;
                canvas.addEventListener('click', function (a, b) {
                    for (var i = 0; i < p.car.length; i++)
                    {
                        var c = p.car[i];
                        var x = a.clientX;
                        var y = a.clientY;
                        var s = c.size ;

                        if (p.isVisible && Math.abs(c.x-x) < s && Math.abs(c.y-y) < s )
                        {
                            alert('ok');
                            return;
                        }

                    }
                    
                });
                canvas.addEventListener('mousemove', function (a, b) {
                    for (var i = 0; i < p.car.length; i++) {
                        var c = p.car[i];
                        var x = a.clientX;
                        var y = a.clientY;
                        var s = c.size;

                        if (p.isVisible && Math.abs(c.x - x) < s && Math.abs(c.y - y) < s) {
                            canvas.style.cursor = 'pointer';
                            return;
                        }
                    }
                    if (canvas.style.cursor != '')
                        canvas.style.cursor = '';
                });
                var resize = function () {
                    var size = map.getSize();
                  //  var canvas = canvas;
                    var pixelRatio;

                   {
                        pixelRatio = (function (context) {
                            var backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;

                            return (window.devicePixelRatio || 1) / backingStore;
                        })(canvas.getContext('2d'));
                    }

                    canvas.width = size.width * pixelRatio;
                    canvas.height = size.height * pixelRatio;
                    canvas.style.width = size.width + "px";
                    canvas.style.height = size.height + "px";
                    p.draw();
                };
                map.addEventListener('resize', function () {
                    resize();
                });
                //map.getContainer().appendChild(canvas);
                return this.canvas;
            }
            ComplexCustomOverlay.prototype.draw = function () {
                var map = this._map;
                var bounds = map.getBounds();
                var sw = bounds.getSouthWest();
                var ne = bounds.getNorthEast();
                var project = map.getMapType().getProjection();
                var pixel2 = project.lngLatToPoint(new BMap.Point(sw.lng, sw.lat));
                var pixel3 = project.lngLatToPoint(new BMap.Point(ne.lng, ne.lat));
              // pixel = map.pointToPixel(new BMap.Point(sw.lng, ne.lat));
                var size = map.getSize();
                var center = map.getCenter();
                if (center) {
                   var pixel = map.pointToOverlayPixel(center);
                    this.canvas.style.left = pixel.x - size.width / 2 + 'px';
                    this.canvas.style.top = pixel.y - size.height / 2 + 'px';

                }
                var py = pixel;
                // 墨卡托坐标计算方法
                var zoom = map.getZoom();
                var zoomUnit = Math.pow(2, 18 - zoom);
                var mcCenter = project.lngLatToPoint(map.getCenter());
                var nwMc = new BMap.Pixel(mcCenter.x - map.getSize().width / 2 * zoomUnit, mcCenter.y + map.getSize().height / 2 * zoomUnit); //左上角墨卡托坐标
                pixel2.x = (pixel2.x - nwMc.x) / zoomUnit;
                pixel2.y = (nwMc.y - pixel2.y) / zoomUnit;

                pixel3.x = (pixel3.x - nwMc.x) / zoomUnit;
                pixel3.y = (nwMc.y - pixel3.y) / zoomUnit;

                for (var i = 0; i < this.car.length; i++) {
                    var c = this.car[i];
                    //var pt = project.lngLatToPoint(c.pt);
                    if (c.pt && (!c.by || !c.bx))
                    {
                        var pixel = project.lngLatToPoint(c.pt);
                        c.bx = pixel.x;
                        c.by = pixel.y;
                    }
                    if (c.bx && c.by) {
                        c.x = (c.bx - nwMc.x) / zoomUnit;
                        c.y = (nwMc.y - c.by) / zoomUnit;
                        if ( c.x == 0 && c.y == 0 )
                        {
                            var a;
                        }
                    }
                    //var lg = project.pointToLngLat(new BMap.Pixel());
                    //var px = map.pointToOverlayPixel(c.pt);
                    //c.x = px.x - py.x;
                    //c.y = px.y - py.y;
                }
                
                //if (rs.length > 0) {
                //    showStars(rs);
                //}
                
              //  this.canvas.style.left = py.x + 'px';
              //  this.canvas.style.top = py.y + 'px';
                this.canvas.style.opacity = 0.8;

                this.ctx.clearRect(0, 0, map.getSize().width, map.getSize().height);
                this.ctx.fillRect(0, 0, map.getSize().width, map.getSize().height);

                this.ctx.globalCompositeOperation = "lighter";
                
                if ( this.car.length > 0 )
                {
                    var dcar = [];
                    for(var i = 0; i<this.car.length; i++)
                    {
                        c = this.car[i];
                        if (c.x == 0 && c.y == 0)
                            continue;
                      //  if (c.x > pixel3.x || c.y > pixel3.y || c.x < pixel2.x || c.y < pixel2.y)
                      //      continue;
                        if (this.car[i].render(4))
                            dcar.push(this.car[i]);
                    }
                    if ( dcar.length < 100 )
                    {
                        for(var i=0; i<dcar.length; i++)
                        {
                            dcar[i].render(10);
                        }
                    }
                }
            }
            var myCompOverlay = new ComplexCustomOverlay(new BMap.Point(0.407845, 0.914101));
            map.addOverlay(myCompOverlay);
            map.addEventListener('click', function (a, b) {
                console.log(a, b);
            })
        }
    </script>
</body>
</html>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值