egeloen / IvoryGoogleMapBundle

Google Map API v3 integration for your Symfony2 project.
https://github.com/egeloen/ivory-google-map
MIT License
217 stars 152 forks source link

AutoZoom with minimum zoom level #192

Closed KevinSleegers closed 7 years ago

KevinSleegers commented 7 years ago

Hi,

I would like to use the AutoZoom functionality, but still make it possible to define a minimum zoom level.

Can you tell me how I can accomplish such thing?

Thanks in advance, Kevin

egeloen commented 7 years ago

Hey @KevinSleegers

I just give a try to your interesting issue :)

First, you can use the map options (maxZoom and minZoom) but it strongly limits the map zoom...

I have google it and found this answer: http://stackoverflow.com/questions/2989858/google-maps-v3-enforcing-min-zoom-level-when-using-fitbounds

When using the auto zoom feature, the bundle internally uses a bound in order to wrap all overlay elements and then, make the map fit this bounds. In order to limit the zoom automatically, you need to reproduce this javascript snippet with the library:

google.maps.event.addListener(map, 'zoom_changed', function() {
    var zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function() {
        if (this.getZoom() > 15 && this.initialZoom === undefined) {
            // Change max/min zoom here
            this.setZoom(15);
            this.initialZoom = true;
        }

        google.maps.event.removeListener(zoomChangeBoundsListener);
    });
});
$eventRenderer = $this->get('ivory.google_map.helper.renderer.event.event');
$formatter = $this->get('ivory.google_map.helper.formatter');

$eventListener = 'zoomChangeBoundsListener';

$code = <<<EOF
if (this.getZoom() > 15 && this.initialZoom === undefined) {
    // Change max/min zoom here
    this.setZoom(15);
    this.initialZoom = true;
}
google.maps.event.removeListener($eventListener);
EOF;

$boundEvent = new Event(
    $map->getVariable(),
    'bounds_changed',
    $formatter->renderClosure($code)
);

$boundEvent->setVariable($eventListener);

$zoomEvent = new Event(
    $map->getVariable(),
    'zoom_changed',
    $formatter->renderClosure($eventRenderer->render($boundEvent))
);

$map->getEventManager()->addEvent($zoomEvent);

I have git it a try and it's working :)