Home > Back-end >  Get geographical coordinates in a given square
Get geographical coordinates in a given square

Time:08-02

My task is as follows: knowing the center (starting point), for example - [{'lat': -7.7940023, 'lng': 110.3656535}] and knowing the radius 5km I need to get all the points included in this square in 1 km increments. How do I achieve this?

P.S Using the Haversine formula I can check if a point is in a given square according to the radius

enter image description here

# The haversine formula determines the great-circle distance between two points on a sphere given 
# their longitudes and latitudes. Important in navigation, it is a special case of a more general 
# formula in spherical trigonometry, the law of haversines, that relates the sides and angles of 
# spherical triangles. 

lat1 = df['lat']
lon1 = df['lng']
lat2 = df['latitude_deg']
lon2 = df['longitude_deg']

from math import radians, cos, sin, asin, sqrt
def haversine(lat1, lon1, lat2, lon2):
    """
    Calculate the great circle distance between two points 
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians 
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
    # haversine formula 
    dlon = lon2 - lon1 
    dlat = lat2 - lat1 
    a = sin(dlat/2)**2   cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a)) 
    # Radius of earth in kilometers is 6371
    km = 6371* c
    return km

# Creating a new column to generate the output by passing lat long information to Haversine Equation
df['distance'] = [haversine(df.lat[i],df.lng[i],df.latitude_deg[i],df.longitude_deg[i]) for i in range(len(df))]
df['distance'] = df['distance'].round(decimals=3)

# Printing the data table 
df.sort_values(by=['distance'], inplace=True)
df.head()

enter image description here

# Let's sort by our newly created field, which identifies airport lat/lonn coordinates within .5 places of 
# a city's lat/long coordinates

# Create a mask where our conditions are met (difference between lat and latitude_deg < 0.1 and 
# difference between lng and longitude_deg < 0.1)
mask = ((abs(df["lat"] - df["latitude_deg"]) < 0.1) & (abs(df["lng"] - df["longitude_deg"]) < 0.1))

# Fill the type column
df.loc[mask, 'Type'] = "Airport"

df.sort_values(by=['Type'], inplace=True)
df.head()

enter image description here

More details here.

https://github.com/ASH-WICUS/Notebooks/blob/master/Haversine Distance - Airport or Not.ipynb

  • Related