Created
March 10, 2014 17:11
-
-
Save DanH42/9469377 to your computer and use it in GitHub Desktop.
Pan a to a given LatLng if the location is not near the middle of the map (either off-screen or near the edge)
This file contains hidden or 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
// License: MIT (c) 2014 Dan Hlavenka | |
function panIfNotClose(map, latLng){ | |
// Calculate the "middle half" of the map | |
var bounds = map.getBounds(); | |
var center = bounds.getCenter(); | |
var northEast = bounds.getNorthEast(); | |
var southWest = bounds.getSouthWest(); | |
var adjust = { | |
lat: Math.abs(northEast.lat() - center.lat()) / 2, | |
lng: Math.abs(northEast.lng() - center.lng()) / 2 | |
}; | |
var newNorthEast = new google.maps.LatLng(northEast.lat() - adjust.lat, northEast.lng() - adjust.lng); | |
var newSouthWest = new google.maps.LatLng(southWest.lat() + adjust.lat, southWest.lng() + adjust.lng); | |
var newBounds = new google.maps.LatLngBounds(newSouthWest, newNorthEast); | |
// If the marker isn't near the center of the map, pan to it | |
if(!newBounds.contains(latLng)) | |
map.panTo(latLng); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment