1

I have implemented map in my application. Below is a dummy array geoCord[] I am getting api respons in one array and I am mapping this and diaplaying lar long on maps . No I am trying to calculate the distance between two lat longs, like in array there are 2 values which is displaying on map , so there shoul be one line draw and show the distance between . I have tried something but its not working . Pelase help

// Dynaimc array will come from server , this kind off value will come from api

geoCord:[
0:
center: {latitude: 12.9949, longitude: 77.65311}
coordinate: {latitude: 12.9949, longitude: 77.65311}
description: "Metro"
fillColor: "rgba(230,238,255,0.5)"
key: "90.64801"
radius: 550
strokeColor: "grey"
strokeWidth: 2
title: "Baiyyappanahalli"

1:
center: {latitude: 13.0164, longitude: 77.65855}
coordinate: {latitude: 13.0164, longitude: 77.65855}
description: "Abhigyan"
fillColor: "rgba(230,238,255,0.5)"
key: "90.67495000000001"
radius: 550
strokeColor: "green"
strokeWidth: 4
title: "Home"
]

// Below is my code

import React, { Component } from 'react';
import { ScrollView, View, ImageBackground, Alert, Dimensions, StyleSheet, Image, ToastAndroid, Platform, Linking, StatusBar } from 'react-native';
import BG from '../images/background_600x1024.png';
import _ from 'lodash';
import HeaderComponent from './ui/header';
import { withNavigationFocus } from 'react-navigation';
import GeoFencing from 'react-native-geo-fencing';
import MapView, { Marker, Overlay, Polygon, Circle } from "react-native-maps";
import Geolocation from '@react-native-community/geolocation';
import MapViewDirections from 'react-native-maps-directions';


const deviceHeight = Dimensions.get('window').height;
const deviceWidth = Dimensions.get('window').width;


class GeoFencingg extends Component {
  constructor(props) {
    super(props)
    this.state = {
      isLoading: false,
      title: 'Geo fencing',
      icon: 'settings',
      iconType: 'MaterialCommunityIcons',
      latitude: 0,
      longitute: 0,
      lat: 13.01640,
      lng: 77.65855,
      timestamp: null,
    };
    
  }

  componentDidMount() {
    //-------------------- Start Get current location of user---------//

    Geolocation.getCurrentPosition(
      position => {
        this.setState({
          latitude: position.coords.latitude,
          longitute: position.coords.longitude,
          timestamp: position.timestamp
        });
      },

      error => {
        console.log(error);
      },
      { enableHighAccuracy: false, timeout: 50000 }
    );
  
    polygon = [
      { lat: this.state.latitude, lng: this.state.longitute },
      { lat: this.state.lat, lng: this.state.lng },
      //{ lat: 22.7192, lng: 75.852 },
      { lat: 13.01640, lng: 77.65855 },
      { lat: this.state.latitude, lng: this.state.longitute }
      // last point has to be same as first point
    ];
   
    let point = {
      lat: 13.01640,
      lng: 77.65855
    };

    GeoFencing.containsLocation(point, polygon)
      .then(() => ToastAndroid.show("User is within area", ToastAndroid.SHORT))
      .catch(() =>
        ToastAndroid.show("User is not within area", ToastAndroid.SHORT)
      );
  }



  render() {
    const { navigation,geoCord } = this.props;
    console.log("dataaa", geoCord);

    const origin = {latitude: 12.99490, longitude: 77.65311};
const destination = {latitude: 13.01640, longitude: 77.65855};
var GOOGLE_MAPS_APIKEY= 'https://developers.google.com/maps/documentation/directions/AIzaSyBzUXl0oI-RzOr_dKAJCZ3y2_EJ3asvIzo';
    const { title, icon } = this.state;
    return (
      <ImageBackground source={BG} style={{ width: '100%', height: '100%' }} resizeMode="cover">
        <View>
          <HeaderComponent flag={'header_left_with_title'} navigation={navigation} subtitle={title} subTitleColor={'#67809F'} backButtonColor={'#67809F'} backgroundColor={'#F3F4F9'} />
        </View>
        <View style={{
          flex: 1,
          alignItems: 'center',
          justifyContent: 'center',
          backgroundColor: '#fff'
        }}>
          <MapView
            style={styles.map}
            initialRegion={{
              latitude: this.state.latitude,
              longitude: this.state.longitute,
              latitudeDelta: 0.015 * 5,
              longitudeDelta: 0.0121 * 5
            }}
            showsUserLocation={true}
            followUserLocation={true}
            zoomEnabled={true}
            showsScale={true}
          >
            {/*Circle Draw and set radius */}

            <MapView.Circle
              key={(this.state.latitude + this.state.longitute).toString()}
              center={{
                latitude: this.state.latitude,
                longitude: this.state.longitute
              }}
              radius={650}
              strokeWidth={2}
              strokeColor={"red"}
              fillColor={"rgba(230,238,255,0.5)"}
            // onRegionChangeComplete = { this.onRegionChangeComplete.bind(this) }
            />

          
            {/* Marker Add */}
            <MapView.Marker
              coordinate={{
                latitude: this.state.latitude,
                longitude: this.state.longitute
              }}
              title={"MTN"}
              description={"Nigeria"}

            //image={require("./images/login-logo.png")}
            //pinColor={"gray"}
            />


            {geoCord.map(
                    (data, index) => {
                      return (
            <MapView.Circle
              key={data.key}
              center={data.center}
              radius={data.radius}
              strokeWidth={data.strokeWidth}
              strokeColor={data.strokeColor}
              fillColor={data.fillColor}
            // onRegionChangeComplete = { this.onRegionChangeComplete.bind(this) }
            />
            )
          }
        )}
           {geoCord.map(
                    (data, index) => {
                      return (
            <MapView.Marker
              coordinate={data.coordinate}
              title={data.title}
              description={data.description}

            //image={require("./images/login-logo.png")}
            //pinColor={"gray"}
            />
            )
          }
        )}
        <MapViewDirections
    origin={origin}
    destination={destination}
    apikey="AIzaSyBzUXl0oI-RzOr_dKAJCZ3y2_EJ3asvIzo"
    strokeWidth={50}
    strokeColor="red"
  />

            <View style={{ backgroundColor: 'red', width: 70, height: 70, marginTop: 10, paddingLeft: 10 }}></View>

          </MapView>

        </View>

      </ImageBackground>

    )
  }
}
export default withNavigationFocus(GeoFencingg);

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF"
  },
  map: {
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0
  }
});
Abhigyan Gaurav
  • 1,854
  • 6
  • 28
  • 58

1 Answers1

2

To find the distance between to points when their latitude and longitude are given you can use Haversine distance. Code below I have tried to implement it in js.

function toRadians(degrees) {
  var pi = Math.PI;
  return degrees * (pi / 180);
}
function haversine_distance(origin, destination) {
  [lat1, lon1] = origin;
  [lat2, lon2] = destination;
  radius = 6371; // earth radius in km

  dlat = toRadians(lat2 - lat1);
  dlon = toRadians(lon2 - lon1);
  a =
    Math.sin(dlat / 2) * Math.sin(dlat / 2) +
    Math.cos(toRadians(lat1)) *
      Math.cos(toRadians(lat2)) *
      Math.sin(dlon / 2) *
      Math.sin(dlon / 2);
  c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  d = radius * c;

  return d;
}

Now the function can be called as:

console.log(haversine_distance([27, 85], [25, 87]));

Now to plot the line between two points I see that you are using react-native-maps there may be a way to plot line in that library. Here is what official docs say. This should be easy following this documentation.

Binabh Devkota
  • 339
  • 3
  • 4