Skip to content

Instantly share code, notes, and snippets.

@ryanand26
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanand26/1cf83f474a1ec8774c8e to your computer and use it in GitHub Desktop.
Save ryanand26/1cf83f474a1ec8774c8e to your computer and use it in GitHub Desktop.
Center google map whilst maintaining bounds
function centerOnLatLng(center) {
var map = this.map,
bounds = map.getBounds(),
ne = bounds.getNorthEast(),
sw = bounds.getSouthWest(),
neLatDif, swLatDif,
neLonDif, swLonDif,
newBoundary = new google.maps.LatLngBounds();
//Lat
neLatDif = center.lat() - ne.lat();
swLatDif = center.lat() - sw.lat();
//if the sw is closer than ne
if (Math.abs(swLatDif) < Math.abs(neLatDif)) {
//extend the sw lat by the diference
sw = new google.maps.LatLng(sw.lat() + (neLatDif + swLatDif), sw.lng());
}
else {
//extend the ne lat by the diference
ne = new google.maps.LatLng(ne.lat() + (swLatDif + neLatDif), ne.lng());
}
//Lng
neLonDif = center.lng() - ne.lng();
swLonDif = center.lng() - sw.lng();
//if the sw is closer than ne
if (Math.abs(swLonDif) < Math.abs(neLonDif)) {
//extend the sw lng by the diference
sw = new google.maps.LatLng(sw.lat(), sw.lng() + (neLonDif + swLonDif));
}
else {
//extend the ne lng by the diference
ne = new google.maps.LatLng(ne.lat(), ne.lng() + (swLonDif + neLonDif));
}
//extend to these new boundaries
newBoundary.extend(sw);
newBoundary.extend(ne);
map.fitBounds(newBoundary);
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment