本文整理汇总了Python中geopy.distance.distance方法的典型用法代码示例。如果您正苦于以下问题:Python distance.distance方法的具体用法?Python distance.distance怎么用?Python distance.distance使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类geopy.distance
的用法示例。
在下文中一共展示了distance.distance方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: nearby_now
# 需要导入模块: from geopy import distance [as 别名]
# 或者: from geopy.distance import distance [as 别名]
def nearby_now(self) -> List[Tuple[str, Pos, float]]:
now = datetime.utcnow()
t1 = time()
self.last_query_t = t1
lons, lats, alts, errors = self.orbs.get_lonlatalt(now)
t2 = time()
rough_near = np.logical_and(np.abs(lats - self.loc.lat) < 3, np.abs(lons - self.loc.long) < 3)
valid_satpos = list(
zip(self.satnames[~errors][rough_near], lats[rough_near], lons[rough_near], alts[rough_near]))
nearby = [(name, Pos(lat=lat, long=lon), alt) for name, lat, lon, alt in valid_satpos if
distance.distance(self.loc, (lat, lon)).km < 200]
t3 = time()
print("loc:{:.2f}s dist: {:.2f}s tot: {:.2f}s, sats: {:02d}".format(t2 - t1, t3 - t2, t3 - t1, len(nearby)))
if not self.filtered_errors:
print("filtering errors")
self.satnames = self.satnames[~errors]
self.tles = itertools.compress(self.tles, ~errors)
self.create_orbitals()
self.filtered_errors = True
return nearby
示例2: mk_dx_dy_from_geotif_layer
# 需要导入模块: from geopy import distance [as 别名]
# 或者: from geopy.distance import distance [as 别名]
def mk_dx_dy_from_geotif_layer(geotif):
"""
Extracts the change in x and y coordinates from the geotiff file. Presently
only supports WGS-84 files.
"""
ELLIPSOID_MAP = {'WGS84': 'WGS-84'}
ellipsoid = ELLIPSOID_MAP[geotif.grid_coordinates.wkt]
d = distance(ellipsoid=ellipsoid)
dx = geotif.grid_coordinates.x_axis
dy = geotif.grid_coordinates.y_axis
dX = np.zeros((dy.shape[0]-1))
for j in xrange(len(dX)):
dX[j] = d.measure((dy[j+1], dx[1]), (dy[j+1], dx[0])) * 1000 # km2m
dY = np.zeros((dy.shape[0]-1))
for i in xrange(len(dY)):
dY[i] = d.measure((dy[i], 0), (dy[i+1], 0)) * 1000 # km2m
return dX, dY
示例3: _approximate_bbox_area
# 需要导入模块: from geopy import distance [as 别名]
# 或者: from geopy.distance import distance [as 别名]
def _approximate_bbox_area(self):
"""
Calculate the approximate area of the
bounding box in square kilometers.
Returns: numeric area of the bounding box
in km squared.
"""
lat_min, lon_min, lat_max, lon_max = self.bbox
lower_right_point = (lat_min, lon_max)
lower_left_point = (lat_min, lon_min)
upper_left_point = (lat_max, lon_min)
lower_edge = distance.distance(lower_left_point, lower_right_point).km
left_edge = distance.distance(lower_left_point, upper_left_point).km
area = lower_edge * left_edge
if self.logger:
self.logger.info('Approx area of bounding box: {:,.2f} sq. km'.format(area))
return area
示例4: set_google_maps_fields
# 需要导入模块: from geopy import distance [as 别名]
# 或者: from geopy.distance import distance [as 别名]
def set_google_maps_fields(self, latlng=None):
"""
Uses the Google Maps API to set:
- geocoded latlng
- nearest school name + distance
- nearest train station name + distance
"""
client = Client(key=settings.GOOGLE_MAPS_API_SERVER_KEY)
if not latlng:
data = client.geocode(self.address)
if not data:
raise Exception("Unable to resolve the address: '%s'" % address)
latlng = data[0]["geometry"]["location"]
self.point = GEOSGeometry("POINT(%(lng)s %(lat)s)" % latlng)
error = ""
for field in ("school", "train_station"):
try:
place = client.places_nearby(location=latlng, rank_by="distance", type=field)["results"][0]
except IndexError:
continue
except Exception as e:
error = e
continue
setattr(self, "nearest_%s" % field, place["name"])
place_latlng = place["geometry"]["location"]
d = distance((latlng["lat"], latlng["lng"]), (place_latlng["lat"], place_latlng["lng"])).km
setattr(self, "nearest_%s_distance" % field, round(d, 2))
if error:
raise Exception(error)
示例5: closest_led
# 需要导入模块: from geopy import distance [as 别名]
# 或者: from geopy.distance import distance [as 别名]
def closest_led(self, pos: Pos, alt: float) -> Tuple[Pos, int, float]:
level = self._level_from_alt(alt)
closest_led_index = None
closest_led_distance = (2 * self.eq_radius) ** 2
for i, ledpos in enumerate(self.levels_led_poss[level]):
# naive distance calculation, accurate enough for the inter-led distances
d = ((ledpos.long - pos.long) * self.longfactor) ** 2 + (ledpos.lat - pos.lat) ** 2
if d < closest_led_distance:
closest_led_distance = d
closest_led_index = i
closest_led_pos = self.levels_led_poss[level][closest_led_index]
closest_led_index += level * self.level_ledn
return closest_led_pos, closest_led_index, closest_led_distance
示例6: get_latest_measures
# 需要导入模块: from geopy import distance [as 别名]
# 或者: from geopy.distance import distance [as 别名]
def get_latest_measures(self, lat, lon, max_distance, size=50):
"""
If cache is used, latest measures will be fetched and cached with a larger radius.
Arbitrary values are used in that case:
max_distance: 10 km
lat and lon: rounded to 1 decimal
This ensures that all measure points are covered by at least 1 cache key, with a tolerance of 2km.
At the equator: distance((0,0),(0.05,0.05)) is 7.9 km
"""
if not self.use_cache:
return self._fetch_latest_measures(lat, lon, max_distance=max_distance, size=size)
assert max_distance <= 2000, "Cached recycling data cannot be retrieved for radius > 2km"
rounded_lat, rounded_lon = f"{lat:.1f}", f"{lon:.1f}"
key = f"recycling_latest_measures_{rounded_lat}_{rounded_lon}"
results = RedisWrapper.cache_it(key, self._fetch_latest_measures, expire=self.cache_expire)(
rounded_lat, rounded_lon, max_distance=10_000, size=10_000
)
if not results:
return []
def get_distance_of_result(r):
measure_geoloc = r["_source"]["metadata"]["location"]["geolocation"]
return distance((lat, lon), (measure_geoloc["lat"], measure_geoloc["lon"])).meters
return list(islice((r for r in results if get_distance_of_result(r) < max_distance), size))
示例7: can_find_home_match
# 需要导入模块: from geopy import distance [as 别名]
# 或者: from geopy.distance import distance [as 别名]
def can_find_home_match(cur_locs, locations, next_index, n):
"""
Searches the list of locations to see if some combination of locations
starting at next_index can be added to the locations currently in
cur_locs that satisfy the constraint that all locations in cur_locs
must be at most 15km from each other. If 5 such points are found,
return success
"""
# The next location to test
loc2 = locations[next_index]
# Check that the next point that could be added (at next_index) would
# satisfy the distance requirement with the current location group
for loc1 in cur_locs:
if get_distance(loc1, loc2) > 15:
return False
# Push on the next location, to see if we can meet the requirements
# while it is a member of the group
cur_locs.append(locations[next_index])
# If we have 5 locations that are all within 15km, return success!
if len(cur_locs) == 5:
return True
# Search the remaining locations to see if some combination can satisfy
# the requirements when this new location is added to the group
for j in range(next_index+1, n):
if can_find_home_match(cur_locs, locations, j, n):
return True
# Remove the last item added since no match could be found when it is a
# member of the current location group
cur_locs.pop()
return False
示例8: get_distance
# 需要导入模块: from geopy import distance [as 别名]
# 或者: from geopy.distance import distance [as 别名]
def get_distance(p1, p2):
"""
Computes the distance between the two latitude-longitude Points using
Vincenty's Formula
"""
return distance.distance(p1, p2).kilometers
示例9: parse_sample_extensions
# 需要导入模块: from geopy import distance [as 别名]
# 或者: from geopy.distance import distance [as 别名]
def parse_sample_extensions(sample, track_point):
if hasattr(track_point, 'extensions'):
for extension in track_point.extensions.iterchildren():
if extension.tag == GPX_NAMESPACE_TRACKPOINTEXTENSION_V1 + GPX_EXTENSION_TRACKPOINTEXTENSION:
if hasattr(extension, GPX_EXTENSION_TRACKPOINTEXTENSION_HEARTRATE):
sample.hr = float(extension.hr) / 60.0 # BPM
for namespace in GPX_NAMESPACES.values():
if extension.tag.startswith(namespace):
tag = extension.tag.replace(namespace, '')
text = extension.text
if tag == GPX_EXTENSION_GPX_V1_TEMP:
sample.temperature = float(text) + 273.15 # Kelvin
elif tag == GPX_EXTENSION_GPX_V1_DISTANCE:
sample.distance = float(text)
elif tag == GPX_EXTENSION_GPX_V1_ALTITUDE:
sample.gps_altitude = float(text)
sample.altitude = int(round(sample.gps_altitude))
elif tag == GPX_EXTENSION_GPX_V1_ENERGY:
sample.energy_consumption = float(text)
elif tag == GPX_EXTENSION_GPX_V1_SEALEVELPRESSURE:
sample.sea_level_pressure = float(text)
elif tag == GPX_EXTENSION_GPX_V1_SPEED:
sample.speed = float(text)
elif tag == GPX_EXTENSION_GPX_V1_VSPEED:
sample.vertical_speed = float(text)
break
示例10: insert_pause
# 需要导入模块: from geopy import distance [as 别名]
# 或者: from geopy.distance import distance [as 别名]
def insert_pause(samples, insert_pause_idx, move, pause_type):
if (insert_pause_idx <= 0):
return
stop_sample = samples[insert_pause_idx - 1]
start_sample = samples[insert_pause_idx]
pause_duration = start_sample.time - stop_sample.time
pause_distance = distance((radian_to_degree(stop_sample.latitude), radian_to_degree(stop_sample.longitude)),
(radian_to_degree(start_sample.latitude), radian_to_degree(start_sample.longitude))).meters
# Introduce start of pause sample
pause_sample = Sample()
pause_sample.move = move
pause_sample.utc = stop_sample.utc
pause_sample.time = stop_sample.time
stop_sample.utc -= timedelta(microseconds=1) # Cut off 1ms from last recorded sample in order to introduce the new pause sample and keep time order
stop_sample.time -= timedelta(microseconds=1)
pause_sample.events = {"pause": {"state": "True",
"type": str(pause_type),
"duration": str(pause_duration),
"distance": str(pause_distance),
}}
samples.insert(insert_pause_idx, pause_sample) # Duplicate last element
# Introduce end of pause sample
pause_sample = Sample()
pause_sample.move = move
pause_sample.utc = start_sample.utc
pause_sample.time = start_sample.time
start_sample.utc += timedelta(microseconds=1) # Add 1ms to the first recorded sample in order to introduce the new pause sample and keep time order
start_sample.time += timedelta(microseconds=1)
pause_sample.events = {"pause": {"state": "False",
"duration": "0",
"distance": "0",
"type": str(pause_type)
}}
samples.insert(insert_pause_idx + 1, pause_sample)
示例11: get_distance
# 需要导入模块: from geopy import distance [as 别名]
# 或者: from geopy.distance import distance [as 别名]
def get_distance(region, src):
"""
Compute within-region distances from the src pixels.
Parameters
----------
region : np.ndarray(shape=(m, n), dtype=bool)
mask of the region
src : np.ndarray(shape=(m, n), dtype=bool)
mask of the source pixels to compute distances from.
Returns
-------
d : np.ndarray(shape=(m, n), dtype=float)
approximate within-region distance from the nearest src pixel;
(distances outside of the region are arbitrary).
"""
dmax = float(region.size)
d = np.full(region.shape, dmax)
d[src] = 0
for n in range(region.size):
d_orth = minimum_filter(d, footprint=_ORTH2) + 1
d_diag = minimum_filter(d, (3, 3)) + _SQRT2
d_adj = np.minimum(d_orth[region], d_diag[region])
d[region] = np.minimum(d_adj, d[region])
if (d[region] < dmax).all():
break
return d
示例12: analyze_location_2
# 需要导入模块: from geopy import distance [as 别名]
# 或者: from geopy.distance import distance [as 别名]
def analyze_location_2():
aux = defaultdict(lambda: defaultdict(lambda: defaultdict(str)))
locations_from_db = defaultdict(list)
with db.cursor() as cur:
cur.execute('select '
'c1.id, '
'c1.name, '
'c1.latitude, '
'c1.longitude, '
'r.name, '
'c2.name, '
'c2.iso_code '
'from geography.city c1 '
'inner join geography.region r on c1.region_id = r.id '
'inner join geography.country c2 on r.country_id = c2.id')
for c1_id, c1, latitude, longitude, r, c2_name, c2_code in cur:
aux[c2_name][r][c1] = c1_id
locations_from_db[c2_code].append((c1, latitude, longitude))
for location_uuid, location in locations.items():
coordinate = coordinates[location_uuid]
city = cities[location['city']]
city_name = city['name']
region = regions[city['region']]
region_name = region['name']
country = countries[region['country']]
country_code = country['code']
country_name = country['name']
res = aux.get(country_name)
if res is not None:
res = res.get(region_name)
if res is not None:
res = res.get(city_name)
if res is not None:
print('Match: {}'.format(city_name))
continue
min_dist = None
result_name = None
for c1_name, latitude, longitude in locations_from_db[country_code]:
point1 = (float(latitude), float(longitude))
point2 = (float(coordinate['latitude']), float(coordinate['longitude']))
dist = distance(point1, point2).km
if min_dist is None or dist < min_dist:
min_dist = dist
result_name = c1_name
print('Actual: {}, calculated: {}'.format(city_name, result_name))
示例13: _fetch_latest_measures
# 需要导入模块: from geopy import distance [as 别名]
# 或者: from geopy.distance import distance [as 别名]
def _fetch_latest_measures(self, lat, lon, max_distance, size):
self.refresh_token()
query = {
"bool": {
"filter": [
{"range": {"hour": {"gte": f"now-{self.measures_max_age_in_hours}h"}}},
{
"nested": {
"path": "metadata.location",
"query": {
"bool": {
"filter": [
{
"geo_distance": {
"distance": f"{max_distance}m",
"metadata.location.geolocation": {
"lon": lon,
"lat": lat,
},
}
}
]
}
},
}
},
]
}
}
response = self.session.post(
f"{self.base_url}/{self.data_index}/{self.data_collection}/_search",
json={
"query": query,
# keep the latest document for each measuring point
"collapse": {"field": "measuringPointId"},
"sort": {"hour": "desc"},
},
params={"size": size},
timeout=self.request_timeout,
)
response.raise_for_status()
return response.json().get("result", {}).get("hits", [])
示例14: get_geometric_median
# 需要导入模块: from geopy import distance [as 别名]
# 或者: from geopy.distance import distance [as 别名]
def get_geometric_median(coordinates):
"""
Returns the geometric median of the list of locations.
"""
n = len(coordinates)
# The geometric median is only defined for n > 3 points, so just return
# an arbitrary point if we have fewer
if n == 1:
return coordinates[0]
elif n == 2:
return coordinates[random.randint(0, 1)]
min_distance_sum = 10000000
median = None # Point type
# Loop through all the points, finding the point that minimizes the
# geodetic distance to all other points. By construction median will
# always be assigned to some non-None value by the end of the loop.
for i in range(0, n):
p1 = coordinates[i]
dist_sum = 0
for j in range(0, n):
# Skip self-comparison
if i == j:
continue
p2 = coordinates[j]
dist = get_distance(p1, p2)
dist_sum += dist
# Abort early if we already know this isn't the median
if dist_sum > min_distance_sum:
break
if dist_sum < min_distance_sum:
min_distance_sum = dist_sum
median = p1
return median
示例15: calculate_distances
# 需要导入模块: from geopy import distance [as 别名]
# 或者: from geopy.distance import distance [as 别名]
def calculate_distances(model, samples):
total_distance_horizontal = 0.0
total_distance_real = 0.0
total_distance_descent = 0.0
total_distance_ascent = 0.0
total_distance_flat = 0.0
previous_gps_sample = None
current_altitude_sample = None
previous_altitude_sample = None
for sample in samples:
if sample.altitude:
current_altitude_sample = sample
if sample.latitude:
if previous_gps_sample:
distance_horizontal = distance(_sample_to_point(previous_gps_sample), _sample_to_point(sample)).meters
if previous_altitude_sample:
if current_altitude_sample != previous_altitude_sample and distance_horizontal > 0:
total_distance_horizontal += distance_horizontal
hm = current_altitude_sample.altitude - previous_altitude_sample.altitude
distance_real = math.sqrt(distance_horizontal ** 2 + hm ** 2)
if hm > 0:
total_distance_ascent += distance_real
elif hm < 0:
total_distance_descent += distance_real
else:
total_distance_flat += distance_real
total_distance_real += distance_real
previous_gps_sample = sample
previous_altitude_sample = current_altitude_sample
else:
previous_altitude_sample = current_altitude_sample
else:
previous_gps_sample = sample
model['total_distance_horizontal'] = total_distance_horizontal
model['total_distance_ascent'] = total_distance_ascent
model['total_distance_descent'] = total_distance_descent
model['total_distance_flat'] = total_distance_flat
model['total_distance_real'] = total_distance_real