I’m trying to figure out a way to centre the map view to a particular maker, but the view centre needs to take into an account viewable area of the map which is not always the full width and height and absolute top or left position. The viewable area is easily solved, its calculating the centre is the tricky part.
Now this is react app and I’m using the react-native-map package with google.
So far I have tried the following calculations I found online, but the view is not centring to the marker, its off the screen by the height and width of the viewable area.
Any suggestions how to improve it or packages that can do the calculation for me?
const setMapCenterToMarkerBaseOnViewableArea = (
mapCenterGeolocation: { latitude: number, longitude: number },
zoomLevel: number,
mapDimensions: { height: number, width: number },
mapView: MapView,
visibleArea: { positionTop: number, positionLeft: number, height: number, width: number }
) => {
const mapCenterY = mapDimensions.height / 2;
const mapCenterX = mapDimensions.width / 2;
const visibleCenterY = visibleArea.positionTop + visibleArea.height / 2;
const visibleCenterX = visibleArea.positionLeft + visibleArea.width / 2;
const adjustLatitude = (visibleCenterY - mapCenterY) * zoomLevel / mapDimensions.height;
const adjustLongitude = (visibleCenterX - mapCenterX) * zoomLevel / mapDimensions.width;
const visibleCenterLatitude = mapCenterGeolocation.latitude - adjustLatitude;
const visibleCenterLongitude = mapCenterGeolocation.longitude - adjustLongitude;
mapView.animateToRegion({
latitude: visibleCenterLatitude,
longitude: visibleCenterLongitude,
latitudeDelta: zoomLevel,
longitudeDelta: zoomLevel,
}, 1000);
}
Example mockup; red boundary is the map view able area, Map pin/marker is in the centre of this viewable area. Green is the map itself.