Python haversine geofence checker function only checking first in list

29 Views Asked by At

I have a pandas dataframe, df_phys, containing GPS position data.

I want to extend this dataframe with two columns, GeofenceStatus and GeofenceLocation. This should be done by providing a list of geofence coordinates as below:

geofences = [
("XYZ", (57.17091382060343, 9.214415698467825), 0.2),
("ABC", (54.45463431728363, 9.445558085614901), 0.2),
]

df_phys["GeofenceStatus"] = df_phys.apply(
            in_geofence, axis=1, geofences=geofences, type="status", null_type=""
        )

df_phys["GeofenceLocation"] = df_phys.apply(
            in_geofence, axis=1, geofences=geofences, type="location", null_type=""
        )

Here, the geofence checker function looks as below:

# geofence checker function
def in_geofence(row, geofences, type, null_type=""):
    from haversine import haversine
    import numpy as np

    for location, center, radius in geofences:
      
        lat1, lon1 = center
        try:
            lat2, lon2 = row["Latitude"], row["Longitude"]
            if np.isnan(lat2) == False:
                distance = haversine((lat1, lon1), (lat2, lon2))
                if type == "location":
                    if distance <= radius:
                        return location
                    else: 
                        return ""
                elif type == "status":
                    if distance <= radius:
                        return 1.0
                    else: 
                        return 0.0
            else:
                return null_type
        except:
            return null_type

I have this working as expected for the first entry in the geofences list - but the second entry does not seem to have any effect. My thinking was that since I'm looping through each entry in the geofences list, each entry would be evaluated - but that does not seem to happen.

A single df_phys dataframe may contain periods where the vehicle is both within XYZ and ABC, in which case this should be reflected.

Any idea what I'm missing?

0

There are 0 best solutions below