If you are building an app that revolves around maps and locations, you might need screens where you mark a particular location/coordinate. While it’s easy for iOS, things can get slightly messy for Android.
I have compiled an example on how you can mark a location with a custom marker such that it works perfectly for both iOS and Android platforms.
First, create a main screen where you will place your MapContainer
or any other buttons.
export const LocationDetailsScreen: React.FunctionComponent = () => {
return (
<SafeAreaView style={styles.safeAreaViewContainer}>
<View style={styles.container}>
<View style={styles.topTextContainer}>
<Text>
Zurück
</Text>
</View>
<MapContainer/>
</View>
</SafeAreaView>
);
};
export const styles = StyleSheet.create({
safeAreaViewContainer: {
flex: 1,
},
container: {
height: '100%',
backgroundColor: 'white',
width: '100%',
},
topTextContainer: {
marginVertical: moderateScale(8),
paddingLeft: moderateScale(30),
},
});
Next, create another component, which will be your map container. This will contain a few sub-components.
The map is created and held inside the MapView. Note that the Id
field needs to be a string.
With a Camera, you basically zoom into the coordinate and display a zoomed version of your map on the screen. The zoomLevel
and animationDuration
can be adjusted as per the requirement.
The MarkerView
is where we will place our custom marker. Now this is something that can cause problems on Android. In order to avoid that, keep these things in mind:
AnnotationContent
is wrapped under a view.MarkerView
itself is wrapped under a view.export const MapContainer: React.FunctionComponent = () => {
const {
favouritePlaceId,
coordinates,
placeName,
customisedName,
} = route.params;
return (
<View style={styles.container}>
<View style={styles.addressContainer}>
<AddressTextBox placeName={placeName} />
</View>
<MapboxGL.MapView
style={styles.map}
logoEnabled={false}
localizeLabels={true}>
<MapboxGL.Camera
zoomLevel={15}
animationMode={'flyTo'}
animationDuration={1100}
centerCoordinate={coordinates}
/>
<View>
<MapboxGL.MarkerView
id={favouritePlaceId.toString()}
coordinate={coordinates}>
<View>
<AnnotationContent customisedName={customisedName} />
</View>
</MapboxGL.MarkerView>
</View>
</MapboxGL.MapView>
</View>
);
};
export const styles = StyleSheet.create({
container: {
flex: 1,
},
map: {
flex: 1,
},
addressContainer: {
position: 'absolute',
flex: 1,
width: '100%',
height: '20%',
zIndex: 1,
},
});
#javascript #mapbox #programming #react-native #android