How to send data from one screen to another - react-native

I've got this problem - I can get variables from the props (being sent from MainContainer which contains navigation and those variables. (item.name, item.coordinates.latitude and item.coordinates.longitude work fine on Primary.js, but I can't get them on Map_map.js.
What i'm trying to do is to send the coords (from MainContainer.js through Primary.js which shows names of cities) into in Map_map.js.
When it gets there, it should place a marker only on the location of the city I clicked on.
Also, I currently have Map_map in the navigation tab and when I remove it from there, I can't navigate to it anymore so I need help with that as well.
Code:
MainContainer.js
import * as React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';
// Screens
import Primary from './Screens/Primary';
import Secondary from './Screens/Secondary';
import Map_map from './Screens/Map_map';
// Locations
const mesta = [
{
name: 'Praha',
coordinates: {
latitude: 50.072829,
longitude: 14.433817
}},
,
{
name: 'České Budějovice',
coordinates: {
latitude: 48.975250,
longitude: 14.479161
}},
,
{
name: 'Plzeň',
coordinates: {
latitude: 49.739296,
longitude: 13.372455
}},
{
name: 'Karlovy Vary',
coordinates: {
latitude: 50.231656,
longitude: 12.869226
}},
{
name: 'Ústí nad Labem',
coordinates: {
latitude: 50.662592,
longitude: 14.042824
}},
{
name: 'Liberec',
coordinates: {
latitude: 50.764136,
longitude: 15.047840
}},
{
name: 'Hradec Králové',
coordinates: {
latitude: 50.210071,
longitude: 15.829660
}},
{
name: 'Pardubice',
coordinates: {
latitude: 50.032558,
longitude: 15.773678
}},
{
name: 'Jihlava',
coordinates: {
latitude: 49.401642,
longitude: 15.584001
}},
{
name: 'Brno',
coordinates: {
latitude: 49.190254,
longitude: 16.614144
}},
{
name: 'Olomouc',
coordinates: {
latitude: 49.590450,
longitude: 17.259280
}},
{
name: 'Ostrava',
coordinates: {
latitude: 49.820469,
longitude: 18.269387
}},
{
name: 'Zlín',
coordinates: {
latitude: 49.224215,
longitude: 17.668567
}},
]
//Screen names
const lokace = "Lokace";
const mapa = "Mapa";
const mapa_det = "Mapa_det";
const Tab = createBottomTabNavigator();
function MainContainer() {
return (
<NavigationContainer>
<Tab.Navigator
initialRouteName={lokace}
screenOptions={({ route }) => ({
tabBarIcon: ({ focused, color, size }) => {
let iconName;
let rn = route.name;
if (rn === lokace) {
iconName = focused ? 'home' : 'home-outline';
} else if (rn === mapa) {
iconName = focused ? 'map' : 'map-outline';
}
else if (rn === mapa_det) {
iconName = focused ? 'locate' : 'locate-outline';
}
// You can return any component that you like here!
return <Ionicons name={iconName} size={size} color={color} />;
},
})}
tabBarOptions={{
activeTintColor: '#007aff',
inactiveTintColor: 'grey',
labelStyle: { paddingBottom: 10, fontSize: 10 },
style: { padding: 10, height: 70}
}}>
<Tab.Screen name={lokace} children={() => <Primary towns={mesta}/>}/>
<Tab.Screen name={mapa} children={() => <Secondary towns={mesta}/>}/>
<Tab.Screen name={mapa_det} component={Map_map}/>
</Tab.Navigator>
</NavigationContainer>
);
}
export default MainContainer;
(inside "nav" folder): Primary.js, Secondary.js, Map_map.js
Primary.js
import * as React from 'react';
import { StyleSheet, ScrollView, View, Text, Image } from 'react-native';
import { useNavigation } from '#react-navigation/native';
export default function Primary(props)
{
const navigation = useNavigation();
const map_map = "Map_map";
return(
<ScrollView style=
{{
flex: 1,
}}>
<View>
{props.towns.map(item => (
<Text
style={styles.card}
onPress={() => navigation.navigate('Map_map', item.coordinates)}
>
{item.name}
{item.coordinates.latitude }
{item.coordinates.longitude}
</Text>
))}
</View>
</ScrollView>
);
}
const styles = StyleSheet.create({
card:{
backgroundColor: "#007aff",
borderRadius: 50,
alignItems: 'center',
margin: 5,
padding: 10,
color: 'white',
fontWeight: 'bold'
},
card2:{
backgroundColor: "#FF3300",
borderRadius: 50,
alignItems: 'center',
margin: 5,
padding: 10,
color: 'white',
fontWeight: 'bold'
},
});
Map_map.js
import * as React from 'react';
import { StyleSheet, View, Text, Image } from 'react-native';
import Primary from './Primary.js';
import MapView, {PROVIDER_GOOGLE, Marker} from 'react-native-maps';
function ProfileScreen({ navigation: { goBack } }) {
return (
<View>
<Button onPress={() => goBack()} title="Go back from ProfileScreen" />
</View>
);
}
export default function Map_map({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<MapView
style={styles.map}
provider={PROVIDER_GOOGLE}
//specify our coordinates.
initialRegion=
{{
latitude: 49.061880,
longitude: 17.349916,
latitudeDelta: 0.002,
longitudeDelta: 0.002,
}}
>
<Marker
//coordinate={navigation.getParam(item.coordinates)}
// latitude: 49.061880,
// longitude: 17.349916,
/>
</MapView>
</View>
);
}
const styles = StyleSheet.create({
map: {
height: '100%',
width: '100%'
},
});

In your Primary.js card onPress, do it like below -
onPress={() => navigation.navigate('Map_map', {
data: item.coordinates,
})}

As you can see in the documentation you can pass param to another screen in the second parameter of navigate function.
navigation.navigate('Screen_Name', { param: 'abc' })

Related

How to update coordinates of "showsUserLocation" marker in react native maps?

The (blue dot) marker doesn't response to user movements. I can get the current location of the user, but I can't figure how to update the location of the blue marker. I can use component and update its location, but I need to use blue dot marker because I need to have geolocator button on the top right hand side.
import React, { useState, useEffect } from "react";
import * as Location from "expo-location";
import { Dimensions, StyleSheet, Text, View } from "react-native";
import MapView, { Callout, Circle, Marker } from "react-native-maps";
export default function App() {
const [location, setLocation] = useState(null);
const [errorMsg, setErrorMsg] = useState(null);
useEffect(() => {
(async () => {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== "granted") {
setErrorMsg("Permission to access location was denied");
return;
}
// let location = await Location.getCurrentPositionAsync({});
let watchID = await Location.watchPositionAsync(
{
accuracy: Location.Accuracy.High,
timeInterval: 500,
distanceInterval: 0
},
position => {
setLocation(position);
}
);
})();
}, []);
let text = "Waiting..";
if (errorMsg) {
text = errorMsg;
} else if (location) {
text = JSON.stringify(location);
}
return (
<View style={{ marginTop: 50, flex: 1 }}>
{location && (
<>
<Text style={styles.paragraph}>
{"lat:" + location.coords.latitude}
</Text>
<Text style={styles.paragraph}>
{"long:" + location.coords.longitude}
</Text>
<Text style={styles.paragraph}>
{"acurracy:" + location.coords.accuracy}
</Text>
</>
)}
<MapView
style={styles.map}
initialRegion={{
latitude: 37.78825,
longitude: -122.4324,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421
}}
provider="google"
showsUserLocation={true}
followsUserLocation={true}
// scrollEnabled={false}
>
{location && (
<Marker
coordinate={{
latitude: location.coords.latitude,
longitude: location.coords.longitude
}}
></Marker>
)}
</MapView>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center"
},
map: {
width: Dimensions.get("window").width,
height: Dimensions.get("window").height
}
});
Thanks!
Adding followsUserLocation={true} props fixed my problem.

The action'NAVIGATE' with payload {"name":"Map_map"} was not handled > by any navigator

The error appears when I click on any of the buttons from Primary.js
Error:
The action'NAVIGATE' with payload {"name":"Map_map"} was not handled
by any navigator. Do you have a screen named 'Map_Map?
File structure:
app.js
nav (folder)
MainContainer.js
Screens (folder)
Primary.js /trying to get from this
Secondary.js
Map_map.js /to this
-App.js (only contains MainContainer.js
MainContainer.js
import * as React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';
// Screens
import Primary from './Screens/Primary';
import Secondary from './Screens/Secondary';
import Map_map from './Screens/Map_map';
// Locations
const mesta = [
{
name: 'Praha',
coordinates: {
latitude: 50.072829,
longitude: 14.433817
}},
,
{
name: 'České Budějovice',
coordinates: {
latitude: 48.975250,
longitude: 14.479161
}},
,
{
name: 'Plzeň',
coordinates: {
latitude: 49.739296,
longitude: 13.372455
}},
{
name: 'Karlovy Vary',
coordinates: {
latitude: 50.231656,
longitude: 12.869226
}},
{
name: 'Ústí nad Labem',
coordinates: {
latitude: 50.662592,
longitude: 14.042824
}},
{
name: 'Liberec',
coordinates: {
latitude: 50.764136,
longitude: 15.047840
}},
{
name: 'Hradec Králové',
coordinates: {
latitude: 50.210071,
longitude: 15.829660
}},
{
name: 'Pardubice',
coordinates: {
latitude: 50.032558,
longitude: 15.773678
}},
{
name: 'Jihlava',
coordinates: {
latitude: 49.401642,
longitude: 15.584001
}},
{
name: 'Brno',
coordinates: {
latitude: 49.190254,
longitude: 16.614144
}},
{
name: 'Olomouc',
coordinates: {
latitude: 49.590450,
longitude: 17.259280
}},
{
name: 'Ostrava',
coordinates: {
latitude: 49.820469,
longitude: 18.269387
}},
{
name: 'Zlín',
coordinates: {
latitude: 49.224215,
longitude: 17.668567
}},
]
//Screen names
const lokace = "Lokace";
const mapa = "Mapa";
const mapa_det = "Mapa_det";
const Tab = createBottomTabNavigator();
function MainContainer() {
return (
<NavigationContainer>
<Tab.Navigator
initialRouteName={lokace}
screenOptions={({ route }) => ({
tabBarIcon: ({ focused, color, size }) => {
let iconName;
let rn = route.name;
if (rn === lokace) {
iconName = focused ? 'home' : 'home-outline';
} else if (rn === mapa) {
iconName = focused ? 'map' : 'map-outline';
}
else if (rn === mapa_det) {
iconName = focused ? 'locate' : 'locate-outline';
}
// You can return any component that you like here!
return <Ionicons name={iconName} size={size} color={color} />;
},
})}
tabBarOptions={{
activeTintColor: '#007aff',
inactiveTintColor: 'grey',
labelStyle: { paddingBottom: 10, fontSize: 10 },
style: { padding: 10, height: 70}
}}>
<Tab.Screen name={lokace} children={() => <Primary towns={mesta}/>}/>
<Tab.Screen name={mapa} children={() => <Secondary towns={mesta}/>}/>
<Tab.Screen name={mapa_det} component={Map_map}/>
</Tab.Navigator>
</NavigationContainer>
);
}
export default MainContainer;
Primary.js
import * as React from 'react';
import { StyleSheet, ScrollView, View, Text, Image } from 'react-native';
import { useNavigation } from '#react-navigation/native';
export default function Primary(props, {Map_map})
{
const navigation = useNavigation();
const map_map = "Map_map";
return(
<ScrollView style=
{{
flex: 1,
}}>
<View>
{props.towns.map(itemz => (
<Text
style={styles.card}
onPress={() => navigation.navigate(map_map)} >
{itemz.name}
</Text>
))}
</View>
</ScrollView>
);
}
const styles = StyleSheet.create({
card:{
backgroundColor: "#007aff",
borderRadius: 50,
alignItems: 'center',
margin: 5,
padding: 10,
color: 'white',
fontWeight: 'bold'
},
card2:{
backgroundColor: "#FF3300",
borderRadius: 50,
alignItems: 'center',
margin: 5,
padding: 10,
color: 'white',
fontWeight: 'bold'
},
});
You should use the name prop to navigate instead of component name.
<Tab.Screen name={mapa_det} component={Map_map}/>
So, it should be:
navigation.navigate("Mapa_det")

Null is not an object(evaluating 'mapView.current.animateToRegion')

In component Description I have a button, when I press the button I send to Map component coordinates of marker:
const onNavigationTap = () => {
navigation.navigate('Map', {
destination: data["data"].coordinates,
});
}
In component Map I have condition:
const mapView = React.createRef();
if (route.params){
mapView.current.animateToRegion({
latitude: route.params.destination.latitude,
longitude: route.params.destination.longitude,
latitudeDelta: 0.4,
longitudeDelta: 0.4,
},1000);
}
return (
<MapView ref={mapView} />
)
So when I open Map I want to show region near marker. I've tried to create a button on Map screen:
<TouchableOpacity style={{
position: 'absolute',
top: '5%',
alignSelf: 'flex-start'
}} onPress={animateMap}><Text>Start</Text></TouchableOpacity>
and then I created function:
const animateMap = () => {
mapView.current.animateToRegion({ // Takes a region object as parameter
latitude: destination.latitude,
longitude: destination.longitude,
latitudeDelta: 0.4,
longitudeDelta: 0.4,
},1000);
}
And this solution with button on Map screen working fine but what I want is to animateToRegion not on button press, but when user opens the Map from Description component. I don't understand why in first case I got Null is not an object(evaluating 'mapView.current.animateToRegion'). Please tell me what should I do if I want to animateToRegion using params that I get from another component?
It seems that the error you got is because mapView.current.animateToRegion is null.
You can follow this sample code and code snippet below on how to achieve your use case:
App.js
import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import MapScreen from './Map'
function HomeScreen({ navigation }) {
const onBtnPress = () =>{
navigation.navigate('Maps', {
destination: { latitude: 40.463667, longitude: -3.74922 },
});
}
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={onBtnPress}
/>
</View>
);
}
const Stack = createNativeStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Maps" component={MapScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
Map.js
import React, { Component } from 'react';
import { Text, View, StyleSheet, Dimensions } from 'react-native';
import MapView, { Marker, Circle, Polyline } from 'react-native-maps';
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
map: {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
},
});
function Map (props){
const onMapLoad=()=>{
console.log(this.mapView)
console.log(props.route.params.destination.latitude)
this.mapView.animateToRegion({
latitude: props.route.params.destination.latitude,
longitude: props.route.params.destination.longitude,
latitudeDelta: 0.4,
longitudeDelta: 0.4,
},1000);
}
return (
<View style={styles.container}>
<MapView
ref={(ref) => this.mapView = ref}
style={styles.map}
initialRegion={{
latitude: 37.78825,
longitude: -122.4324,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
onMapReady={onMapLoad}
>
</MapView>
</View>
);
}
export default Map;

react-native-maps does not work after build the app using expo?

Problem:
I have created a react native application with expo clii. In there I am using react-native-maps.With expo app It was very worked. But after building the standalone app and when I try to open it it did not navigate to that component.It mean when I click on the location tab it restart the app.This is my that component code.
import React, { Component } from "react";
import {
StyleSheet,
KeyboardAvoidingView,
View,
ActivityIndicator,
TouchableOpacity,
TextInput,
Text,
Image,
ScrollView,
Dimensions
} from "react-native";
import MapView from "react-native-maps";
import PageHeader from "../Shared/pageHeader/PageHeader";
const windowheight = (Dimensions.get("window").height * 75) / 100;
const windowwidth = (Dimensions.get("window").width * 80) / 100;
class Location extends Component {
constructor(props) {
super(props);
this.state = {
focusedLocation: {
latitude: 6.9336686,
longitude: 79.8489527,
latitudeDelta: 0.0322,
longitudeDelta:
(Dimensions.get("window").width / Dimensions.get("window").height) *
0.0322
},
locationChosen: false,
placesList: [],
isFocused: false
};
}
static navigationOptions = {
header: null
};
componentDidMount() {
navigator.geolocation.getCurrentPosition(
pos => {
const coordsEvent = {
nativeEvent: {
coordinate: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude
}
}
};
this.pickLocationHandler(coordsEvent);
},
err => {
console.log(err);
alert("Fetching the Position failed");
}
);
}
reloadLocation = () => {
navigator.geolocation.getCurrentPosition(
pos => {
const coordsEvent = {
nativeEvent: {
coordinate: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude
}
}
};
this.pickLocationHandler(coordsEvent);
},
err => {
console.log(err);
alert("Fetching the Position failed");
}
);
};
pickLocationHandler = event => {
this.setState({ locationChosen: true });
const coords = event.nativeEvent.coordinate;
let placesList = [];
let places = [];
this.map.animateToRegion({
...this.state.focusedLocation,
latitude: coords.latitude,
longitude: coords.longitude
});
const apikey = "AIzaSyDsA9zWFxw__OiApEKhbUEqVL4VQ_uN0hc";
fetch(
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" +
coords.latitude +
"," +
coords.longitude +
"&radius=800" +
"&type=parking" +
"&key=" +
apikey
)
.then(response => response.json())
.then(responseJson => {
if (responseJson) {
placesList = responseJson.results;
placesList.map((el, index) => {
var place = {
title: el.name,
coordinates: {
latitude: el.geometry.location.lat,
longitude: el.geometry.location.lng
}
};
places.push(place);
});
this.setState({ placesList: places });
}
});
};
componentWillUnmount = () => {
this.setState(prevState => {
return {
focusedLocation: {
...prevState.focusedLocation,
latitude: 6.9336686,
longitude: 79.8489527
},
locationChosen: false,
placesList: []
};
});
};
render() {
let marker = null;
if (this.state.locationChosen) {
marker = <MapView.Marker coordinate={this.state.focusedLocation} />;
}
const places = this.state.placesList;
return (
<View>
<PageHeader
title="Nearby Parking"
image={require("../../../assets/shape.png")}
width="4%"
marginTop="1.5%"
marginLeft="40%"
></PageHeader>
<View
style={{
marginTop: "2%",
marginBottom: "2%",
marginLeft: "2%",
marginRight: "2%"
}}
>
<MapView
style={styles.map}
provider="google"
initialRegion={this.state.focusedLocation}
showsUserLocation={true}
zoomControlEnabled={true}
style={styles.map}
onPress={this.pickLocationHandler}
onUserLocationChange={this.reloadLocation}
ref={ref => (this.map = ref)}
>
{places.map((place, index) => {
return (
<MapView.Marker
key={index}
coordinate={place.coordinates}
title={place.title}
pinColor="red"
tooltip={true}
/>
);
})}
{marker}
</MapView>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
map: {
height: "100%",
width: "100%"
},
button: {
margin: 8,
backgroundColor: "#fff",
borderWidth: 1,
borderColor: "#fff",
alignItems: "center",
justifyContent: "center",
width: 50,
height: 50,
borderRadius: 100,
marginTop: windowheight,
marginLeft: windowwidth
},
callout: {},
calloutButton: {
marginTop: windowheight,
marginLeft: windowwidth,
borderWidth: 1,
borderColor: "rgba(0,0,0,0.2)",
alignItems: "center",
justifyContent: "center",
width: 50,
height: 50,
backgroundColor: "#2b78fe",
borderRadius: 100,
shadowColor: "#e9ebee"
}
});
export default Location;
Can someone tell me what kind of reason would cause this issue.Thank you.
Modify the following
Add flex: 1 to your parent view:
// ... other code
<View style={{ flex: 1 }}> <=== add flex here
<PageHeader
title="Nearby Parking"
image={require("../../../assets/shape.png")}
// ... other code
Change your map styling to the following:
map: {
flex: 1
}
Remove the duplicate declaration of style on the
// ... other code
<MapView
style={styles.map}
provider="google"
initialRegion={this.state.focusedLocation}
showsUserLocation={true}
zoomControlEnabled={true}
style={styles.map} <=== remove this
onPress={this.pickLocationHandler}
onUserLocationChange={this.reloadLocation}
ref={ref => (this.map = ref)}>
// ... other code
The correct way to use the GOOGLE provider
import MapView, { PROVIDER_GOOGLE, Marker } from 'react-native-maps'
// ... other code
<MapView
style={styles.map}
provider={PROVIDER_GOOGLE} <=== make this chage
initialRegion={this.state.focusedLocation}
showsUserLocation={true}
zoomControlEnabled={true}
style={styles.map}
onPress={this.pickLocationHandler}
onUserLocationChange={this.reloadLocation}
ref={ref => (this.map = ref)}>
// ... other code
Hope this Helps!

How to dsplay coordinates of GPS in a Mapview?

I need your help to know how to display GPS coordinates in a MapView.
I want to track a person's location from gps coordinates (longitude and latitude).
I tried too much to recover the coordinates in a MapView but I did not arrive to do it, I am blocked.
So, I get the coordinates from a web service and I display them in a TextView.
This is my code:
import React, { Component } from 'react';
import { Constants, Location, Permissions } from 'expo';
import { Card } from 'react-native-paper';
import { Polyline } from 'react-native-maps';
import {
StyleSheet,
Platform,
View,
ActivityIndicator,
FlatList,
Text,
Image,
TouchableOpacity,
Alert,
YellowBox,
AppRegistry,
Button,
} from 'react-native';
export default class gps extends Component {
static navigationOptions = ({ navigation }) => {
return {
title: 'Suivi GPS',
headerStyle: {
backgroundColor: 'transparent',
},
headerTitleStyle: {
fontWeight: 'bold',
color: '#000',
zIndex: 1,
fontSize: 18,
lineHeight: 25,
fontFamily: 'monospace',
},
};
}
state = {
mapRegion: null,
dat: '',
};
GetItem() {}
componentDidMount() {
this.webCall();
}
FlatListItemSeparator = () => {
return (
<View
style={{
height: 0.5,
width: '100%',
backgroundColor: '#000',
}}
/>
); //
};
webCall = () => {
return fetch('http://first-ontheweb.com/onLineSenior/pos.php')
.then(response => response.json())
.then(responseJson => {
this.setState({
isLoading: false,
dataSource: responseJson,
});
})
.catch(error => {
console.error(error);
});
};
render() {
if (this.state.isLoading) {
return (
<View
style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<ActivityIndicator size="large" />
</View>
);
}
return (
<View style={styles.map}>
<FlatList
data={this.state.dataSource}
ItemSeparatorComponent={this.FlatListItemSeparator}
renderItem={({ item }) => (
<View>
<Text style={styles.textView}>Longitude :</Text>
<Text style={styles.textView}>{item.longitude}</Text>
<Text style={styles.textView}>Latitude :</Text>
<Text style={styles.textView}>{item.latitude}</Text>
</View>
)}
keyExtractor={(index) => index.toString()}
/>
</View>
);
}
}
const styles = StyleSheet.create({
map: {
...StyleSheet.absoluteFillObject,
},
});
So, I want to display the GPS coordinates in a MapView.
Thanks.
You can do something like this:
first import the mapView:
import MapView from "react-native-maps";
Then:
state = {
focusedLocation: {
latitude: 37.7900352, //or your coordinates
longitude: -122.4013726, //or your coordinates
latitudeDelta: 0.0122,
longitudeDelta:
Dimensions.get("window").width /
Dimensions.get("window").height *
0.0122
}
};
render() {
let marker = null;
if (this.state.locationChosen) {
marker = <MapView.Marker coordinate={this.state.focusedLocation} />;
}
return (
let marker = <MapView.Marker coordinate={this.state.focusedLocation} />;
<View style={styles.container}>
<MapView
initialRegion={this.state.focusedLocation}
style={//map style here}
>
{marker}
</MapView>
</View>
);
}
you need to install react-native-maps package than
import MapView from 'react-native-maps';
Rendering a Map with an initial region
<MapView
initialRegion={{
latitude: 37.78825,
longitude: -122.4324,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
/>
Using a MapView while controlling the region as state
getInitialState() {
return {
region: {
latitude: 37.78825,
longitude: -122.4324,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
},
};
}
onRegionChange(region) {
this.setState({ region });
}
render() {
return (
<MapView
region={this.state.region}
onRegionChange={this.onRegionChange}
/>
);
}
Rendering a list of markers on a map
import { Marker } from 'react-native-maps';
<MapView
region={this.state.region}
onRegionChange={this.onRegionChange}
>
{this.state.markers.map(marker => (
<Marker
coordinate={marker.latlng}
title={marker.title}
description={marker.description}
/>
))}
</MapView>
you can find more in the documention here.
https://github.com/react-native-community/react-native-maps