Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

javascript - Google Maps with fitBounds don't zoom

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 convert a address to latlng because I get the addresses out of a database.

Anyone an idea what is wrong?

    <!DOCTYPE html> 
<html>  
<head>  
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>  
   <title>Google Maps Test</title>  
   <script src="http://maps.google.com/maps/api/js?sensor=false"  
           type="text/javascript"></script>  
</head>  
<body>  
   <div id="map" style="width: 600px; height: 400px;"></div>  

   <script type="text/javascript">  

   var arrAddress = new Array();

   arrAddress[0] = "kelbergen, Amsterdam";
   arrAddress[1] = "Kraailookstraat, Amsterdam";
   arrAddress[2] = "krootstraat, Amsterdam";

   var optionMap = {
          zoom: 16,
          MapTypeId: google.maps.MapTypeId.ROADMAP,
          };

    var map = new google.maps.Map(document.getElementById('map'), optionMap);

    var geocoder = new google.maps.Geocoder();

    var latlngbounds = new google.maps.LatLngBounds();

    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);

    </script>  
</body>  
</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...