Google Maps API v3 recenter the map to a marker

Jim picture Jim · Jun 6, 2012 · Viewed 41.6k times · Source

i am searching for a way to recenter (focus) the map if an marker is outside the map. For example if you click on a marker which is not in your viewarea ... Marker 1: New York Marker 2: SanFransisco

in V2 i make this way...but for v3 the containsLatLng needs an extra libary and did not work for me ...(see my other post: Google Maps v3 map.getBounds().containsLatLng is not a function) is they any other way to focus to a marker position??

update:

        if ((!map.getBounds().contains(marker.getPosition())) & (showAllCategoryElements == 0)) {
        var newCenterPointLng = (map.getBounds().getCenter().lng() + marker.getPosition().lng()) / 2;
        var newCenterPointLat = (map.getBounds().getCenter().lat() + marker.getPosition().lat()) / 2;

        map.panTo(marker.getPosition());
        //map.setCenter(new google.maps.LatLng(newCenterPointLat, newCenterPointLng));

        if (!map.getBounds().contains(marker.getPosition())){
            map.zoomOut();
        } 
    }

Answer

puckhead picture puckhead · Jun 6, 2012

The method you want is contains(), not containsLatLng(). map.getBounds().contains(marker.getPosition())

You could use either the setCenter() or panTo() methods of the map to center on the marker position: map.setCenter(marker.getPosition()) or map.panTo(marker.getPosition())

So if I understand correctly what you are trying to do, it should look like this:

if ((!map.getBounds().contains(marker.getPosition())) && (showAllCategoryElements == 0)) { //Note the double &  
    map.setCenter(marker.getPosition());  
    //OR map.panTo(marker.getPosition());  
}