添加标记时,googlemaps-js-api会阻塞ui

google maps js api blocks ui when adding markers

本文关键字:ui googlemaps-js-api 加标记 添加      更新时间:2023-09-26

我在移动浏览器上使用谷歌地图时遇到问题。

我正在进行的项目需要在地图上显示大约500个标记,但当添加它们时,ui会冻结。

我正在使用markcluster添加标记,一旦标记出现在页面上,性能就很好。有没有一种方法可以异步添加标记,或者在用户开始滚动后暂停添加标记?

这是我们正在使用的代码:

var mcOptions = { gridSize: 50, maxZoom: 15, zoomOnClick: false };
var mc = new MarkerClusterer(context.map, [], mcOptions);
getMarkerLocations().then(function(branches){    
    branches.forEach(function(branch) => {
        var marker = new google.maps.Marker({
            icon: {
                path: google.maps.SymbolPath.CIRCLE,
                scale: 2,
                strokeColor: 'red',
                fillColor: 'red',
                strokeWeight: 2,
                fillOpacity: 1
            },
            position: new google.maps.LatLng(branch.Latitude, branch.Longitude),
            visible: true
        });
        mc.addMarker(marker);
    });
});

谢谢你的地理编码,这就像一个魅力!对于其他有同样问题的人,以下是我解决问题的方法:

.then(function(branches){
    var loopFunction = function(branchesToAdd) => {
                if (branchesToAdd.length === 0) return;
            var item = branchesToAdd.pop();
            var marker = new google.maps.Marker({
                ....
            });
            mc.addMarker(marker);
            setTimeout(function(){loopFunction(branchesToAdd)}, 30);
        };
    loopFunction(branchesToShow);
});

异步添加标记,使用setTimeout计划添加每个标记,这将给浏览器一些时间来渲染和响应UI。