Google Maps API v3 recenter the map to a marker
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());
}
Comments
-
Jim almost 2 years
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(); } }
-
Jim almost 12 yearswith your tips i changed it (see the top of my post)...
map.setCenter
is not required if i usePanTo
? Now i have an "a is undefined" in "maps.gstatic.com/cat_js/intl/de_de/mapfiles/api-3/9/2/… file" -
puckhead almost 12 yearsUpdated code above. You may need to post more code if you continue to get an error.