Rodrigo V
Rodrigo V

Reputation: 514

How to get the length in km of a polyline from react- native-maps?

So i´ve created a map, with a polyline inside of it:

import React from 'react';
import MapView, {Polyline} from 'react-native-maps';

function TrackDetailScreen({navigation}) {

return (
    <>
        <MapView    
            initialRegion={
                { 
                    [{latitude: 23,longitude: 83 },{latitude: 25,longitude: 86 }, ],
                    latitudeDelta: 0.01,
                    longitudeDelta: 0.01,
                  


                }
            }
            > 
            <Polyline  strokeColor='#fc5e13'
           strokeWidth={5} coordinates={track.locations.map(loc => loc.coords)}/>
        </MapView>
    </>
)
}

export default TrackDetailScreen;

Now I want to figure out the distance of the polyline i´ve just built.

How can I tackle that?

Upvotes: 1

Views: 1368

Answers (1)

gbalduzzi
gbalduzzi

Reputation: 10176

The proper way to calculate the distance between two points given their coordinates is to use the haversine formula, because you must consider the earth curvature.

function haversine(coords1, coords2) {
  const R = 6371e3; // metres
  const φ1 = coords1.lat * Math.PI/180; // φ, λ in radians
  const φ2 = coords2.lat * Math.PI/180;
  const Δφ = (coords2.lat-coords1.lat) * Math.PI/180;
  const Δλ = (coords2.lon-coords1.lon) * Math.PI/180;

  const a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
          Math.cos(φ1) * Math.cos(φ2) *
          Math.sin(Δλ/2) * Math.sin(Δλ/2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

  return R * c; // in metres
}

Full disclosure: I stole this code from here: https://www.movable-type.co.uk/scripts/latlong.html

Once you have this, you can simply iterate over the points of your polyline and incrementally calculate the sum:

let totalDistance = 0
for (let i = 1; i < track.locations.length; i++) {
  totalDistance += haversine(track.locations[i-1].coords, track.locations[i].coords)
}

It's worth noting that for short distances, you can obtain an estimate of the distance with simple geometry, without considering the earth curvature. It should be way faster to calculate and is probably better if your polyline contains a ton of points with a short distance beetwen them.

function distance(coords1, coords2) {
   const latDiffSquared = Math.pow((coords1.lat - coords2.lat), 2)
   const lonDiffSquared = Math.pow((coords1.lon - coords2.lon), 2)
   return Math.sqrt(latDiffSquared + lonDiffSquared)
}

Upvotes: 2

Related Questions