我们从Python开源项目中,提取了以下39个代码示例,用于说明如何使用geopy.distance.vincenty()。
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
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
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
def numersum(test_median, data_point): """Provides the denominator of the weiszfeld algorithm depending on whether you are adjusting the candidate x or y.""" try: return 1 / vincenty(test_median, data_point).kilometers except ZeroDivisionError: return 0 # 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 return 1 / great_circle(test_median, data_point).kilometers
def objfunc(test_median, data_points): """This function calculates the sum of linear distances from the current candidate median to all points in the data set, as such it is the objective function that we are minimising. """ temp = 0.0 for i in range(0, len(data_points)): try: temp += vincenty(test_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 temp += great_circle(test_median, data_points[i]).kilometers return temp
def MotherShipDistance(): home=(latitude,longitude) fremont_ca = (37.5483, -121.9886) distance=int(vincenty(fremont_ca, home).miles) text="Your car is currently %d %s from the Tesla factory in Fremont California" % (distance*distscale,distunits) return statement(text) # INTENTS THAT SEND COMMANDS TO THE CAR # "Unlock my car for 10 minutes."
def start_recording(self): print("inside gps") self.port.write(b"$PMTK397,0*23F\r\n") self.port.write(b"$PMTK397,0.2*3F\r\n") self.port.write(b"$PMTK220,100*2F\r\n") while self.shutdown: fd = self.port.readline() if fd.startswith(b'$GPRMC'): # print("*******", fd) result = fd.split(b',') if result[2] == b'A': now = time.time() self.activated = True try: lat = int(result[3][:2]) + float(result[3][2:].decode('ascii',errors='ignore'))/60 lon = int(result[5][:3]) + float(result[5][3:].decode('ascii',errors='ignore')) / 60 # if self.long != lon or self.lat != lat: # dist = vincenty((self.lat, self.long),(lat,lon)).meters # speed = dist/ (now - self.last_time) # print("speed from latlong", speed) # for cb in self.callbacks: # cb(speed) self.lat, self.long,self.last_time = lat, lon, now except Exception as oops: print(oops) else: self.activated = False # now = time.time() # dist = vincenty((self.lat, self.long),(lat,lon)).meters / (current[3] - self.latlong[3]) # current[3] = velocity # self.latlong = current # print("latlongg..", self.lat, self.long) if fd.startswith(b'$GPVTG'): if self.activated: print(fd) result = fd.split(b',') try: gps_speed = float(result[7].decode('ascii',errors='ignore')) print("speed from gps", gps_speed) for cb in self.callbacks: cb(gps_speed) except Exception as oops: print(oops) else: # print("ignoring..", fd) pass yield from asyncio.sleep(0.1)
def __init__(self, uuid, geojson, search_preset, user_coordinates, timezone_name): self.uuid = uuid if geojson['geometry']['type'] == "Point": self.osm_meta = ("node", geojson["id"]) self.coordinates = ( geojson["geometry"]["coordinates"][1], geojson["geometry"]["coordinates"][0] ) else: # Should be "LineString". self.osm_meta = ("way", geojson["id"]) self.coordinates = ( geojson["geometry"]["coordinates"][0][1], geojson["geometry"]["coordinates"][0][0] ) self.user_coords = user_coordinates self.search_preset = search_preset self.properties = geojson["properties"] self.default_address = self.get_default_address() self.string_address = '' self.distance = round(distance.vincenty( (user_coordinates[0], user_coordinates[1]), self.coordinates ).m) self.bearing = get_bearing(user_coordinates, self.coordinates) self.direction = deg2dir(self.bearing) oh_field = self.properties.get("opening_hours") self.opening_hours = None lang = get_language().split('-')[0] if lang not in ["fr", "en"]: lang = "en" if oh_field: try: self.opening_hours = humanized_opening_hours.HumanizedOpeningHours( oh_field, lang, tz=pytz.timezone(timezone_name) ) except humanized_opening_hours.HOHError: # TODO : Warn user ? debug_logger.error( "Opening hours - HOHError ; OSM_ID: '{id}' ; opening_hours: '{oh}'".format( id=self.osm_meta[1], oh=oh_field ) ) self.opening_hours = None except Exception as e: # TODO : Warn user ? debug_logger.error( "Opening hours - Error ; Exception: '{exception}' ; OSM_ID: '{id}' ; opening_hours: '{oh}'".format( exception=str(e), id=self.osm_meta[1], oh=oh_field ) ) self.opening_hours = None self.tags = self.get_tags() self.renderable_tags = [t[0] for t in self.tags] return
def compare_coordinates(cls, coords1, coords2, *args, tolerance=None, unit='km', **kwargs): """ Check if a distance between the pairs of coordinates provided is within the specified tolerance. Return True if yes, otherwise return False. Use geopy (https://pypi.python.org/pypi/geopy). Try to use Vincenty formula, if error occurs use Great Circle formula. :param coords1: pair of coordinates - a tuple of two numbers :param coords2: pair of coordinates - a tuple of two numbers :param tolerance: number :param unit: str, one of: 'kilometers', 'km', 'meters', 'm', 'miles', 'mi', 'feet', 'ft', 'nautical', 'nm' :rtype: bool :Example: >>> a, b = (36.1332600, -5.4505100), (35.8893300, -5.3197900) >>> MatchBlock.compare_coordinates(a, b, tolerance=20, unit='mi') True >>> a, b = (36.1332600, -5.4505100), (35.8893300, -5.3197900) >>> MatchBlock.compare_coordinates(a, b, tolerance=1, unit='mi') False """ if tolerance is None: tolerance = cls.coordinates_tolerance units = {'kilometers', 'km', 'meters', 'm', 'miles', 'mi', 'feet', 'ft', 'nautical', 'nm'} unit = unit.strip().lower() if unit not in units: raise ValueError('unsupported unit') try: length = getattr(vincenty(coords1, coords2, *args, **kwargs), unit) except ValueError as e: if 'Vincenty formula failed to converge!' in e.args: warnings.warn( 'vincenty formula failed, using great circle formula') length = getattr(great_circle(coords1, coords2, *args), unit) else: raise return length <= tolerance
def _connector_edges(osm_nodes, transit_nodes, travel_speed_mph=3): """ Generate the connector edges between the osm and transit edges and weight by travel time Parameters ---------- osm_nodes : pandas.DataFrame osm nodes DataFrame transit_nodes : pandas.DataFrame transit nodes DataFrame travel_speed_mph : int, optional travel speed to use to calculate travel time across a distance on a edge. units are in miles per hour (MPH) for pedestrian travel this is assumed to be 3 MPH Returns ------- net_connector_edges : pandas.DataFrame """ start_time = time.time() transit_nodes['nearest_osm_node'] = _nearest_neighbor( osm_nodes[['x', 'y']], transit_nodes[['x', 'y']]) net_connector_edges = [] for transit_node_id, row in transit_nodes.iterrows(): # create new edge between the node in df2 (transit) # and the node in openstreetmap (pedestrian) osm_node_id = int(row['nearest_osm_node']) osm_row = osm_nodes.loc[osm_node_id] distance = vincenty((row['y'], row['x']), (osm_row['y'], osm_row['x'])).miles time_ped_to_transit = distance / travel_speed_mph * 60 time_transit_to_ped = distance / travel_speed_mph * 60 # save the edge net_type = 'transit to osm' net_connector_edges.append((transit_node_id, osm_node_id, time_transit_to_ped, net_type)) # make the edge bi-directional net_type = 'osm to transit' net_connector_edges.append((osm_node_id, transit_node_id, time_ped_to_transit, net_type)) net_connector_edges = pd.DataFrame(net_connector_edges, columns=["from", "to", "weight", "net_type"]) log( 'Connector edges between the OSM and transit network nodes ' 'successfully completed. Took {:,.2f} seconds'.format( time.time() - start_time)) return net_connector_edges
def factor_polygon_into_circles(polygon, radius_km): """ Takes a GEOSGeomtery Polygon and a radius in kilometers. Returns a list of (lng, lat) tuples representing the centers of circles of the specified radius that together cover the area of the Polygon. """ safety_buffer = 0.01 # small safety buffer for overlap if not isinstance(polygon, Polygon): raise TypeError('object is not a Polygon') if radius_km <= safety_buffer: raise ValueError('radius must be greater than safety buffer') # get the bounds of the polygon with a small safety buffer buffer_dist_m = (radius_km * 1000) * safety_buffer bounds = create_buffered_bounds(polygon, buffer_dist_m) # get the space between circle centers, with a safety margin of 10 meters dist_bw_centers_m = calculate_circle_spacing(radius_km * 1000, overlap_m=10) # create a coordinate calculator for the increment distance calculator = vincenty(meters=dist_bw_centers_m) points = [] # array for collecting the circle centers # position first point so the circle intersects with the sw corner of bounds starting_pt = vincenty(kilometers=radius_km).destination( point=(bounds.s_lat, bounds.w_lng), bearing=45 ) # get the starting latitude lat = starting_pt.latitude # find the number of rows of circles needed to span the height of the polygon rows = int(math.ceil(bounds.height_m / dist_bw_centers_m)) for dummy_row_idx in range(rows): # reset the starting longitude before each west-to-east loop lng = starting_pt.longitude # get the distance between w_lng and e_lng at the current latitude width_m = bounds.get_width_at_latitude_m(lat) # find the number of columns of circles needed to span the width cols = int(math.ceil(width_m / dist_bw_centers_m)) for dummy_col_idx in range(cols): # add current coordinates to point array points.append((lng, lat)) # calculate next point to the east and increment longitude lng = calculator.destination(point=(lat, lng), bearing=90).longitude # calculate next point to the north and increment latitude lat = calculator.destination(point=(lat, lng), bearing=0).latitude return points
def compute_user_median(data_points, num_iter, csvwriter, current_uid): if len(data_points) < LIMIT_POINTS: # Insufficient points for the user - don't record median if OUTPUT_ALL_USERS: csvwriter.writerow([current_uid, None]) else: if SNAP_TO_USER_POINTS: # ensure median is one of the user's points lowest_dev = float("inf") for point in data_points: tmp_abs_dev = objfunc(point, data_points) if tmp_abs_dev < lowest_dev: lowest_dev = tmp_abs_dev test_median = point else: test_median = cand_median(data_points) # Calculate centroid more or less as starting point if objfunc(test_median, data_points) != 0: # points aren't all the same # iterate to find reasonable estimate of median for x in range(0, num_iter): denom = denomsum(test_median, data_points) next_lat = 0.0 next_lon = 0.0 for y in range(0, len(data_points)): next_lat += (data_points[y][0] * numersum(test_median, data_points[y])) / denom next_lon += (data_points[y][1] * numersum(test_median, data_points[y])) / denom prev_median = test_median test_median = (next_lat, next_lon) try: if vincenty(prev_median, test_median).meters < DISTANCE_THRESHOLD: break except: if great_circle(prev_median, test_median).meters < DISTANCE_THRESHOLD: break if x == num_iter - 1: print('{0}: failed to converge. Last change between iterations was {1} meters.'.format(current_uid, great_circle(prev_median, test_median).meters)) # Check if user points are under the limit median absolute deviation if check_median_absolute_deviation(data_points, test_median) <= LIMIT_MAD: csvwriter.writerow([current_uid, (round(test_median[0],6), round(test_median[1],6))]) else: if OUTPUT_ALL_USERS: csvwriter.writerow([current_uid, None])