Jakob
Jakob

Reputation: 4854

Zoom in to marker google.maps

I can't zoom to a marker properly.

I'm trying to switch the view to a specified marker, but can't ge tit to work.

I've tried

map.setCenter(location);
map.setZoom(20);

and

map.fitBounds(new google.maps.latLngBounds(location,location));

but in the first case, I simply get zoomed in without the center change being registered, and in the second case I get this overview over a huge area, not zoomed in at all.

Perhaps this issue could be solved by setting a timout from setcenter to setzoom, but that's an ugly hack to me, so a prettier solution would be preferred.

How do you guys do this?

Also - if the infowindow could be displayed without changing content, that would really be a plus to, but the most important thing is to zoom into the marker at the right spot, close up.

thank you very much.

Upvotes: 44

Views: 95778

Answers (3)

Will Ayd
Will Ayd

Reputation: 7164

is this a new instance of a map object you are creating? if so you can just have an object which contains the location and zoom and then pass that object to the map when initalising it like so (taken from the Gmaps basics tutorial http://code.google.com/apis/maps/documentation/javascript/basics.html:

function initialize() {
    var myLatlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
        zoom: 8,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

Upvotes: 2

AdRock
AdRock

Reputation: 3096

I thought I would post an answer here as people wanted some example code.

I too needed to be able to zoom in and center as soon as a marker was added to the map.

Hope this helps somebody.

function getPoint(postcode) {

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

    geocoder.geocode( { 'address': postcode + ', UK'}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {

            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });

            map.setZoom(10);
            map.panTo(marker.position);
        }
        else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}

Upvotes: 11

Jakob
Jakob

Reputation: 4854

The solution turned out to be

map.setZoom(17);
map.panTo(curmarker.position);

Upvotes: 111

Related Questions