Aashish Sapkota
Aashish Sapkota

Reputation: 59

React Native map data acess

I have a question about react-native MapViewDirection with the expo.

I have my result received from the onReady function inside MapViewDirection.

I want to display the distance and duration field to the user.

 onReady={result => {

              console.log(result)
}}; 

I want to declare I am learning and am using someone else's code to practice. Below is full code:

import React, { Component } from 'react';
import { Dimensions, StyleSheet } from 'react-native';
import MapView from 'react-native-maps';
import MapViewDirections from 'react-native-maps-directions';

const { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 40.3788;
const LONGITUDE = -105.5143;
const LATITUDE_DELTA = 0.0192;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;

const GOOGLE_MAPS_APIKEY = 'AIzaSyAkwAlX2w0S3ba6OxBqr13JGDuYIi5GRZ8';

class Example extends Component {

  constructor(props) {
    super(props);


    this.state = {
      coordinates: [
        {
          latitude:40.3788,
          longitude:-105.5143,
        },

      ],
    };

    this.mapView = null;
  }

  onMapPress = (e) => {
    this.setState({
      coordinates: [
        ...this.state.coordinates,
        e.nativeEvent.coordinate,
      ],
    });
  }

  render() {
    return (
      <MapView
        initialRegion={{
          latitude: LATITUDE,
          longitude: LONGITUDE,
          latitudeDelta: LATITUDE_DELTA,
          longitudeDelta: LONGITUDE_DELTA,
        }}
        style={StyleSheet.absoluteFill}
        ref={c => this.mapView = c}
        onPress={this.onMapPress}
      >
        {this.state.coordinates.map((coordinate, index) =>
          <MapView.Marker key={`coordinate_${index}`} coordinate={coordinate} />
        )}
        {(this.state.coordinates.length >= 2) && (
          <MapViewDirections
            origin={this.state.coordinates[0]}
            waypoints={ (this.state.coordinates.length > 2) ? this.state.coordinates.slice(1, -1): null}
            destination={this.state.coordinates[this.state.coordinates.length-1]}
            apikey={GOOGLE_MAPS_APIKEY}
            strokeWidth={3}
            strokeColor="hotpink"
            optimizeWaypoints={true}
            onStart={(params) => {
              console.log(`Started routing between "${params.origin}" and "${params.destination}"`);
            }}
            onReady={result => {

              console.log(result);

              this.mapView.fitToCoordinates(result.coordinates, {
                edgePadding: {
                  right: (width / 20),
                  bottom: (height / 20),
                  left: (width / 20),
                  top: (height / 20),
                }
              });
            }}
            onError={(errorMessage) => {
              // console.log('GOT AN ERROR');
            }}
          />
        )}
      </MapView>
    );
  }
}

export default Example; 

enter image description here

enter image description here

Upvotes: 1

Views: 700

Answers (1)

Kailash
Kailash

Reputation: 877

Using the below given code you can get the distance between two locations using there latitude & longitude. We are using google distance matrix api here to get distance.

  getDistanceOneToOne(lat1, lng1, lat2, lng2) 
  {
    const Location1Str = lat1 + "," + lng1;
    const Location2Str = lat2 + "," + lng2;
    let GOOGLE_API_KEY = "API_KEY"
    let ApiURL = "https://maps.googleapis.com/maps/api/distancematrix/json?"

    let params = `origins=${Location1Str}&destinations=${Location2Str}&key=${GOOGLE_API_KEY}`; // you need to get a key
    let finalApiURL = `${ApiURL}${encodeURI(params)}`;

    this.getDistance(finalApiURL).then((getDistance) => {
      console.log('Distance charges',getDistance);

      if (getDistance.status == "OK") 
      {

          let value = getDistance.rows[0].elements[0].distance.text; //Distance 
          let time = getDistance.rows[0].elements[0].duration.value; //time
      }    
  });
  }

    getDistance = (url) => {
        return this.getDistanceCall(url)
    }

    getDistanceCall = (url) => {

        return fetch(url, {
            method: 'GET',
        })
            .then((response) => { return response.json(); })
            .catch((error) => {
                return error;
            });
    }

Upvotes: 1

Related Questions