Skip to content

Instantly share code, notes, and snippets.

@amitpdev
Last active July 18, 2017 21:24
Show Gist options
  • Save amitpdev/7090076e70260aec760db4ea5d911532 to your computer and use it in GitHub Desktop.
Save amitpdev/7090076e70260aec760db4ea5d911532 to your computer and use it in GitHub Desktop.
React Native Map Region Persistency - Save and Restore the last region on the map set by your user
import React from 'react'
import { View, StyleSheet, AsyncStorage } from 'react-native'
import MapView from 'react-native-maps'
const DEFAULT_REGION = {
latitude: 32.068185,
longitude: 34.778051,
latitudeDelta: 0.045,
longitudeDelta: 0.045,
}
const STORAGE_REGION_KEY = 'nester.map.region'
_getValue = async (key) => {
try {
value = await AsyncStorage.getItem(key)
return JSON.parse(value)
} catch (error) {
console.log('Error retrieving data: '+error)
throw error
}
}
_saveValue = async (key, value) => {
try {
await AsyncStorage.setItem(key, JSON.stringify(value))
return value
} catch (error) {
console.log(error)
throw error
}
}
_removeValue = async (key) => {
try {
await AsyncStorage.removeItem(key)
return true
} catch (error) {
console.log(error)
throw error
}
}
class MapScreen extends React.Component {
constructor(props) {
super(props)
this.state = {
region: DEFAULT_REGION
}
}
async _initialRegion() {
region = await _getValue(STORAGE_REGION_KEY)
return region || DEFAULT_REGION
}
_onRegionChangeComplete = (region) => {
_saveValue(STORAGE_REGION_KEY, region)
}
componentDidMount() {
this._initialRegion().then(region => {
this.setState({region: region})
})
}
render() {
return (
<View style={styles.container}>
<MapView
style={styles.map}
region={this.state.region}
onRegionChangeComplete={this._onRegionChangeComplete}>
</MapView>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'black'
},
map: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
},
})
export default MapScreen
@amitpdev
Copy link
Author

amitpdev commented May 18, 2017

MapScreen is a React Native component which implements a full screen map using react-native-maps by Airbnb.
It saves (to local storage) the last active map region (or viewport if you prefer) and restores it back whenever its being mounted.
Having consistent map region between app launches improves user experience not needing to pan and zoom the map again and again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment