How to use haversine - 10 common examples

To help you get started, we’ve selected a few haversine examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cb-cities / sf_abm / 0_network / scripts / 1_osm2json.py View on Github external
print('example, {}: {}'.format(random_key, all_nodes[random_key]))

    # Make a list of way elements
    all_ways = [w_e for w_e in osm_data if w_e['type']=='way']
    print('it includes {} nodes'.format(len(all_ways)))
    end_nodes_l = [] # list holding all end nodes of the way elements. All will be preserved.
    mid_nodes_l = [] # list holding all mid nodes of the way elements. Some will be discarded as curve nodes.
    ###################### lecture break ############################
    for way in all_ways:
        way_nodes = way['nodes']
        end_nodes_l.append(way_nodes[0])
        end_nodes_l.append(way_nodes[-1])
        mid_nodes_l += way_nodes[1:-1]
        # Use harversine formula to calculate the length between two nodes. Set length as 0.1 if calculated distance is smaller
        # some nodes will be cleaned as they define curves rather than intersections. However, the length between two nodes will contribute to the final total length
        way['length'] = [max(0.1, haversine.haversine(all_nodes[x][0], all_nodes[x][1], all_nodes[y][0], all_nodes[y][1])) for (x,y) in zip(way_nodes, way_nodes[1:])]
        #pprint.pprint(way)
        #sys.exit(0)

    # critieria for filtering out curve nodes, but preserve intersections:
    # 1. all end nodes are preserved
    # 2. nodes are preserved if it appears twice or more in mid_nodes_l + end_nodes_l
    # The final set of nodes is the the union of results from the above two criteria
    # Find duplicates: https://stackoverflow.com/a/9835819
    all_nodes_l = end_nodes_l + mid_nodes_l # all nodes with duplicates
    seen = set()
    dupes = set()
    for n in all_nodes_l:
        if n not in seen:
            seen.add(n)
        else:
            dupes.add(n)
github Dungyichao / Electric-Vehicle-Route-Planning-on-Google-Map-Reinforcement-Learning / Environment.py View on Github external
end_lng = self.end_position[1]
        east = start_lng if start_lng > end_lng else end_lng
        west = start_lng if start_lng < end_lng else end_lng
        north = start_lat if start_lat > end_lat else end_lat
        south = start_lat if start_lat < end_lat else end_lat
        a = (north, west)
        b = (south, west)
        self.stridebounda = a
        self.strideboundb = b
        lat = position[0]
        #lng = position[1]
        right = (lat, east)
        left = (lat, west)
        height = haversine(a, b) # km
        self.envheightkm = height
        wide = haversine(right, left) # km
        self.stride_height = (north - south) / (height * self.length)  # positive   # 500m per stride
        self.stride_wide = (east - west) / (wide * self.length)
        #self.stride_height = (north - south) / (height * 2)  # positive   # 500m per stride
github PokemonGoF / PokemonGo-Bot / pokemongo_bot / walkers / polyline_generator.py View on Github external
def get_total_distance(self, points):
        return ceil(sum([haversine.haversine(*x)*1000 for x in self.walk_steps(points)]))
github PokemonGoF / PokemonGo-Bot / pokemongo_bot / walkers / polyline_generator.py View on Github external
def cached_polyline(origin, destination, speed, google_map_api_key=None):
        '''
        Google API has limits, so we can't generate new Polyline at every tick...
        '''

        # Absolute offset between bot origin and PolyLine get_last_pos() (in meters)
        if PolylineObjectHandler._cache and PolylineObjectHandler._cache.get_last_pos() != (None, None):
            abs_offset = haversine.haversine(tuple(origin), PolylineObjectHandler._cache.get_last_pos())*1000
        else:
            abs_offset = float("inf")
        is_old_cache = lambda : abs_offset < 8 # Consider cache old if we identified an offset more then 8 m
        new_dest_set = lambda : tuple(destination) != PolylineObjectHandler._cache.destination

        if PolylineObjectHandler._run and (not is_old_cache()):
            # bot used to have struggle with making a decision.
            PolylineObjectHandler._instability -= 1
            if PolylineObjectHandler._instability <= 0:
                PolylineObjectHandler._instability = 0
                PolylineObjectHandler._run = False
            pass # use current cache
        elif None == PolylineObjectHandler._cache or is_old_cache() or new_dest_set():
            # no cache, old cache or new destination set by bot, so make new polyline
            PolylineObjectHandler._instability += 2
            if 10 <= PolylineObjectHandler._instability:
github tehp / OpenPoGoBot / polyline / polyline_walker.py View on Github external
def walk(self):
        if not self.is_paused:
            walked_distance = 0.0
            time_passed = time.time()
            remaining_points = []
            time_passed_distance = self.speed * abs(time_passed - self._timestamp - self._paused_total)
            for step in self.walk_steps():
                step_distance = haversine.haversine(*step) * 1000
                if walked_distance + step_distance >= time_passed_distance:
                    if walked_distance > time_passed_distance:
                        percentage_walked = 0.0
                    else:
                        if step_distance == 0.0:
                            percentage_walked = 1.0
                        else:
                            percentage_walked = (time_passed_distance - walked_distance) / step_distance
                    remaining_points += self.calculate_coord(percentage_walked, *step)
                else:
                    percentage_walked = 1.0
                walked_distance += step_distance * percentage_walked
            self.points = remaining_points
            if self.points:
                self.lat, self.long = self.points[0][0], self.points[0][1]
                self.polyline = self.combine_polylines(self.points)
github cb-cities / sf_abm / 4_validation / mtc_travelmodelone / loaded_network_analysis.py View on Github external
mtc_gdf['haversine_length'] = mtc_gdf.apply(lambda x: 
        sum([haversine.haversine(y0, x0, y1, x1) 
            for ((x0, y0), (x1, y1)) in zip(x['geometry'].coords, x['geometry'].coords[1:])]), 
        axis=1)
github ProjectSidewalk / SidewalkWebpage / label_clustering.py View on Github external
        dist_matrix = pdist(np.array(labels[['lat', 'lng']].values), lambda x, y: haversine(x, y))
    else:
github mojodna / marblecutter / bin / get_zoom.py View on Github external
def get_resolution(input):
    with rasterio.Env():
        with rasterio.open(input) as src:
            # grab the lowest resolution dimension
            if src.crs.is_geographic:
                left = (src.bounds[0], (src.bounds[1] + src.bounds[3]) / 2)
                right = (src.bounds[2], (src.bounds[1] + src.bounds[3]) / 2)
                top = ((src.bounds[0] + src.bounds[2]) / 2, src.bounds[3])
                bottom = ((src.bounds[0] + src.bounds[2]) / 2, src.bounds[1])

                return max(
                    haversine(left, right) * 1000 / src.width,
                    haversine(top, bottom) * 1000 / src.height)
            return max((src.bounds.right - src.bounds.left) / src.width,
                       (src.bounds.top - src.bounds.bottom) / src.height)
github jaredquinn / homeassistant-config / custom_components / sensor / new_georss_events.py View on Github external
def calculate_distance_to_coords(self, coordinates):
        """Calculate the distance between HA and the provided coordinates."""
        # Expecting coordinates in format: (lat, lon).
        from haversine import haversine
        distance = haversine(coordinates, self._home_coordinates)
        _LOGGER.debug("Distance from %s to %s: %s km", self._home_coordinates,
                      coordinates, distance)
        return distance
github oasis-open / cti-python-stix2 / stix2 / environment.py View on Github external
def partial_location_distance(lat1, long1, lat2, long2, threshold):
    """Given two coordinates perform a matching based on its distance using the Haversine Formula.

    Args:
        lat1: Latitude value for first coordinate point.
        lat2: Latitude value for second coordinate point.
        long1: Longitude value for first coordinate point.
        long2: Longitude value for second coordinate point.
        threshold (float): A kilometer measurement for the threshold distance between these two points.

    Returns:
        float: Number between 0.0 and 1.0 depending on match.

    """
    from haversine import haversine, Unit
    distance = haversine((lat1, long1), (lat2, long2), unit=Unit.KILOMETERS)
    result = 1 - (distance / threshold)
    logger.debug(
        "--\t\tpartial_location_distance '%s' '%s' threshold: '%s'\tresult: '%s'",
        (lat1, long1), (lat2, long2), threshold, result,
    )
    return result

haversine

Calculate the distance between 2 points on Earth.

MIT
Latest version published 10 months ago

Package Health Score

74 / 100
Full package analysis