Reputation: 171
I use DefaultMarkers to get location from user.
I have a button and a function. In the function I use a code to show latitude in console. Now When I press the button, in console not happening but for second press I can see latitude in console.
If I change location and try again, I should press button for twice to see latitude in console.
constructor(props){
super(props);
this.state={
markers: [],
}
}
onMapPress(e) {
this.setState({
markers: [
{
coordinate: e.nativeEvent.coordinate,
key: 0,
},
],
});
}
SaveAddress=()=>{
console.log(JSON.stringify(this.state.markers[0].coordinate.latitude);
}
<Button onPress={this.SaveAddress}>
<Text>Save</Text>
</Button>
<MapView
style={styles.map}
initialRegion={{
latitude: 28.95761453,
longitude: 50.83710976,
latitudeDelta: 0.0040,
longitudeDelta: 0.0040,
}}
provider={this.props.provider}
onPress={(e) => this.onMapPress(e)}
>
{this.state.markers.map(marker => (
<Marker
key={marker.key}
coordinate={marker.coordinate}
/>
))}
</MapView>
Upvotes: 0
Views: 252
Reputation: 2283
Because, when you first-time press that button to execute this function
SaveAddress=()=>{console.log(JSON.stringify(this.state.markers[0].coordinate.latitude);}
The state is empty so you don't get any value. On your first press, it just starts to save the state and start to render. But on your second press, rendering is complete and the states became set then you got the value. You can do instead
import React, { Component } from 'react';
import { View, Text, TouchableOpacity, WebView, StyleSheet,KeyboardAvoidingView, ActivityIndicator,Platform,TextInput,Dimensions} from 'react-native'
import MapView, { PROVIDER_GOOGLE, Region,Marker } from 'react-native-maps';
export default class App extends React.Component {
constructor(props){
super(props);
this.state={
markers: [
{
coordinate: { latitude: 28.95761453,
longitude: 50.83710976,
},
key: 0,
},
],
}
}
onMapPress(e) {
this.setState({
markers: [
{
coordinate: e.nativeEvent.coordinate,
key: 0,
},
],
});
}
SaveAddress=()=>{
console.log(JSON.stringify(this.state.markers[0].coordinate.latitude))
}
render() {
return (
<View style={{flex:1}}>
<MapView
style={[styles.map]}
initialRegion={{
latitude: 28.95761453,
longitude: 50.83710976,
latitudeDelta: 0.0040,
longitudeDelta: 0.0040,
}}
// onMapReady={this.onMapReady}
provider={ PROVIDER_GOOGLE}
onPress={(e) => this.onMapPress(e)}
>
{this.state.markers.map(marker => (
<Marker
key={marker.key}
coordinate={marker.coordinate}
/>
))}
</MapView>
<TouchableOpacity onPress={()=>this.SaveAddress()}>
<Text>Save</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
map: {
...StyleSheet.absoluteFillObject,
},
});
Upvotes: 1