Reputation: 3639
I'm using Google Maps to show what users are drinking and where, so they can go check out who drinks what near them.
You can see the current version of the map here: www.vinpin.com/map
You'll see that the page itself doesn't lag, the ajax call to the server is super fast but the bottleneck is really Google Maps that just freezes for a few seconds while I loop and add the markers on the map.
Is there a way to add markers without freezing the map?
Basically what I do is loop on a json list of markers and add them like so:
// Map Creation Part:
var mapOptions = {
center: new google.maps.LatLng(47.279229, -94.21875), // North America
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 4,
minZoom: 3
};
map = new google.maps.Map(document.getElementById("google_map_canvas"), mapOptions);
// Part that's in the loop:
var shadow = {
url: (isPin) ? pin_marker_icon_shadow : user_marker_icon_shadow,
size: new google.maps.Size(29.0, 25.0),
anchor: new google.maps.Point(8.0, 12.0)
};
var image = {
url: (isPin) ? pin_marker_icon : user_marker_icon,
size: new google.maps.Size(16.0, 25.0),
anchor: new google.maps.Point(8.0, 12.0)
};
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
icon: image,
shadow: shadow
});
markers.push(marker);
Is there anything wrong with this? Any better way of handling a lot of markers?
Thanks!
Upvotes: 0
Views: 1444
Reputation: 11
Actually you don't need to set a delay (of 200ms for example) you can just use 0 delay. The reason this works is that Javascript is executed in a single thread and the browser will execute your whole AJAX request callback (including the loop) until control is returned to the browser that only then is able to process other things like map movement etc.
Throwing in regular setTimeout() calls interrupts the current exceution (your loop) and schedules it for later. This gives the browser an opportunity to also schedule other things (like map movement) in between. This will slightly slow down the insertion of your markers for the benefit of better user experience (less lag).
If you have a list of markers your insertion procedure could possibly look like this:
function addMarkers(jsonList) {
if (jsonList.length > 0) {
var element = jsonList.pop();
var marker = new google.maps.Marker({...});
markers.push(marker);
setTimeout(function() {
addMarkers(jsonList);
}, 0);
}
}
Might not be the most elegant solution possible, but I hope this explanation will push you and maybe others in the right direction.
Upvotes: 1
Reputation: 161324
Don't add all the markers at once, add them in smaller chunks (say 10 at a time), with a setTimeout between chunks to give the browser time to render the changes to the map.
Upvotes: 1