def get_bbox(position, radius):
    """
    return (4 float): long west, lat north, long east, lat south
    """
    nw = geodistance(meters=radius * 1.4).destination(
        Point(position[1], position[0]), 225)
    se = geodistance(meters=radius * 1.4).destination(
        Point(position[1], position[0]), 45)
    return nw[1], nw[0], se[1], se[0]
def get_distance(a, b):
    """
    origin (float, float): coordinates longitude, latitude, eg: (-122.7282, 45.5801)
    destination (float, float): coordinates
    return (float): in m
    """
    return geodistance(Point(a[1], a[0]), Point(b[1], b[0])).meters
Exemple #3
0
def find_shortest_distance(needle, haystack, rough=False):
    shortest = [-1, None]

    for index, location in enumerate(haystack):
        if rough:
            # If rough is enabled, get the difference between the coordinates
            # to prevent expensive geodistance calculation
            diff = [
                abs(float(needle[0]) - float(location[0])),
                abs(float(needle[1]) - float(location[1]))
            ]

            # 0.1 is roughly 5 km
            if sum(diff) > 0.1:
                continue

        distance = geodistance(needle, location).km

        if not shortest[1]:
            shortest[1] = distance

        if distance < shortest[1]:
            shortest = (index, distance)

    return shortest
Exemple #4
0
    def get_distance(self, coords):
        valid_indices = self.get_valid_indices(
            np.array(coords[:, 0]).astype(float),
            np.array(coords[:, 1]).astype(float))
        coords = coords[valid_indices]

        dist = 0
        for i in range(len(coords) - 1):
            dist += geodistance(coords[i], coords[i + 1]).km

        return dist
Exemple #5
0
def get_distance(dest, start=None):
    """Gets the distance from the "search_location" to a given location.

    This distance is the point-to-point ellipsoidal (Vincenty) distance.
    This function does not calculate the driving/walking/travel distance.
    The idea is to offer a simple estimate of the shortest distance between 
    two locations.

    Uses the google geocoding API to geocode locations and calculate distances
    (via the awesome 'geopy' library: http://code.google.com/p/geopy/)

    Args: 
        dest: a string containing the target location (destination)
            to where the distance is to be calculated

        start: an *optional* string containing the start location
            from where the distance is to be calculated.
            If not provided, start will default to the value of the
            global variable, 'search_location'

    Returns:
        a floating point number representing the distance between 
        'start' and 'dest'

    Raises:

    Examples: 
        # uses the default value of search_location for 'start':
        my_dist = get_distance('Vishalakshi Mantap, Bangalore')

        # uses 'RMV 2nd Stage' as 'start' 
        # ('search_city' is appended to both start and dest)
        dist2 = get_distance('Jayanagar', 'RMV 2nd Stage')

    To Do:
        See if walking/driving/travel distance can be found and given
        instead of the ellipsoidal surface distance
    """

    try:
        # set default value of 'start' if none provided
        # to 'search_location' : a global var
        if start in [None, ""]:
            start = search_location
        elif search_city not in start.lower():
            start = start + ", " + search_city

        g = geocoders.Google(domain="maps.google.co.in")

        _, start_coords = list(g.geocode(start, exactly_one=False))[0]

        # append 'search_city' to the destination string, if needed
        # ( not all location strings from dealsites contain city name)
        if search_city not in dest.lower():
            dest = dest + ", " + search_city

        _, dest_coords = list(g.geocode(dest, exactly_one=False))[0]

        return geodistance(start_coords, dest_coords).kilometers
    except Exception, e:
        logger.error(str(e))
Exemple #6
0
 def loc_dist_acc(self, p, q):
     return geodistance(p, q).m
Exemple #7
0
def go_get_directions(vertices,
                      edges,
                      all_data,
                      dep_time,
                      logger,
                      init=True,
                      edge_indexes=[]):
    """
        this will sweep over all edges and get directions
        from source to target using the Google Directions API
        - vertices - lat lon info
        - edges
        - all_data: contains json information already fetched
    """
    if init:
        edge_length = np.full(len(edges), None)
        leg_distance = np.full(len(edges), None)
        leg_duration = np.full(len(edges), None)
        leg_start_loc = np.full(len(edges), None)
        leg_end_loc = np.full(len(edges), None)
        steps_distance = np.full(len(edges), None)
        steps_duration = np.full(len(edges), None)
        google_distance = np.full(len(edges), None)
        n_steps = np.full(len(edges), None)

    if len(edge_indexes) == 0:
        edge_indexes = edges.index.values
    for i in edge_indexes:
        if int(i) % 100 == 0:
            print(i)
        orig = edges['s'][i]
        dest = edges['t'][i]
        origin = vertices['coord'][orig]
        destination = vertices['coord'][dest]
        edge_length[i] = geodistance(origin, destination).m
        logger.info('edge {:} - origin = {:}, destination = {:}'.format(
            i, origin, destination))
        logger.info('edge {:} - length = {:} meters (geopy)'.format(
            i, edge_length[i]))

        key = str(i)
        if key in all_data:
            data = all_data[key]
        else:
            print('feching', key)
            data = get_directions(origin, destination, dep_time)
            all_data[key] = data
        # --- PARSING data ------------------------------------------
        n_routes = len(data['routes'])
        if n_routes == 0:
            logger.warning("# NO ROUTES TO DESTINATION")
        else:
            # legs ---------------------------------
            n_legs = len(data['routes'][0]['legs'])
            assert n_legs > 0
            leg = data['routes'][0]['legs'][0]

            if 'duration_in_traffic' in leg:
                leg_duration[i] = leg['duration_in_traffic']['value']
            elif 'duration' in leg:
                leg_duration[i] = leg['duration']['value']

            if 'distance' in leg:
                leg_distance[i] = leg['distance']['value']

            if 'start_location' in leg:
                leg_start_loc[i] = (leg['start_location']['lat'],
                                    leg['start_location']['lng'])
                leg_end_loc[i] = (leg['end_location']['lat'],
                                  leg['end_location']['lng'])

            logger.info('leg')
            logger.info('\t start loc = {:}, end loc = {:}'.format(
                leg_start_loc[i], leg_end_loc[i]))
            logger.info('\t distance = {:} meters'.format(leg_distance[i]))
            logger.info('\t duration = {:} sec'.format(leg_duration[i]))

            # steps -----------------------------------
            if 'steps' in leg:
                n_steps[i] = len(leg['steps'])
                logger.info('\t number of steps = {:}'.format(n_steps[i]))
                if n_steps[i] > 1:
                    logger.warning('\t more than one step for this edge')
                steps_duration[i] = 0.0
                steps_distance[i] = 0.0
                google_distance[i] = 0.0
                for _, step in enumerate(leg['steps']):
                    duration = step['duration']['value']
                    distance = step['distance']['value']
                    logger.debug(
                        '\t\t step {:}:  duration = {:} sec, distance = {:} meters'
                        .format(i, duration, distance))

                    step_start_loc = (step['start_location']['lat'],
                                      step['start_location']['lng'])
                    step_end_loc = (step['end_location']['lat'],
                                    step['end_location']['lng'])
                    google_distance[i] += geodistance(step_start_loc,
                                                      step_end_loc).m
                    steps_duration[i] += duration
                    steps_distance[i] += distance

                logger.info('\t total leg duration = {:} sec'.format(
                    steps_duration[i]))
                logger.info('\t total leg distance {:} meters'.format(
                    steps_distance[i]))
                logger.info(
                    '\t total computed distance = {:} meters (geopy)'.format(
                        google_distance[i]))
                logger.info('---------------- end leg')

    dta = {
        'edge_length': edge_length,
        'leg_distance': leg_distance,
        'leg_duration': leg_duration,
        'leg_start_loc': leg_start_loc,
        'leg_end_loc': leg_end_loc,
        'steps_distance': steps_distance,
        'steps_duration': steps_duration,
        'google_distance': google_distance,
        'n_steps': n_steps
    }
    df = pd.DataFrame(data=dta)
    print('finished')
    return all_data, df