def __init__(self, bbox): self.bot_left = Point(bbox[1], bbox[0]) self.top_right = Point(bbox[3], bbox[2]) self.bot_right = Point(bbox[1], bbox[2]) self.top_left = Point(bbox[3], bbox[0]) self._width = get_distance(self.top_left, self.top_right) self._height = get_distance(self.top_left, self.bot_left)
def get_distance(row): try: x = Point(row.longitudeCommuneAcheteur, row.latitudeCommuneAcheteur) y = Point(row.longitudeCommuneEtablissement, row.latitudeCommuneEtablissement) return distance(x, y).km except ValueError: return None
def get_distance(row): """Calcul des distances entre l'acheteur et l'établissement qui répond à l'offre""" try: x = Point(row.longitudeCommuneAcheteur, row.latitudeCommuneAcheteur) y = Point(row.longitudeCommuneEtablissement, row.latitudeCommuneEtablissement) return distance(x, y).km except ValueError: return None
def get_corners( coordinates, radius=DEFAULT_INSCRIPTION_RADIUS): #inscribed square in circle km = radius / 1000 TL_point = vincenty(kilometers=km).destination( Point(coordinates[0], coordinates[1]), 315) # northwest BR_point = vincenty(kilometers=km).destination( Point(coordinates[0], coordinates[1]), 135) # southeast TL = (TL_point[0], TL_point[1]) BR = (BR_point[0], BR_point[1]) return (TL, BR)
def _check_geolocation(validator, ref, instance, schema): default_deviation = 50 if instance.get(ref['override_field']): # Check has been overridden return address = instance.get(ref['address_field']) if not address: # we cannot validate anything without an address string raise ValidationError( '`{}` field is required for geo location check'.format( ref['address_field'])) # resolve the given address matches = app.geocode(address) # check address for error in _check_address(address, matches): yield error # check geo point if present geo_point = instance.get(ref['geopoint_field']) max_deviation = ref.get('geopoint_deviation', default_deviation) if geo_point: for error in _check_geo_point(Point(geo_point), matches[0].point, max_deviation): yield error
def recherche_voisin(support, distance): data_sup = d_les_supports[support] dept_limitrof = limit[data_sup[1][1]] dept_limitrof.append(data_sup[1][1]) geo_gsmr = data_sup[0] lat1, lon1 = geo_gsmr liste = [] origin = Point(lat1, lon1) limit0 = VincentyDistance(kilometers=distance).destination( origin, 0).format_decimal() limit90 = VincentyDistance(kilometers=distance).destination( origin, 90).format_decimal() lat0, lon0 = limit0.split(', ') lat90, lon90 = limit90.split(', ') dif0 = float(lat0) - lat1 dif90 = float(lon90) - lon1 latmini = lat1 - dif0 latmaxi = float(lat0) lonmini = lon1 - dif90 lonmaxi = float(lon90) for dept in set(dept_limitrof): for support_P in d_dept_geo[dept]: if latmini <= support_P[1] <= latmaxi: if lonmini <= support_P[2] <= lonmaxi: if support_P[0] in l_support_GsmP_seuls: liste.append(support_P[0]) return liste
def newPoint(self, point, mDist, bearing): kmDist = mDist / 1000 origin = Point(point[0][0], point[0][1]) destination = VincentyDistance(kilometers=kmDist).destination( origin, bearing) return ((destination.latitude, destination.longitude), point[1] + timedelta(0, 4))
def set_from_vincenty_formulae(self, initial_coordinates, distance): azimuth = abs((initial_coordinates.azimuth - 360.0) - 90) point = VincentyDistance(kilometers=distance).destination( Point(initial_coordinates.latitude, initial_coordinates.longitude), azimuth) self.latitude = point.latitude self.longitude = point.longitude
def fetch_stores(client, stores, src, max_distance): src_loc = get_geoloc(client, src) filtered = {} for key in stores.keys(): p = Point(latitude=stores[key]['lat'], longitude=stores[key]['lon']) if great_circle(src_loc, p).kilometers < max_distance: filtered[key] = stores[key] return filtered
def get_geoloc(client, addr): for old, new in [(u'פינת', '&'), (u'אזו"ת', ''), (u'אזוה"ת', ''), (u"אזוה''ת", '')]: addr = addr.replace(old, new) loc = geocode(client, addr, language='iw') if len(loc) == 0: return None geoloc = loc[0]['geometry']['location'] return Point(latitude=geoloc['lat'], longitude=geoloc['lng'])
def get_horizontal_circles(radius, bounds, start): circles = [] center = Point(start.latitude, start.longitude) right = Point(start.latitude, bounds.bot_right.longitude) if bounds.width() / 2 > radius: while True: center = distance(radius).destination(point=center, bearing=90) circle = Circle(center, radius) circles.append(circle) if get_distance(center, right) < radius * 3: last_center = distance(radius).destination(point=right, bearing=270) last_circle = Circle(last_center, radius) if get_distance(circle.center, last_circle.center) > radius / 4: circles.append(last_circle) break center = distance(radius).destination(point=center, bearing=90) else: center = distance(bounds.width() / 2).destination(point=center, bearing=90) circles.append(Circle(center, radius)) return circles
def get_country_shape(country_code): sf = shapefile.Reader( "/Users/dilip/Downloads/TM_WORLD_BORDERS-0.3/TM_WORLD_BORDERS-0.3.shp") for index, record in enumerate(sf.records()): if record[1] == country_code: print('Record index', index) shape = sf.shape(index) print(len(shape.points), 'points in country shape') points = [] for point in shape.points: points.append(Point(point[::-1])) return points
def get_filler_circles(prev_row_circles, row_circles, radius): circles = [] if len(prev_row_circles) < 2 or len(row_circles) < 2: return circles max_index = min(len(prev_row_circles), len(row_circles)) index = 1 while index < max_index: bottom = prev_row_circles[index - 1].center top = row_circles[index].center center = Point((bottom.latitude + top.latitude) / 2, (bottom.longitude + top.longitude) / 2) circles.append(Circle(center, radius / 2)) index += 1 return circles
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
def get_rides_from_to(self, from_, to_, seats=1): from_latitude, from_longtitude = self._lat_lot_of_city(from_) to_latitude, to_longtitude = self._lat_lot_of_city(to_) prices = self._client.get_price_estimates( start_latitude=from_latitude, start_longitude=from_longtitude, end_latitude=to_latitude, end_longitude=to_longtitude, seat_count=seats) best = None for price in prices.json['prices']: if (price['high_estimate'] is None or price['low_estimate'] is None or price['currency_code'] is None): continue if best is None: best = price if (best['low_estimate'] < price['low_estimate']): best = price result = { key: val for key, val in best.items() if key in ('currency_code', 'low_estimate', 'high_estimate') } # dystans w linii prostej ! result['distance'] = distance( Point(from_latitude, from_longtitude), Point(to_latitude, to_longtitude), ).kilometers if result['currency_code'] != 'EUR': result['low_estimate'], result[ 'high_estimate'] = self._convert_currencies( [result['low_estimate'], result['high_estimate']], result['currency_code'], 'EUR', ) result['currency_code'] = 'EUR' return result
def find_most_pop_area_within_dist(lat, lon, d=100): # returns lat,lon of the most populated area # from point (lat,lon) within distance d km global ds, transf, transfInv origin = Point(lat, lon) latd={} lond={} i=0 pxl=float('inf') pxh=float('-inf') pyl=float('inf') pyh=float('-inf') bs = [0,90,180,270] for b in bs: destination = vincenty(kilometers=d).destination(origin, b) latd[i], lond[i] = destination.latitude, destination.longitude px, py = gdal.ApplyGeoTransform(transfInv, lond[i], latd[i]) # print((latd[i],lond[i])) pxl = min(pxl,px) pxh = max(pxh,px) pyl = min(pyl,py) pyh = max(pyh,py) i+=1 pxl = int(np.floor(pxl)) pxh = int(np.ceil(pxh)) pyl = int(np.floor(pyl)) pyh = int(np.ceil(pyh)) ed=max(latd.values())-min(latd.values()) eD=max(lond.values())-min(lond.values()) pxmax=0 pymax=0 pvmax=float('-inf') for px in range(pxl,pxh+1): for py in range(pyl,pyh+1): lonc, latc = gdal.ApplyGeoTransform(transf, px, py) if not pointInEllipse(lat,lon,latc,lonc,ed,eD): continue pv = pixel2val(px, py) if pv > pvmax: pvmax = pv pxmax = px pymax = py lonmax, latmax = gdal.ApplyGeoTransform(transf, pxmax, pymax) return latmax,lonmax, latd,lond
def find_route(src, qty, max_per_store, store2price, store_locs): store_locs = {k: Point(latitude=v['lat'], longitude=v['lon']) for k, v in store_locs.items()} keys = store_locs.keys() keys = filter(lambda store: store in store2price, keys) acquired = 0 current_loc = src route = [] while acquired < qty: prices = np.array(map(lambda store: store2price[store][0], keys)) distances = np.array(map(lambda store: great_circle(current_loc, store_locs[store]).kilometers, keys)) distances_home = np.array(map(lambda store: great_circle(src, store_locs[store]).kilometers, keys)) going_to_purchase = min(max_per_store, qty - acquired) score = going_to_purchase * prices + 0.5 * (distances + distances_home) best = np.argmin(score) print prices[best] acquired += going_to_purchase current_loc = store_locs[keys[best]] route.append(keys[best]) keys.remove(keys[best]) return route
def get_state_shapes(country_code): code = pycountry.countries.get(alpha_2=country_code).alpha_3 path = "/Users/dilip/Downloads/gadm/{}_adm_shp/{}_adm1.shp".format( code, code) sf = shapefile.Reader(path) fields = sf.fields[1:] field_names = [field[0] for field in fields] states = [] for sr in sf.shapeRecords(): attrs = dict(zip(field_names, sr.record)) points = [] for point in sr.shape.points: points.append(Point(point[::-1])) states.append({ 'name': attrs['NAME_1'], 'country': attrs['NAME_0'], 'type': attrs['ENGTYPE_1'], 'shape': points, 'bbox': sr.shape.bbox }) return states
def get_destination(lat, lon, bearing, km): origin = Point(lat, lon) destination = VincentyDistance(kilometers=km).destination(origin, bearing) return destination.latitude, destination.longitude
print(dis,'nm') dis = distance(kilometers=1).destination((-24,-42),0) print(dis,'km') help(distance) # para ver o nome das unidades de distancias #%%Formata de DD.DD para DMS.SS ponto = distance(nautical=1).destination((-24,-42),0) print(dir(ponto)) print(help(ponto.format)) print("DMS = ",ponto.format()) #Passa de grau decimal (D) para grau minuto segundo (DMS) print("DMS com grau = ", ponto.format(deg_char='°')) #Passa de grau decimal (D) ou DMS print("DD.DD = ", ponto.format_decimal()) #%%Ponto a partir de uma string p1 = Point('24 45.55m S, 45 0m 0s W') p2 = Point.from_string('24 45m 30s S, 45 W') print('p1 = ',p1) print('p1 == p2?', p1 == p2) print(p1.format(deg_char = "°", min_char= '\'' ,sec_char= "\"")) # %% print(p1.format_decimal()) # %% def dd2dms(dd): if dd < 0: dd = abs(dd) sinal = -1
def notify(pokemon): """Send a PushBullet notification and/or a Tweet, depending on if their respective API keys have been set in config. """ # skip if no API keys have been set in config if cnf['PB_API_KEY'] or cnf['TWITTER_CONSUMER_KEY']: time_till_hidden = pokemon['time_till_hidden_ms'] coordinates = Point(latitude=round(pokemon['latitude'], 6), longitude=round(pokemon['longitude'], 6)) pokeid = pokemon['pokemon_data']['pokemon_id'] encounter_id = pokemon['encounter_id'] if encounter_id in recent_encounters: return (False, 'Already notified.') # skip duplicate else: pokename = POKEMON_NAMES[pokeid] # do not notify if it expires in less than 3 minutes if time_till_hidden < 180000: return (False, pokename + ' was expiring too soon to notify.') if cnf['TZ_OFFSET']: now = datetime.now(timezone(timedelta(hours=cnf['TZ_OFFSET']))) else: now = datetime.now() if time_till_hidden > 3600000: # actual expiration time should be a minimum of 15 minutes away delta = timedelta(minutes=15) else: delta = timedelta(milliseconds=time_till_hidden) expire_time = (now + delta).strftime('%I:%M %p').lstrip('0') if time_till_hidden > 3600000: expire_time = 'at least ' + expire_time map_link = ('https://maps.google.com/maps?q=' + str(coordinates.latitude) + ',' + str(coordinates.longitude)) place_string, landmark = find_landmark(coordinates) try: if landmark.hashtags: cnf['HASHTAGS'] = landmark.hashtags except AttributeError: pass tweeted = False pushed = False if cnf['PB_API_KEY']: pushed = pbpush(pokename, delta, expire_time, map_link, place_string) if (cnf['TWITTER_CONSUMER_KEY'] and cnf['TWITTER_CONSUMER_SECRET'] and cnf['TWITTER_ACCESS_KEY'] and cnf['TWITTER_ACCESS_SECRET']): tweeted = tweet(pokename, expire_time, map_link, place_string, coordinates) if tweeted and pushed: recent_encounters.append(encounter_id) return (True, 'tweeted and pushed about ' + pokename) elif tweeted: recent_encounters.append(encounter_id) return (True, 'tweeted about ' + pokename) elif pushed: recent_encounters.append(encounter_id) return (True, 'pushed about ' + pokename) else: return (False, 'Failed to notify about ' + pokename) else: return (False, 'Did not notify, no Twitter/PushBullet keys set.')