Last active
August 29, 2015 14:05
-
-
Save ryanand26/1cf83f474a1ec8774c8e to your computer and use it in GitHub Desktop.
Center google map whilst maintaining bounds
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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