Пример #1
0
def hurricane_halfii(roci_, lat, lon):
    for r in xrange(1, len(roci_)):
        for bearing in range(180, 361):
            bearing_angle.append(bearing)
            distance_from.append(r)
            destination = VincentyDistance(kilometers=r).destination(
                Point(lat, lon), bearing)
            lat2, lon2 = destination.latitude, destination.longitude
            latitude_halfii.append(lat2)
            longitude_halfii.append(lon2)
Пример #2
0
def delta_c(latitude, longitude, distance, bearing):
    '''given: lat1, lon1, bearing = bearing in degrees, distance = distance in kilometers.
    The program outputs the change in coordinates by moving a distance and bearing'''
    origin = geopy.Point(latitude, longitude)
    destination = VincentyDistance(kilometers=distance).destination(
        origin, bearing)
    lat2, lon2 = destination.latitude, destination.longitude
    d_lat = lat2 - latitude
    d_lon = lon2 - longitude
    return (d_lat, d_lon)
Пример #3
0
def get_drone_steps(origin, destiny, city):
    geo_point_origin = (origin.lat, origin.lng)
    geo_point_destiny = (destiny.lat, destiny.lng)
    dist = geopy.distance.distance(geo_point_origin, geo_point_destiny).meters
    total_steps = int(dist // HORIZONTAL_SPEED)
    extra_step = dist % HORIZONTAL_SPEED
    bearing = \
        calculate_initial_compass_bearing(geo_point_origin, geo_point_destiny)
    actual_point = Point(origin.lat, origin.lng, origin.alt)
    steps = []
    while actual_point.alt != city.flying_altitude:
        steps.append(
            Point(actual_point.lat, actual_point.lng, actual_point.alt))
        actual_point.alt += VERTICAL_SPEED
        if actual_point.alt >= city.flying_altitude:
            actual_point.alt = city.flying_altitude
            steps.append(
                Point(actual_point.lat, actual_point.lng, actual_point.alt))
    for i in range(total_steps):
        destination = VincentyDistance(meters=HORIZONTAL_SPEED).destination(
            geopy.Point(actual_point.lat, actual_point.lng), bearing)
        actual_point.lat = destination.latitude
        actual_point.lng = destination.longitude
        steps.append(
            Point(actual_point.lat, actual_point.lng, actual_point.alt))
    if extra_step != 0:
        destination = VincentyDistance(meters=extra_step).destination(
            geopy.Point(actual_point.lat, actual_point.lng), bearing)
        actual_point.lat, actual_point.lng = \
            destination.latitude, destination.longitude
        steps.append(
            Point(actual_point.lat, actual_point.lng, actual_point.alt))
    while actual_point.alt != destiny.alt:
        actual_point.alt -= VERTICAL_SPEED
        if actual_point.alt <= destiny.alt:
            actual_point.alt = destiny.alt
            steps.append(
                Point(actual_point.lat, actual_point.lng, actual_point.alt))
        else:
            steps.append(
                Point(actual_point.lat, actual_point.lng, actual_point.alt))
    return steps
Пример #4
0
def geoOffset(loc, bearing, d):
    '''
    loc as GeoPt
    d in km
    bearing in degrees
    Returns GeoPt
    '''
    origin = geopy.Point(loc.lat, loc.lon)
    destination = VincentyDistance(kilometers=d).destination(origin, bearing)
    lat2, lon2 = destination.latitude, destination.longitude
    return db.GeoPt(lat2, lon2)
Пример #5
0
def destination_coordinates(lat1, lon1, bearing_in_degrees,
                            distance_to_travel_in_meters):
    # given: lat1, lon1,  bearing = bearing to travel in degrees, distance_to_travel = distance to travel in meters
    distance_to_travel_in_meters = float(distance_to_travel_in_meters) / 1000
    print distance_to_travel_in_meters
    origin = geopy.Point(lat1, lon1)
    destination = VincentyDistance(
        kilometers=distance_to_travel_in_meters).destination(
            origin, bearing_in_degrees)
    lat2, lon2 = destination.latitude, destination.longitude
    return lat2, lon2
Пример #6
0
def offset_by_meters(x,y,lat,lon):
    if x==y==0:
        return lat,lon
    dist = math.sqrt(x*x+y*y)
    bearing = math.atan2(y,x)

    origin = geopy.Point(lat, lon)
    destination = VincentyDistance(meters=dist).destination(origin, math.degrees(bearing))

    lat2, lon2 = destination.latitude, destination.longitude    
    return lat2,lon2
Пример #7
0
def pierce_point_plot(st, pierce_h5, **kwargs):
    """
   Plot source and reciever on map
   """
    save = kwargs.get('save', False)
    f = h5py.File(
        '/home/samhaug/anaconda2/lib/python2.7/site-packages/seispy' +
        pierce_h5, 'r')
    pierce_array = f['pierce'][...]

    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
    lon_0 = st[0].stats.sac['evlo']
    lat_0 = st[0].stats.sac['evla']
    m = Basemap(llcrnrlon=-90.,llcrnrlat=-20,urcrnrlon=-50.,urcrnrlat=10.,\
               resolution='l',area_thresh=1000.,projection='poly',\
                           lat_0=-0.,lon_0=-70.)
    #m = Basemap(projection='nsper',lon_0=lon_0,lat_0=lat_0,
    #        satellite_height=800*1000.,resolution='l')
    m.drawcoastlines()
    m.drawcountries()
    m.drawparallels(np.arange(-90., 120., 10.))
    meridians = np.arange(180., 360., 10.)
    m.drawmeridians(meridians)
    coord_list = stat_coord(st)
    title = os.getcwd().split('/')
    ax = plt.gca()

    for ii in pierce_array:
        bearing = ii[1]
        origin = geopy.Point(lat_0, lon_0)
        destination = VincentyDistance(
            kilometers=111 * np.degrees(ii[0])).destination(origin, bearing)
        lat = destination[0]
        lon = destination[1]
        x, y = m(lon, lat)
        m.scatter(x, y, 8, marker='o', color='yellow', lw=0)

    try:
        x, y = m(st[0].stats.sac['evlo'], st[0].stats.sac['evla'])
        b = beachball(st[0], xy=(x, y), plot='map', width=0.3e6, alpha=0.5)
        b.set_zorder(2)
        ax.add_collection(b)
    except KeyError:
        print('No focal mechanism found')

    ax.set_title('{} \n Depth (km): {} '.format(title[5],
                                                pierce_h5.split('_')[0]))

    m.bluemarble()
    if save != False:
        plt.savefig(save + '/map.pdf', format='pdf')
    if save == False:
        plt.show()
Пример #8
0
def circle_as_polygon(lat, lon, n=12, distance=Distance(km=1)):
    # this can be done all in degrees because that's what geopy uses!
    points = []
    # build points, loop around circle
    for angle in [360. * i / n for i in range(0, n)]:
        curr = VincentyDistance(kilometers=distance.km) \
               .destination(gpPoint(lat, lon), angle)
        points.append((curr.longitude, curr.latitude))
    # loop back to the first point for the n+1th point in the list
    points.append(points[0])
    return Polygon(tuple(points))
Пример #9
0
    def interpolation_radius(self, lat, lon):
        distance = VincentyDistance()
        d = distance.measure((np.amin(lat), np.amin(lon)),
                             (np.amax(lat), np.amax(lon))) * 1000 / 8.0

        if d == 0:
            d = 50000

        d = np.clip(d, 20000, 50000)

        return d
def calculate_ball_parks(dropoff_latitude, dropoff_longitude,
                         walking_threshold):
    origin = geopy.Point(dropoff_latitude, dropoff_longitude)
    b = 0
    destinations = []
    while b < 360:
        destination = VincentyDistance(miles=walking_threshold /
                                       2).destination(origin, b)
        b = b + 45
        lat2, lon2 = destination.latitude, destination.longitude
        destinations.append((round(lat2, 4), round(lon2, 4)))
    return destinations
Пример #11
0
 def next(self, field):
     from geopy.distance import VincentyDistance
     longitude = random.randint(
         -179, 179) if self.longitude is None else self.longitude
     latitude = random.randint(
         -179, 179) if self.latitude is None else self.latitude
     radius = random.randint(100,
                             6000) if self.radius is None else self.radius
     d = VincentyDistance(kilometers=radius)
     bearing = random.randint(0, 359)
     p = d.destination((latitude, longitude), bearing)
     return Point(x=p.longitude, y=p.latitude)
Пример #12
0
 def _get_next_pos(self, lat, lon, bearing, speed, precision):
     origin = Point(lat, lon)
     if speed == 0.0:
         return lat, lon
     if speed == float("inf"):
         return self.destLat, self.destLng
     else:
         offset_angle = (1 / self.speed) * (precision / 1.74)
         lat, lon, _ = VincentyDistance(
             kilometers=speed * 1e-3).destination(
                 origin, bearing + uniform(-offset_angle, offset_angle))
         return lat, lon
Пример #13
0
def getNewLatLong(startLat, startLong, dis_list, azimuth_list):
    length = len(dis_list)
    NewLat = []
    NewLong = []
    NewLat.append(startLat)
    NewLong.append(startLong)
    for i in range(length):
        startPoint = geopy.Point(NewLat[i], NewLong[i])
        newPoint = VincentyDistance(meters=(dis_list[i])).destination(
            startPoint, azimuth_list[i])
        NewLat.append(newPoint.latitude)
        NewLong.append(newPoint.longitude)
    return NewLat, NewLong
Пример #14
0
 def sum_grid(rkey, tkey, t_pure, waveform, gcarc_id, az):
     km = r[rkey][str(int(h))]['deg'][gcarc_id] * 111.19
     time = t[tkey][str(int(h))][gcarc_id]
     dest = VincentyDistance(kilometers=km).destination(origin, az)
     lon_idx = np.argmin(np.abs(lon_a - dest.longitude))
     lat_idx = np.argmin(np.abs(lat_a - dest.latitude))
     stack_d = waveform[int(np.abs(time - t_pure) * 10) + 500]
     i = tree.query_ball_point((dest.longitude, dest.latitude), 2.0)
     for jj in i:
         lon_idx = np.abs(lon_a - x[jj]).argmin()
         lat_idx = np.abs(lat_a - y[jj]).argmin()
         grid_count[lon_idx, lat_idx, h_idx] += 1.
         grid[lon_idx, lat_idx, h_idx] += stack_d
Пример #15
0
def make_square(latitude, longitude, altitude, i, b, d):
  if(i < 4):
    i++
    # given: lat1, lon1, b = bearing in degrees, d = distance in kilometers

    origin = geopy.Point(latitude, longitude)
    destination = VincentyDistance(kilometers=d).destination(origin, b)

    lat2, lon2 = destination.latitude, destination.longitude

    #goto wp

    make_square(lat2,lon2, altitude, i, b, d)
Пример #16
0
def getNeighbors(loc, level=15, spread=700):
    distance = VincentyDistance(meters=spread)
    center = (loc[0], loc[1], 0)
    p1 = distance.destination(point=center, bearing=45)
    p2 = distance.destination(point=center, bearing=225)
    p1 = s2sphere.LatLng.from_degrees(p1[0], p1[1])
    p2 = s2sphere.LatLng.from_degrees(p2[0], p2[1])
    rect = s2sphere.LatLngRect.from_point_pair(p1, p2)
    region = s2sphere.RegionCoverer()
    region.min_level = level
    region.max_level = level
    cells = region.get_covering(rect)
    return sorted([c.id() for c in cells])
Пример #17
0
def get_circle_centers(b1, b2, radius):
    """the function covers the area within the bounds with circles
    this is done by calculating the lat/lng distances and the number of circles needed to fill the area
    as these circles only intersect at one point, an additional grid with a (+radius,+radius) offset is used to
    cover the empty spaces
    :param b1: bounds
    :param b2: bounds
    :param radius: specified radius, adapt for high density areas
    :return: list of circle centers that cover the area between lower/upper
    """

    sw, ne = Point(b1), Point(b2)

    # north/east distances
    dist_lat = int(vincenty(Point(sw[0], sw[1]), Point(ne[0], sw[1])).meters)
    dist_lng = int(vincenty(Point(sw[0], sw[1]), Point(sw[0], ne[1])).meters)

    def cover(p_start, n_lat, n_lng, r):
        _coords = []

        for i in range(n_lat):
            for j in range(n_lng):
                v_north = VincentyDistance(meters=i * r * 2)
                v_east = VincentyDistance(meters=j * r * 2)

                _coords.append(v_north.destination(v_east.destination(point=p_start, bearing=90), bearing=0))

        return _coords

    def _calc_base(dist):
        """ Calculation for base cover """
        return math.ceil((dist - radius) / (2 * radius)) + 1

    def _calc_offset(dist):
        """ Calculation for offset cover """
        return math.ceil((dist - 2 * radius) / (2 * radius)) + 1

    coords = []

    # get circles for base cover
    coords += cover(sw, _calc_base(dist_lat), _calc_base(dist_lng), radius)

    # update south-west for second cover
    vc_radius = VincentyDistance(meters=radius)
    sw = vc_radius.destination(vc_radius.destination(point=sw, bearing=0), bearing=90)

    # get circles for offset cover
    coords += cover(sw, _calc_offset(dist_lat), _calc_offset(dist_lng), radius)

    # only return the coordinates
    return [c[:2] for c in coords]
Пример #18
0
def start_points_and_distances_and_bearings_to_endpoints(
        start_latitudes_deg=None, start_longitudes_deg=None,
        displacements_metres=None, geodetic_bearings_deg=None):
    """Computes endpoint from each start point, displacement, and bearing.

    P = number of start points

    :param start_latitudes_deg: length-P numpy array of beginning latitudes
        (deg N).
    :param start_longitudes_deg: length-P numpy array of beginning longitudes
        (deg E).
    :param displacements_metres: length-P numpy array of displacements.
    :param geodetic_bearings_deg: length-P numpy array of geodetic bearings
        (from start point towards end point, measured clockwise from due north).
    :return: end_latitudes_deg: length-P numpy array of end latitudes (deg N).
    :return: end_longitudes_deg: length-P numpy array of end longitudes (deg E).
    """

    error_checking.assert_is_valid_lat_numpy_array(
        start_latitudes_deg, allow_nan=False)
    error_checking.assert_is_numpy_array(start_latitudes_deg, num_dimensions=1)
    num_points = len(start_latitudes_deg)

    start_longitudes_deg = lng_conversion.convert_lng_positive_in_west(
        start_longitudes_deg, allow_nan=False)
    error_checking.assert_is_numpy_array(
        start_longitudes_deg, exact_dimensions=numpy.array([num_points]))

    error_checking.assert_is_geq_numpy_array(displacements_metres, 0.)
    error_checking.assert_is_numpy_array(
        displacements_metres, exact_dimensions=numpy.array([num_points]))

    error_checking.assert_is_geq_numpy_array(geodetic_bearings_deg, 0.)
    error_checking.assert_is_leq_numpy_array(geodetic_bearings_deg, 360.)
    error_checking.assert_is_numpy_array(
        geodetic_bearings_deg, exact_dimensions=numpy.array([num_points]))

    end_latitudes_deg = numpy.full(num_points, numpy.nan)
    end_longitudes_deg = numpy.full(num_points, numpy.nan)
    for i in range(num_points):
        this_start_point_object = geopy.Point(
            start_latitudes_deg[i], start_longitudes_deg[i])
        this_end_point_object = VincentyDistance(
            meters=displacements_metres[i]).destination(
                this_start_point_object, geodetic_bearings_deg[i])

        end_latitudes_deg[i] = this_end_point_object.latitude
        end_longitudes_deg[i] = this_end_point_object.longitude

    return end_latitudes_deg, lng_conversion.convert_lng_positive_in_west(
        end_longitudes_deg, allow_nan=False)
Пример #19
0
def bipartite(day, month,year,files):
    """
    Function bipartite
    ---------------------
    Creates a bipartite graph with edges across all possible combinations of waypoints through the zones.
    Each edge has an attribute of speed(average speed across the edge based on wind) and time (speed/distance)

    day: day the data was collected
    month: month the data was collected
    year: year the data was collected
    files: list with tags for paths of xlsx files formatted in the way shown getFlightData

    returns: a bipartite graph with edges between zones that have the attributes of speed and time (networkx graph)
    """
    
    import geopy
    from geopy.distance import VincentyDistance


    zone = zones()  #create zones
    waypoint = waypointDict(files) #get the waypoint dict of all waypoints
    zdir = GP(day,month,year)[0] #predicted wind directions across all prediction points
    zspeed = GP(day,month,year)[0]#predicted wind speed across all prediction points
    network = nx.DiGraph()

    for i in range(len(zone) - 1):  #Creates the edges from layer to layer in bipartite graph
        for j in range(len(zone[i])):
            for k in range(len(zone[i+1])):
                network.add_edge(zone[i][j], zone[i+1][k],  #Adds edges from one zone to another with distance as attribute
                                 distance = haversine((waypoint[zone[i][j]]), (waypoint[zone[i+1][k]]))/1.60934)
    for i in range(len(zone[0])):
        network.add_edge('source', zone[0][i], distance = haversine(waypoint['source'], waypoint[zone[0][i]])/1.60934)
    for i in range(len(zone[5])):
        network.add_edge(zone[5][i], 'sink', distance = haversine(waypoint[zone[5][i]], waypoint['sink'])/1.60934)

    p = 0 #placeholder for iterating through zdir and zspeed lists
    for i in range(network.number_of_edges()):#Goes through each edge to find intervals to calculate weather data
        b = bearing((waypoint[network.edges()[i][0]]), (waypoint[network.edges()[i][1]]))   #bearing of the edge
        origin = geopy.Point(waypoint[network.edges()[i][0]][0], waypoint[network.edges()[i][0]][1])#lat,lon of point 1
        network[network.edges()[i][0]][network.edges()[i][1]]['speed'] = 0
        k = 0 #placeholder to find total number of iteration points along each edge
        for j in range(0, int(roundDown(network[network.edges()[i][0]][network.edges()[i][1]]['distance'],20)),20):
            destination = VincentyDistance(kilometers=j).destination(origin, b) #geopy to calculate lat lon after 20miles
            b_final = (bearing((destination.latitude, destination.longitude), (waypoint[network.edges()[i][0]][0], waypoint[network.edges()[i][0]][1]))+180)%360
            network[network.edges()[i][0]][network.edges()[i][1]]['speed'] += speed_calc(destination.latitude, destination.longitude, b_final, zdir[p],zpeed[p])
            k+=1
            p+=1
        network[network.edges()[i][0]][network.edges()[i][1]]['speed'] /= k #average speed across each edge
        network[network.edges()[i][0]][network.edges()[i][1]]['time'] = network[network.edges()[i][0]][network.edges()[i][1]]['distance']/
                                                                                        network[network.edges()[i][0]][network.edges()[i][1]]['speed'] #time across each edge
Пример #20
0
def get_dest_gps_cood(lat1, lon1, bearing, distance_in_meters):
    # given: lat1, lon1, b = bearing in degrees, d = distance in kilometers
    #returns new lat long
    #lat1 = 53.32055555555556
    #lat2 = 53.31861111111111
    #lon1 = -1.7297222222222221
    #lon2 = -1.6997222222222223
    d = distance_in_meters / 1000.0
    b = bearing
    print d, b
    origin = geopy.Point(lat1, lon1)
    destination = VincentyDistance(kilometers=d).destination(origin, b)
    lat2, lon2 = destination.latitude, destination.longitude
    return lat2, lon2
Пример #21
0
def get_next_point(lat, lon, distance, bearing):
    """
    This function calculates the next point given an 
    origin point, a distance and a bearing.

    :param float lat: Latitude of the first point
    :param float lon: Longitude of the first point
    :param float distance: Radius of the circle in km
    :param float bearing: Bearing angle in degrees
    """
    origin = Point(lat, lon)
    destination = VincentyDistance(kilometers=distance).destination(
        origin, bearing)
    return destination.latitude, destination.longitude
Пример #22
0
def get_circle_centers(b1, b2, radius):
    """
    the function covers the area within the bounds with circles
    :param b1: south-west bounds [lat, lng]
    :param b2: north-east bounds [lat, lng]
    :param radius: specified radius, adapt for high density areas
    :return: list of circle centers that cover the area between lower/upper
    """

    sw = Point(b1)
    ne = Point(b2)

    # north/east distances
    dist_lat = vincenty(Point(sw[0], sw[1]), Point(ne[0], sw[1])).meters
    dist_lng = vincenty(Point(sw[0], sw[1]), Point(sw[0], ne[1])).meters

    circles = cover_rect_with_cicles(dist_lat, dist_lng, radius)
    cords = [
        VincentyDistance(meters=c[0]).destination(
            VincentyDistance(meters=c[1]).destination(point=sw, bearing=90),
            bearing=0)[:2] for c in circles
    ]

    return cords
def get_data(latitude,longitude,parameter,distance):
	url = 'http://icity-gw.icityproject.com:8080/developer/api/devices/'
	apikey = '?apikey=l7xxe1d39a7eac524bd2b709c55002d702e2'
	params = '&cityID=7'

	response = urllib.request.urlopen(url + apikey + params).read()
	if response:
		res = json.loads(response.decode())

		param = "urn:" + parameter

		origin = geopy.Point(latitude, longitude)
		destination = VincentyDistance(distance).destination(origin, 0)
		latdif = destination.latitude - latitude
		destination = VincentyDistance(distance).destination(origin, 90)
		londif = destination.longitude - longitude

		url = 'http://icity-gw.icityproject.com:8080/developer/api/observations/last/'
		sensors = []
		#Barcelona parsing--------------------------------------------
		#latitude: 41.3477244-41.4536057, longitude: 2.0980604-2.2252299
		i = 0
		for i in range(len(res)):
			if(float(res[i]["latitude"]) > 41.3477244 and float(res[i]["latitude"]) < 41.4536057 and float(res[i]["longitude"]) > 2.0980604 and float(res[i]["longitude"]) < 2.2252299):
				if(float(res[i]["latitude"]) > latitude-latdif and float(res[i]["latitude"]) < latitude+latdif and float(res[i]["longitude"]) > longitude-londif and float(res[i]["longitude"]) < longitude+londif):
					if(param in res[i]["properties"]):
						params = "&id="+ res[i]["deviceID"] + "&property=" + param + "&n=1"
						response = urllib.request.urlopen(url + apikey + params).read()
						if response:
							result = json.loads(response.decode())
							#Sensors without units...
							if result[0]["units"]:		
								sensors.append(result[0])
								print(result[0]["value"],result[0]["units"])

		print(sensors)
Пример #24
0
def get_pts(r, loc1, d):
    
    pts = []
    
    lat, lon = loc1
    for ii in range(r):
        b = np.random.uniform(360)
        di = np.random.uniform(d)
        
        origin = geopy.Point(lat, lon)
        destination = VincentyDistance(kilometers=di).destination(origin, b)
        lat2, lon2 = destination.latitude, destination.longitude
        
        pts.append([lon2, lat2])

    return pts
Пример #25
0
 def createRandomAddress(self):
     origin = geopy.Point(self.centerLatLng['lat'], self.centerLatLng['lng'])
     while True:
         randAngle = rd.randrange(0,360)
         randDistance = rd.randrange(0,self.radiusInMeter)
         newLoc = VincentyDistance( (randDistance+0.1)/1000.).destination(origin, randAngle)
         lat, lng = newLoc.latitude, newLoc.longitude
         if self.checkValidity:
             validAddress = self.geop.isValidGeocode(lat,lng,self.verbose)
         else:
             validAddress = True
         if not validAddress:
             continue
         else:
             break
     return(lat,lng)        
Пример #26
0
def findShortest(name, radius, origin, alt, circle, direction):
    distArr = []
    circle = circle.to_lat_lon()
    lastDist = 99999
    for i in range(len(circle)):
        destination = geopy.Point(circle[i][0], circle[i][1], alt)
        distance = VincentyDistance(origin, destination).meters
        dist = distance - radius
        if (lastDist > 0) and (dist < 0) and (direction == "North"):
            minDist = dist
            j = i
        if (lastDist < 0) and (dist > 0) and (direction == "South"):
            minDist = dist
            j = i
        lastDist = dist
    return geopy.Point(circle[j][0], circle[j][1], alt)
Пример #27
0
 def makePolygon(self, latlon):
     '''creating a polygon from the x and y coordinates and the area'''
     L = 150                                                             # 150 km by default
     d = 0.5 * (np.sqrt(L**2 + L**2))                                   # distance from area
     b = [45, 135, 225, 315, 45]                                         # direction in degrees
     geostr = "POLYGON(("                                                # make a string for the polygon
     lat1, lon1 = latlon
     for i in range(5):
         origin = geopy.Point(lat1, lon1)
         destination = VincentyDistance(kilometers=d).destination(origin, b[i])
         lat2, lon2 = destination.latitude, destination.longitude            # create four corners of polygon
         geostr += str(lon2) + ' ' + str(lat2)
         if i != 4:
             geostr += ','
     geostr += "))"
     return geostr
Пример #28
0
    def radial_zip_data(self, out, session, **params):
        if params.get('radius'):
            res = ZipcodeSearchEngine().by_coordinate(
                self.center["Latitude"], self.center["Longitude"], radius=int(params['radius']), returns=0)

            out.writerow(['# of Attendees', 'City', 'State', 'Zipcode', 'Miles from Event', '% of Total Attendees'])
            if len(res) > 0:
                keys = self.zips.keys()
                center_coord = (self.center["Latitude"], self.center["Longitude"])
                filter = Attendee.badge_status.in_([c.NEW_STATUS, c.COMPLETED_STATUS])
                attendees = session.query(Attendee).filter(filter)
                total_count = attendees.count()
                for x in res:
                    if x['Zipcode'] in keys:
                        out.writerow([self.zips_counter[x['Zipcode']], x['City'], x['State'], x['Zipcode'],
                                      VincentyDistance((x["Latitude"], x["Longitude"]), center_coord).miles,
                                      "%.2f" % float(self.zips_counter[x['Zipcode']] / total_count * 100)])
Пример #29
0
def loc_from_distance(lat, lon, d, brng):
    '''
    Parameters:
    lat, lon in degrees
    d in km
    brng in degrees

    Return: 
    lat, lon in degree
    '''
    origin = geopy.Point(lat, lon)
    destination = VincentyDistance(kilometers=d).destination(origin, brng)

    lat2, lon2 = destination.latitude, destination.longitude

    print(lat2,lon2)
    return lat2, lon2
def do_blur(db, radius):
    """
    Offsets every GPS point by a random amount (0, radius[ in a random
    direction

    :param db: Database object
    :param radius: the maximum distance to offset
    :return: Void
    """
    select_query = """
        SELECT ST_AsText(lonlat) as point, trip_id, ts, altitude
        FROM sensor_gps LIMIT 1"""
    radius = int(radius)
    cur = db.cursor
    cur.execute(select_query)
    rows = cur.fetchall()
    pointre = re.compile("POINT\((\d+\.\d+) (\d+\.\d+)\)")
    insertdata = []
    for row in rows:
        match = pointre.match(row[0])
        lat = float(match.group(1))
        lon = float(match.group(2))
        origin = geopy.Point(lat, lon)
        bearing = random.randint(0, 360)
        distance = random.randint(0, radius) / 1000
        destination = VincentyDistance(kilometers=distance)\
                       .destination(origin, bearing)
        insertdata.append({
            "point":
            "POINT(" + str(destination.latitude) + " " +
            str(destination.longitude) + ")",
            "trip_id":
            row[1],
            "ts":
            row[2],
            "altitude":
            row[3]
        })
    print("Done Select, starting insert")
    cur.executemany(
        """
    INSERT INTO anon_sensor_gps (lonlat, trip_id, ts, altitude) VALUES (
    ST_GeomFromText(%(point)s), %(trip_id)s, %(ts)s, %(altitude)s);
    """, insertdata)
    print("Done")
    db.connection.commit()