我正在为荷兰的一种商店构建商店定位器。数据量很大,目前 map 上放置了 3455 个标记。 我已经实现了markerclusterer来更快地加载 map 。
但我想要 map 上所有当前可见标记的列表。我有这个示例工作( http://jsfiddle.net/glafarge/mbuLw/ ),但是标记数组中有 3455 个项目,速度非常慢。
有人知道这个问题的解决方案吗?
这是我当前的代码:
var map,markers = [], mc;
function initMap() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(-28, 135),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
});
mc = new MarkerClusterer(map, {imagePath: 'images/maps'});
}
function centerMap(newLat, newLong){
map.setCenter({
lat: newLat,
lng: newLong
});
map.setZoom(18);
}
function setCurrentPosition(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
var lat = position.coords.latitude;
var long = position.coords.longitude;
var geolocation = new google.maps.Marker({
position: new google.maps.LatLng(lat, long),
map: map,
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png'
});
centerMap(lat, long);
})
}
}
$(document).ready(function(){
setCurrentPosition();
var marker;
$.ajax({
url: '*[getshoplocationslink]*',
cache: false,
success: function(data){
for(var i = 0; i< data.length; i++){
marker = new google.maps.Marker({
position: new google.maps.LatLng(data[i].loc[1], data[i].loc[0]),
map: map,
title: data[i].name,
icon: 'images/map_pin.png'
});
var content = '*[loading icon]*';
var id = data[i]._id
bindShopInfo(marker, map, content, data[i]._id);
markers.push(marker);
google.maps.event.addListener(map, 'idle', function(){
showVisibleMarkers();
});
$('#shoplist').append('<div class="info info-' + (i+1) +'">'+ data[i].name + '</div>');
}
mc.addMarkers(markers);
$('#loading').addClass('hidden');
}
//end ajax
});
function bindShopInfo(marker, map, content, shopId){
marker.addListener('click', function(){
$('#shopinfo').toggleClass("hidden", false);
$('#shopinfo').fadeIn("slow");
$('#shopinfo').html(content);
loadShop(shopId); //load additional data through another ajax function
});
}
function showVisibleMarkers(){
var bounds = map.getBounds(),
count = 0;
for(var i = 0; i < markers.length; i++){
var marker = markers[i], infoPanel = $('.info-' + (i+1));
if(bounds.contains(marker.getPosition()) == true){
infoPanel.show();
count ++;
}else{
infoPanel.hide();
}
}
}
最佳答案
不要立即处理所有标记,而是尝试在用户更新视口(viewport)时考虑请求。
顺便考虑一下:
- 当有任何视口(viewport)更新时,您可以获得
map
的中心并使用lat
/lng
属性请求他附近的标记。 - 对于具有许多标记的案例,按要求提出请求更为合适。
一些需要帮助的事件:
bounds_changed
拖拽
拖拽开始
空闲
我在my codepen上做了一个例子为了更好的理解。请参阅浏览器控制台,了解有关每个新标记的 lat
/lng
的更多详细信息。
See more about google maps events: https://developers.google.com/maps/documentation/javascript/events
祝你好运!
关于javascript - 在 Google map 中显示可见标记,许多标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38952581/