Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leaflet: update map

Here is my function that I use to draw a Leaflet map in my website:

function drawTweetMap(points) {
    if (tweetMap != null)
        tweetMap.remove();  

    var london = [51.505, -0.09];
    tweetMap = L.map('tweetMap').setView(london, 5);

    var cloudmadeUrl = 'http://{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.jpg';
    var subDomains = ['otile1','otile2','otile3','otile4'];
    var cloudmadeAttrib = 'Data, imagery and map information provided by <a href="http://open.mapquest.co.uk" target="_blank">MapQuest</a>, <a href="http://www.openstreetmap.org/" target="_blank">OpenStreetMap</a> and contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/" target="_blank">CC-BY-SA</a>';
    L.tileLayer(cloudmadeUrl, 
                  {attribution: cloudmadeAttrib, 
                   maxZoom: 18,
                   subdomains: subDomains})
    .addTo(tweetMap);

    var markers = L.markerClusterGroup();
    var points_rand = L.geoJson(points, {onEachFeature: onEachFeature});
    markers.addLayer(points_rand);
    tweetMap.addLayer(markers);
    tweetMap.fitBounds(markers.getBounds());
}

This function is called periodically:

mapWatch = setInterval(function() {
    retrieveCurrentTweetPositions()},
numMinutes*60*1000);

in this function:

function retrieveCurrentTweetPositions() {
    var points = retrieveCurrentPositions();
    var mapInput = translatePointsInMapFormat(points);
    drawTweetMap(mapInput);
}

Unfortunately, if the map is drawn in this way, the result is the following: enter image description here

In other questions I found that it is possible to invalidate the size of the map to fix this problem, so it was suggested to call on startup this function:

function updateTweetMapPosition() { 
    setTimeout(function(){
        tweetMap.invalidateSize(true);}
    ,500)
}

I did so, and this solves the problem during the first map drawing. However, when I try to redraw the map for a second time, the result is as follows:

enter image description here

Has anyone experienced this problem? How can I redraw the map with a full loading of its content?

Thanks.


EDIT

Here is the jsFiddle: http://jsfiddle.net/qzpwvqzk/

like image 380
Eleanore Avatar asked Apr 21 '15 15:04

Eleanore


2 Answers

I solved the problem as follows

setTimeout(function(){map.invalidateSize(true);},500);

like image 143
user14316535 Avatar answered Sep 29 '22 14:09

user14316535


Use https://leafletjs.com/reference-1.7.1.html#map-invalidatesize

tweetMap.invalidateSize()
like image 29
ncux199rus Avatar answered Sep 29 '22 14:09

ncux199rus