react-nativedirections

react native maps directions onReady distance and duration


There was a problem showing the distance in onReady showing slower than render. Would like to show the distance and duration values ​​before displaying the render.

const MyMapView = (props) => {
    return (
        <MapView
            style={{ flex: 1 }}
            region={props.region}
            showsUserLocation={true}
        >
            <Marker coordinate={props.region} />
            <MapViewDirections
                origin={MapOrigin}
                destination={props.region}
                apikey={API_MAP.API}
                strokeWidth={3}
                strokeColor="hotpink"
                onReady={result => {
                    MapData.distance = result.distance
                    MapData.duration = result.duration
                    console.log(`Distance: ${MapData.distance} km`)
                    console.log(`Duration: ${MapData.duration} min.`)
                }}
            />
            <Body>
                <Text>distance : {MapData.distance} km.time : {MapData.duration} min</Text>
            </Body>
        </MapView>
    )
}

After displaying a value, it displays the value in Text before storing it in the const file.


Solution

  • Try to forceUpdate your component.

    class MyMapView extends React.Component {
      render() {
        return (
          <MapView
            style={{ flex: 1 }}
            region={props.region}
            showsUserLocation={true}
          >
            <Marker coordinate={props.region} />
            <MapViewDirections
              origin={MapOrigin}
              destination={props.region}
              apikey={API_MAP.API}
              strokeWidth={3}
              strokeColor="hotpink"
              onReady={result => {
                MapData.distance = result.distance
                MapData.duration = result.duration
                console.log(`Distance: ${MapData.distance} km`)
                console.log(`Duration: ${MapData.duration} min.`)
                this.forceUpdate()
              }}
            />
            <Body>
              <Text>distance : {MapData.distance} km.time : {MapData.duration} min</Text>
            </Body>
          </MapView>
        )
      }
    }