Python geopy.distance.distance() Examples

The following are 16 code examples of geopy.distance.distance(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module geopy.distance , or try the search function .
Example #1
Source File: main.py    From satellite_tracker with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #2
Source File: utils.py    From pydem with Apache License 2.0 6 votes vote down vote up
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 
Example #3
Source File: NetworkInterface.py    From spatial_access with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #4
Source File: models.py    From property-finder with Apache License 2.0 5 votes vote down vote up
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) 
Example #5
Source File: main.py    From satellite_tracker with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #6
Source File: recycling.py    From idunn with Apache License 2.0 5 votes vote down vote up
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)) 
Example #7
Source File: method.py    From geoinference with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #8
Source File: method.py    From geoinference with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_distance(p1, p2):
    """
    Computes the distance between the two latitude-longitude Points using
    Vincenty's Formula
    """
    return distance.distance(p1, p2).kilometers 
Example #9
Source File: gpx_import.py    From openmoves with MIT License 5 votes vote down vote up
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 
Example #10
Source File: gpx_import.py    From openmoves with MIT License 5 votes vote down vote up
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) 
Example #11
Source File: neo4j-postgres.py    From selene-backend with GNU Affero General Public License v3.0 4 votes vote down vote up
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)) 
Example #12
Source File: recycling.py    From idunn with Apache License 2.0 4 votes vote down vote up
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", []) 
Example #13
Source File: method.py    From geoinference with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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 
Example #14
Source File: openmoves.py    From openmoves with MIT License 4 votes vote down vote up
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 
Example #15
Source File: utils.py    From pydem with Apache License 2.0 4 votes vote down vote up
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 
Example #16
Source File: p2p.py    From spatial_access with GNU General Public License v3.0 4 votes vote down vote up
def _parse_network(self):
        """
        Cleans and generates the city network.
        """

        start_time = time.time()

        edges = self._network_interface.edges

        if self.configs.use_meters:
            edges['edge_weight'] = edges['distance']
        elif self.network_type == 'walk':
            edges['edge_weight'] = edges['distance'] / self.configs._get_walk_speed() \
                                        + self.configs.walk_node_penalty
        elif self.network_type == 'bike':
            edges['edge_weight'] = edges['distance'] / self.configs._get_bike_speed() \
                                        + self.configs.bike_node_penalty
        elif self.network_type == 'drive':
            driving_cost_matrix = self.configs._get_driving_cost_matrix()
            edges = pd.merge(edges, driving_cost_matrix, how='left', left_on='highway', right_index=True)
            edges['unit_cost'].fillna(self.configs._get_default_drive_speed(), inplace=True)
            edges['edge_weight'] = edges['distance'] / edges['unit_cost'] + self.configs.drive_node_penalty

        if self.network_type == 'walk' or self.network_type == 'bike':
            edges['is_bidirectional'] = True
        elif self.network_type == 'drive':
            edges['is_bidirectional'] = edges['oneway'] != "yes"

        simple_node_indeces = self._reduce_node_indeces()

        edges['from_loc'] = edges['from'].map(simple_node_indeces)
        edges['to_loc'] = edges['to'].map(simple_node_indeces)
        edges['edge_weight'] = edges['edge_weight'].astype('int16')

        from_column = list(edges['from_loc'])
        to_column = list(edges['to_loc'])
        edge_weight_column = list(edges['edge_weight'])
        is_bidirectional_column = list(edges['is_bidirectional'])

        self.matrix_interface.add_edges_to_graph(from_column, to_column, edge_weight_column,
                                                 is_bidirectional_column)

        time_delta = time.time() - start_time
        self.logger.debug("Prepared raw network in {:,.2f} seconds".format(time_delta))