views:

1392

answers:

1

I'm trying to use GLatLngBounds to make all the markers on the map visible. Below is a small example of what I'm doing.

INV.createMap = function(containerId) {
    var map = null;
    var geocoder = null;
    var bounds = new GLatLngBounds();

    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById(containerId), {
            size: new GSize(600, 300)
        });
        map.setCenter(new GLatLng(54.729378425601766, 25.279541015625), 15);
        map.addControl(new GSmallZoomControl());
        geocoder = new GClientGeocoder();
    }

    return {
        markAdress: function(address, infoContentHtml) {
            if (map !== null && geocoder !== null) {
                geocoder.getLatLng(address, function(point) {
                    if (point) {
                        var marker = new GMarker(point);
                        GEvent.addListener(marker, 'mouseover', function() {
                            if (!map.getInfoWindow().getPoint().equals(this.getLatLng())) {
                                this.openInfoWindowHtml(infoContentHtml);
                            }
                        });
                        map.addOverlay(marker);
                        bounds.extend(point);
                    }
                });
            }
        },

        finalize: function() {
            map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
        }
    };
};

Usage:

var m = INV.createMap('whatever');
var addresses = ...
for (var i = 0, l = addresses.length; i < l; i++) {
    m.markAdress('address...', 'htmlInfo...');
}
m.finalize();

The problem is that the zoom level is completely wrong (waaay too zoomed out) and the markers appear on the left top corner of the map for some reason (but all of them are visible).

What am I doing wrong?

EDIT: Ignore this question. I've made a stupid mistake - I overlooked the fact that GClientGeocoder makes asynchronous requests so the finalize() method is called too early.

+1  A: 

The last argument of the function call below specifies the zoom level:

map.setCenter(new GLatLng(54.729378425601766, 25.279541015625), 15);

This article talks a bit about zooming. So the zooming level is a bit too high.

Further this tutorial tells you how to fit the map zooming to properly display a set of markers.

Hope this helps

ardsrk
The line you've quoted is just in the initialisation stage. If you finish reading the code, you'll find the line that actually sets the final zoom level.The tutorial you've linked to seems to be no different from what Ree is doing, except for the minor detail that it calls setZoom rather than setting both centre and zoom in a setCenter call. FTR, I use the setCenter(centre, zoom) form with no difficulty. Maybe a complete, self-contained testcase would help diagnose the problem.
Stewart