Pick up data in pairs in lines in sequence

0

I'm reading a csv worksheet with pandas through pd.read_csv() .

The worksheet contains vehicle location data at any time. For example:

  

Location 1: Latitude a, Longitude a   Location 2: Latitude b, Longitude b
  Location 3: Latitude c, Longitude c
  Location 4: Latitude d, Longitude d
  Location 5: Latitude e, Longitude and
  Location 6: Latitude f, Longitude f

I need to show a distance history by calculating through the Maps API via:

  

Location 1 to 2: xKM
  Location 2 to 3: yKM
   etc.

I tried to do using a apply() within a for , but it did not work.

    
asked by anonymous 11.01.2018 / 15:19

1 answer

0

You can use the Haversine Formula to calculate the distance between two geographic coordinates of your samples:

Hereisanexample(tested)ofhowtosolveyourproblem:

frommathimportradians,cos,sin,asin,sqrt#FormuladeHaversinedefhaversine(latA,lonA,latB,lonB):#RaiodaTerraemMetrosr=6371000#Convertecoordenadasdegrauspararadianoslon1,lat1,lon2,lat2=map(radians,[lonA,latA,lonB,latB])#FormuladeHaversinedlon=lon2-lon1dlat=lat2-lat1hav=sin(dlat/2)**2+cos(lat1)*cos(lat2)*sin(dlon/2)**2d=2*r*asin(sqrt(hav))returnddist=0;lat0=0;lon0=0;withopen("path.csv") as arq:

    for i, amostra in enumerate(arq):

        lat,lon = amostra.strip('\n').split(',')
        lat, lon = float(lat), float(lon)

        if( i > 0 ):
            dist = haversine( lat, lon, lat0, lon0 );
            print( "[Amostra %d] Latitude: %f, Longitude: %f, Distancia: %f Metros" % (i, lat, lon, dist ) )
        else:
            print( "[Amostra %d] Latitude: %f, Longitude: %f" % (i, lat, lon ) )

        lat0 = lat;
        lon0 = lon;

Inbound CSV file ( path.csv ):

-23.55172772,-46.63113769
-23.54896501,-46.64119576
-23.55247579,-46.63805426
-23.54635555,-46.63022746
-23.55371538,-46.63583097
-23.55013902,-46.62514466
-23.54576266,-46.64009231
-23.55461708,-46.64011483
-23.54577566,-46.63642792
-23.54339516,-46.6348212

Map coordinates:

Output:

[Amostra 0] Latitude: -23.551728, Longitude: -46.631138
[Amostra 1] Latitude: -23.548965, Longitude: -46.641196, Distancia: 1070.287937 Metros
[Amostra 2] Latitude: -23.552476, Longitude: -46.638054, Distancia: 504.915839 Metros
[Amostra 3] Latitude: -23.546356, Longitude: -46.630227, Distancia: 1048.641060 Metros
[Amostra 4] Latitude: -23.553715, Longitude: -46.635831, Distancia: 997.994340 Metros
[Amostra 5] Latitude: -23.550139, Longitude: -46.625145, Distancia: 1159.600298 Metros
[Amostra 6] Latitude: -23.545763, Longitude: -46.640092, Distancia: 1599.514940 Metros
[Amostra 7] Latitude: -23.554617, Longitude: -46.640115, Distancia: 984.569258 Metros
[Amostra 8] Latitude: -23.545776, Longitude: -46.636428, Distancia: 1052.505353 Metros
[Amostra 9] Latitude: -23.543395, Longitude: -46.634821, Distancia: 311.274120 Metros
    
11.01.2018 / 17:11