def find_close_parks(origin, time, routing, parks):
"""Create a dictionary with park objects corresponding to a distance radius heuristic.
Use Vincenty's solution to the inverse geodetic problem to find straight-line
distance from the origin to each park location and determine whether the
distance is within the bounding box heuristic.
"""
close_parks = {}
for park in parks:
dist = vincenty((origin.latitude, origin.longitude),
(park.latitude, park.longitude)).miles
if dist < find_appx_dist(time, routing):
# close_parks[park.name] = park
close_parks[(dist, park.name)] = park
return close_parks
python类vincenty()的实例源码
def buffer(self, buffer_m):
"""
Takes a buffer distance in meters and extends the bounds by that
distance. Uses the average latitude of the current bounds to calculate
new latitude bounds. Over extremely large latitude bounds, the results
will lose accuracy.
"""
calculator = vincenty(meters=buffer_m)
ave_lng = (self.w_lng + self.e_lng) / 2
ave_lat = (self.n_lat + self.s_lat) / 2
self.n_lat = calculator.destination((self.n_lat, ave_lng), 0).latitude
self.s_lat = calculator.destination((self.s_lat, ave_lng), 180).latitude
self.e_lng = calculator.destination((ave_lat, self.e_lng), 90).longitude
self.w_lng = calculator.destination((ave_lat, self.w_lng), 270).longitude
return self
def convert_circle_to_rectangle(point, radius_m):
"""
(tuple(int or float, int or float), int or float) -> GEOSGeometry Polygon
Takes a circle as a (lng, lat) tuple and a radius in meters. Returns the
smallest rectangular Polygon that encompasses the circle.
"""
# reverse the lng, lat order to convert to geopy Point format
center = reverse_coordinate_order(point)
# create a geopy coordinate calculator for the given distance
calculator = vincenty(meters=radius_m)
# calculate points at the given distance in the cardinal directions
n_pt = calculator.destination(point=center, bearing=0)
s_pt = calculator.destination(point=center, bearing=180)
e_pt = calculator.destination(point=center, bearing=90)
w_pt = calculator.destination(point=center, bearing=270)
bounds = Bounds(n_lat=n_pt.latitude, s_lat=s_pt.latitude,
e_lng=e_pt.longitude, w_lng=w_pt.longitude)
return bounds.bounding_box
def distance(self, lat1, lng1, lat2, lng2):
"""
This method calculate the distance of two cordinates in miles.
Parameters:
lat1: float (latitute)
lng1: float (longitude)
lat2: float (latitude)
lng2: float (longitude)
Return:
d: float
"""
add1 = (lat1,lng1)
add2 = (lat2,lng2)
d = vincenty(add1, add2).miles
return d
def __calculate_sum_distances(self, X):
coordinate_list = X[['latitude', 'longitude']].values
edges = list(combinations(coordinate_list, 2))
return np.sum([distance(edge[0][1:], edge[1][1:]).km for edge in edges])
def geodist(point1, point2):
# print(point1, point2, vincenty((point1[1],point1[0]),(point2[1],point2[0])).meters,np.sqrt((lonconst*(point1[0]-point2[0]))**2+(latconst*(point1[1]-point2[1]))**2))
return(np.sqrt((lonconst*(point1[0]-point2[0]))**2+(latconst*(point1[1]-point2[1]))**2)) #180dg difference equivalent to 80m difference
def process(self, tup):
top_x, location_a = tup.values
a_name , a_lat, a_lon, a_rad = location_a
for b_name, b_coord in top_x:
# get from datastore
distance_km = vincenty((a_lat,a_lon), b_coord).meters /1000
b_rad = self._redis.get(REDIS_LOCATION_DATA_KEY % b_name)
if distance_km < min(a_rad, b_rad):
# self.emit([a_name, b_name], stream="output")
self.log('Match found: %s, %s' % (a_name, b_name))
def findTopDistResults(self):
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="spd", # your username
passwd="meraPassword", # your password
db="topik") # name of the data base
curP = db.cursor()
curT = db.cursor()
curPop = db.cursor()
curP.execute("SELECT * from posts;")
curT.execute("CREATE OR REPLACE TABLE temp_distScore(score DOUBLE,uid NVARCHAR(20),pid NVARCHAR(20) PRIMARY KEY) engine=InnoDB;")
db.commit()
rows = curP.fetchall()
for row in rows:
q_l = (self.lat,self.lng)
row_l = (row[3],row[4])
dist = vincenty(q_l, row_l).miles
if(self.r >= dist):
distScore = float(self.r-dist)/self.r
else:
distScore = 0
curT.execute("INSERT INTO temp_distScore (score,uid,pid) VALUES (%s,%s,%s)",(distScore,row[1],row[5]))
db.commit()
curP.close()
curT.close()
db.close()
return
def callback(self, location: LocationEvent) -> None:
current_coordonates = (location.get_latitude(), location.get_longitude())
distance_from_home = vincenty(self.__home_coordonates, current_coordonates).km
phone_is_home = distance_from_home < self.HOME_RADIUS
sensor = Sensor('phoneIsHome', Sensor.SensorType.PHONE_IS_HOME.value, False, phone_is_home)
self.__sensors_repo.set_sensor(sensor)
def get_distance(self):
position = Pokeconfig.get().position
distance = vincenty(position, self.position)
if Pokeconfig.get().distance_unit == 'meters':
return distance.meters
else:
return distance.miles
Google_Place_Nearby_Search.py 文件源码
项目:Hanhan_Play_With_Social_Media
作者: hanhanwu
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def calculate_distance(merchant_loc, user_loc):
geolocator = Nominatim()
merchant_lat_lng = [Decimal(l) for l in merchant_loc.split(',')]
al1 = (merchant_lat_lng[0], merchant_lat_lng[1])
location2 = geolocator.geocode(user_loc)
if location2 == None: return None
al2 = (location2.latitude, location2.longitude)
distce = vincenty(al1, al2).miles
return distce
def center_width_m(self):
"""
Returns the width of the bounding box at its center latitude, in meters.
"""
ave_lat = (self.n_lat + self.s_lat) / 2
return vincenty((ave_lat, self.w_lng), (ave_lat, self.e_lng)).meters
def height_m(self):
"""
Returns the height of the bounding box in meters.
"""
nw_pt = (self.n_lat, self.w_lng)
sw_pt = (self.s_lat, self.w_lng)
return vincenty(nw_pt, sw_pt).meters
def get_width_at_latitude_m(self, lat):
"""
Returns the width of the bounding box at the given latitude, in meters.
"""
east = (lat, self.e_lng)
west = (lat, self.w_lng)
return vincenty(east, west).meters
def test_center_width(self):
"""
Tests method for finding the average width of the bounding box in meters.
"""
bounds = Bounds(n_lat=50.0, s_lat=0.0, e_lng=25.0, w_lng=0.0)
expected = vincenty((25.0, 0), (25.0, 25.0)).meters
self.assertEqual(bounds.center_width_m, expected)
def test_dist_for_triangle(self):
"""
Tests the function calculate_farthest_dist_km for a triangle.
"""
points = ((0, 10), (0, 20), (20, 15))
target = (0, 15)
actual = shapes.calculate_farthest_dist_km(points, target)
expected = vincenty((15, 20), (15, 0)).kilometers
self.assertEqual(actual, expected)
def test_radius_for_rectangle(self):
"""
Tests the function calculate_polygon_radius_km for a rectangle.
"""
rectangle = Location.objects.get(pk=3)
actual = shapes.calculate_polygon_radius_km(rectangle.geom)
point = shapes.reverse_coordinate_order(rectangle.geom.centroid)
expected = vincenty(point, (0, 1)).kilometers
self.assertEqual(actual, expected)
def test_radius_for_polygon(self):
"""
Tests the function calculate_polygon_radius_km for a nonrectangular
polygon.
"""
polygon = Location.objects.get(pk=7)
actual = shapes.calculate_polygon_radius_km(polygon.geom)
point = shapes.reverse_coordinate_order(polygon.geom.centroid)
expected = vincenty(point, (8, 0)).kilometers
self.assertEqual(actual, expected)
def test_radius_for_rectangle(self):
"""
Test case for a rectangle.
"""
rectangle = Location.objects.get(pk=3)
actual = rectangle.radius_km
expected = vincenty(rectangle.geom.centroid, (0, 1)).kilometers
self.assertTrue(actual, expected)
def test_radius_for_polygon(self):
"""
Test case for a polygon.
"""
polygon = Location.objects.get(pk=4)
actual = polygon.radius_km
point = shapes.reverse_coordinate_order(polygon.geom.centroid)
expected = vincenty(point, (8, 0)).kilometers
self.assertTrue(actual, expected)
def test_radius_for_multipoly(self):
"""
Test case for a multipolygon.
"""
multipolygon = Location.objects.get(pk=8)
actual = multipolygon.radius_km
point = shapes.reverse_coordinate_order(multipolygon.geom.centroid)
expected = vincenty(point, (20, 50)).kilometers
self.assertTrue(actual, expected)
def geodistance( coords1 , coords2 ):
lat1 , lon1 = coords1[ : 2]
lat2 , lon2 = coords2[ : 2]
try: return distance.vincenty( ( lat1 , lon1 ) , ( lat2 , lon2 ) ).meters / 1000.0
except: return distance.great_circle( ( lat1 , lon1 ) , ( lat2 , lon2 ) ).meters / 1000.0
def distance(lat1, lng1, lat2, lng2):
"""
Calculate the distance (miles) between 2 locations given their latitudes and longitudes
"""
add1 = (lat1,lng1)
add2 = (lat2,lng2)
d = vincenty(add1, add2).miles
return d
def distance(self):
"""
Returns:
Distance between two coordinates. Using WGS-84 ellipsoid ,vincenty formulae and geopy to calculate.
"""
return self._distance_km
def calculate(source_coord, target_coord):
"""
Calculate the distance between provided coordinates and the direction from source coordinates to target coordinates.
Returns:
CoordinateRelationship object.
"""
dist = vincenty((source_coord.lat, source_coord.lng), (target_coord.lat, target_coord.lng)).km
deg = CoordinateRelationship._calculate_deg(source_coord, target_coord)
return CoordinateRelationship(dist, deg)
def _ReadAndFilterData(filename, start_date, end_date, pos, distance):
"""Creates a filter function for the CSV reader, and reads csv data.
Args:
filename: The path of the file to read.
start_date: Start date we should begin filtering the data.
end_date: End date we should begin filtering the data.
pos: Location we should be filtering the data for.
distance: Distance in KM for which we include aftershocks.
Returns:
List of dictionaries of ISC data.
"""
def _Filter(x):
"""Filter that we apply to all isc data."""
try:
# Remove the normal problems with the data.
if not _IsRowValid(x): return False
# Make sure the data point is in the date range specified.
if not start_date <= x['date_time'] <= end_date: return False
# Make sure the data point is within the distance specified.
if vincenty((x['lat'], x['lon']), pos) > distance: return False
except ValueError:
# Vincenty doesn't always converge. If it fails to, then default to a
# Great Circle distance.
if great_circle((x['lat'], x['lon']), pos) > distance: return False
return True
return _ReadCsvFile(filename, data_validator=_Filter)
def get_ISS():
api = requests.get("http://api.open-notify.org/iss-now.json")
data = api.json()
iss = (data["iss_position"]["latitude"], data["iss_position"]["longitude"])
home = (40.674974, -73.957325)
dist = vincenty(iss, home).miles
ISS_closeness = map_val(dist, 0.0, 12450.0, -1.0, 1.0)
return -1.0 * ISS_closeness
def hasWikidata( wikidataId, l ):
responsewiki = requests.get("https://www.wikidata.org/w/api.php?action=wbgetentities&ids=" + wikidataId + "&format=json")
datawiki = responsewiki.json()
l['wiki:logs'] = ''
for label in labels:
try:
l['wiki:wikidata'] = wikidataId
wikilabels = datawiki["entities"][wikidataId]["labels"][label]["value"]
l['wiki:label:'+label] = wikilabels
l['wiki:logs'] += label + " Present,"
except:
l['wiki:logs'] += "No " + label + " label,"
try:
l['wiki:label:en'] = datawiki["entities"][wikidataId]["labels"]["en"]["value"]
except:
l['wiki:label:en'] = ""
try:
l['wiki:wikipedia:en'] = datawiki["entities"][wikidataId]["sitelinks"]["enwiki"]["title"]
except:
l['wiki:wikipedia:en'] = ""
try:
latitude = datawiki["entities"][wikidataId]["claims"]["P625"][0]["mainsnak"]["datavalue"]["value"]["latitude"]
longitude = datawiki["entities"][wikidataId]["claims"]["P625"][0]["mainsnak"]["datavalue"]["value"]["longitude"]
geom_geojson = shapely.geometry.shape({"type": "Point", "coordinates": [longitude, latitude]})
d = ast.literal_eval(l['osm:geometry'])
geom_db = shapely.geometry.shape(d)
centroid_geojson = geom_geojson.centroid
centroid_db = geom_db.centroid
distance = vincenty((centroid_geojson.x,centroid_geojson.y),(centroid_db.x, centroid_db.y)).km
l['wiki:Distance'] = distance
except Exception as e:
l['wiki:Distance'] = ""
return l
def check_median_absolute_deviation(data_points, median):
"""Calculate Median Absolute Deviation of a set of points."""
distances = []
for i in range(0, len(data_points)):
try:
distances.append(vincenty(median, data_points[i]).kilometers)
except ValueError:
# Vincenty doesn't always converge so fall back on great circle distance which is less accurate but always converges
distances.append(great_circle(median, data_points[i]).kilometers)
return(numpy.median(distances))
def denomsum(test_median, data_points):
"""Provides the denominator of the weiszfeld algorithm."""
temp = 0.0
for i in range(0, len(data_points)):
try:
temp += 1 / vincenty(test_median, data_points[i]).kilometers
except ZeroDivisionError:
continue # filter points that equal the median out (otherwise no convergence)
except ValueError:
# Vincenty doesn't always converge so fall back on great circle distance which is less accurate but always converges
temp += 1 / great_circle(test_median, data_points[i]).kilometers
return temp