Lothar
Lothar

Reputation: 3489

Angularjs - Google Maps Set Zoom for Multiple markers

I am using this set of Google Maps directives in my app. My question... why do certain pairs of markers have a correct zoom level (meaning I can see both of them and they are not zoomed in too close) while under certain circumstance the zoom level is off (meaning I cannot see the markers without zooming out a click or two)

In my (jade, fwiw) template I use it like so:

div(ng-if="mapready") //this ng-if is to force the map repaint when done, otherwise it can glitch
    google-map(center="fromCenter.center", zoom="zoomcalc")
        markers
            marker(coords="fromMarker", icon="greenMarker")
            marker(coords="toMarker", icon="redMarker")

That zoom is calculated like so:

    getBoundsZoomLevel: function (bounds, mapDim) {
        var zoomValue = 10;

        var WORLD_DIM = { height: 256, width: 256 };
        var ZOOM_MAX = 21;

        var ne = bounds.getNorthEast();
        var sw = bounds.getSouthWest();

        var latFraction = Math.abs((this._latRad(ne.lat()) - this._latRad(sw.lat())) / Math.PI);

        var lngDiff = ne.lng() - sw.lng();
        var lngFraction = ((lngDiff < 0) ? (lngDiff + 360) : lngDiff) / 360;

        var latZoom = this._zoom(mapDim.height, WORLD_DIM.height, latFraction);
        var lngZoom = this._zoom(mapDim.width, WORLD_DIM.width, lngFraction);

        zoomValue = lngZoom <= 0 ? latZoom : Math.min(latZoom, lngZoom, ZOOM_MAX);

        return zoomValue;
    }

Within that code _zoom is:

    _zoom: function (mapPx, worldPx, fraction) {
        return Math.floor(Math.log(mapPx / worldPx / fraction) / Math.LN2);
     }

Here is the other function used in this calculation in case it will help you:

    _latRad: function (lat) {
        var sin = Math.sin(lat * Math.PI / 180);
        var radX2 = Math.log((1 + sin) / (1 - sin)) / 2;

        return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2;
    }

The problem is that the calculation for zoom is occasionally (it usually works correctly) off. A good example, if I set the two markers to both be in San Francisco, they will work. However, if I place one of those markers across the bay in Oakland (leaving the other in SF), the zoom will be too tight and I need to zoom out to see both markers.

I have read about the maps API fitBounds() method but do not know if it would work with these directives nor do I see how to apply it regardless. The directive does have a bounds parameter but again, I do not see how to apply it with multiple markers.

Upvotes: 1

Views: 2322

Answers (1)

Christina
Christina

Reputation: 1126

try using:

div(ng-if="mapready")
    google-map(center="fromCenter.center", zoom="zoomcalc")
        markers(fit="true")
            marker(coords="fromMarker", icon="greenMarker")
            marker(coords="toMarker", icon="redMarker")

Upvotes: 1

Related Questions