Google Maps with fitBounds don't zoom

后端 未结 1 1399
不思量自难忘°
不思量自难忘° 2020-12-11 10:41

Following code works ok, except that it not zoom to the given points.

If I take the Latlng direct it works, without convert the address to Latlng.

I need to

相关标签:
1条回答
  • 2020-12-11 10:56

    Google's geocoder is asynchronous so the map.fitbounds(latlngbounds) is being called before all of the points have been geocoded. The simplest way to fix this would be to put the map.fitbounds(latlngbounds) right after the extend call.

    for(var i = 0; i < arrAddress.length; i++) {
         geocoder.geocode( { 'address': arrAddress[i]}, function(results, status) {
              if (status == google.maps.GeocoderStatus.OK) {
    
                    var marker = new google.maps.Marker({
                      map: map, 
                      position: results[0].geometry.location
                    });
    
                    latlngbounds.extend(results[0].geometry.location);
                    map.fitBounds(latlngbounds);
    
            }
        });
    }
    

    UPDATE: Here is a better answer. In the last example the map.fitbounds(latlngbounds) method is called repeatedly, which can possibly create problems when there are lots of markers. Using the answer in this question you can create an asynchronous loop to make sure the map.fitbounds(latlngbounds) is only called once.

    //replaced the for loop.
    asyncLoop(arrAddress.length, function(loop) {
        geocoder.geocode({                           
            'address': arrAddress[loop.iteration()] //loop counter
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
    
                latlngbounds.extend(results[0].geometry.location);    
            }
    
            //increment the loop counter.
            loop.next();
        });
    }, function() {
        //when the loop is complete call fit bounds.
        map.fitBounds(latlngbounds);
    });    
    
    function asyncLoop(iterations, func, callback) {
        var index = 0;
        var done = false;
        var loop = {
            next: function() {
                if (done) {
                    return;
                }
    
                if (index < iterations) {
                    index++;
                    func(loop);
    
                } else {
                    done = true;
                    callback();
                }
            },
    
            iteration: function() {
                return index - 1;
            },
    
            break: function() {
                done = true;
                callback();
            }
        };
        loop.next();
        return loop;
    }
    

    example has been updated: fiddle of the working code.

    0 讨论(0)
提交回复
热议问题