I am building and Android app with React native, using Expo. My users will write adresses and I have to find the coordinates of this in order to display a route on a map.
As I saw it works correctly, but not on the first attempt. When I press the button which navigates to the MapScreen, the correct values are generated, but not rendered on screen.
When I make back and try again without any change, it will render.
Why only on second attempt renders the data? Is the Geocoder function called after the render or what is the problem?
import MapView, { Marker } from "react-native-maps";
import MapViewDirections from "react-native-maps-directions";
import React, {useState, useEffect} from 'react';
import * as Location from 'expo-location'
import {Alert, StatusBar, StyleSheet, Text, View} from 'react-native';
import { mapStyles } from '../Styles';
import Geocoder from 'react-native-geocoding';
var distance = 0;
var originDir = {
longitude : null,
latitude : null,
};
var destinationDir = {
longitude: null,
latitude: null,
};
const GOOGLE_MAPS_APIKEY = '';
Geocoder.init(GOOGLE_MAPS_APIKEY);
function getDistance(param){
distance = param;
}
const showMapScreen = ({route, navigation}) => {
const {origin} = route.params;
Geocoder.from(origin)
.then(json => {
var destination = json.results[0].geometry.location;
destinationDir.longitude = destination.lng;
destinationDir.latitude = destination.lat;
})
.catch(error => console.log(error));
const [location, setLocation] = useState(null);
const [errorMsg, setErrorMsg] = useState(null);
useEffect(() => {
(async () => {
var { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission to access location was denied');
return;
}
var location = await Location.getCurrentPositionAsync({});
setLocation(location);
originDir.longitude = location.coords.longitude;
originDir.latitude = location.coords.latitude;
})();
}, []);
return (
<View style={mapStyles.container}>
<MapView style={[StyleSheet.absoluteFillObject, {elevation:-1, position:"absolute"}]} initialRegion={{longitude : originDir.longitude, latitude : originDir.latitude, latitudeDelta:0, longitudeDelta:0}} provider={MapView.PROVIDER_GOOGLE}>
<MapViewDirections strokeWidth = {5} strokeColor="blue" lineDashPattern={[1]} origin={originDir} destination={destinationDir} apikey = {GOOGLE_MAPS_APIKEY} onReady={result => {getDistance(result.distance)}}></MapViewDirections>
<Text style={{top:100, elevation:1, position:"absolute", width:70, height:40, fontSize:20}}>Distance: {distance} km</Text>
</MapView>
<StatusBar style="auto"></StatusBar>
</View>);
}
export {showMapScreen};
Thanks for the response!