def tile_server(draw_callback=None, port=8888, debug=False): tiler = GoogleTiles() figure = plt.figure(figsize=(4, 4)) ax = plt.axes([0, 0, 1, 1], projection=tiler.crs) ax.set_global() ax.outline_patch.set_visible(False) ax.background_patch.set_visible(False) if draw_callback: draw_callback(ax) class TileHandler(tornado.web.RequestHandler): def get(self, z, y, x): print 'Requested tile: ', x, y, z self.set_header('Content-Type', 'image/png') x_lim, y_lim = tiler.tile_bbox(int(x), int(y), int(z)) ax.set_xlim(x_lim) ax.set_ylim(y_lim) buff = io.BytesIO() figure.canvas.print_figure(buff, format='png', dpi=64, facecolor='none', edgecolor='none') self.write(buff.getvalue()) print 'Done' application = tornado.web.Application([ (r"/tile/z([0-9]+)_y([0-9]+)_x([0-9]+).png", TileHandler), ], debug=debug) application.listen(port) print 'Server ready.' tornado.ioloop.IOLoop.instance().start()
def get_data(self, element, ranges, style): if isinstance(element.data, util.basestring): tile_source = GoogleTiles(url=element.data) return (tile_source, self.zoom), style, {} else: tile_source = element.data return (tile_source, element.layer), style, {}
def plot_google_maps(): fig = plt.figure(figsize=(10, 10)) tiler = GoogleTiles(style="satellite") mercator = tiler.crs ax = plt.axes(projection=mercator) ax.set_extent((153, 153.2, -26.6, -26.4)) zoom = 12 ax.add_image(tiler, zoom) # even 1:10m are too coarse for .2 degree square #ax.coastlines('10m') home_lat, home_lon = -26.5258277, 153.0912987 # Add a marker for home plt.plot(home_lon, home_lat, marker='o', color='red', markersize=5, alpha=0.7, transform=ccrs.Geodetic()) plt.show()
def gen_sat_map(df): ''' info ''' print("\nDownloading data and plotting map!") img = GoogleTiles( url='https://server.arcgisonline.com/ArcGIS/rest/services' '/World_Imagery/MapServer/tile/{z}/{y}/{x}.jpg') plt.figure(figsize=(100, 100)) ax = plt.axes(projection=img.crs) def gen_map_extent(df): ''' info ''' c = 0.05 min_x, max_x = min(df.lon), max(df.lon) min_y, max_y = min(df.lat), max(df.lat) def get_extent(min_num, max_num): ''' info ''' diff = max_num - min_num delta = (diff / min_num) * 100 if max_num > 0 and min_num > 0: __max__ = max_num + (c * delta) __min__ = min_num - (c * delta) elif max_num < 0 and min_num < 0: __max__ = max_num - (c * delta) __min__ = min_num + (c * delta) extent.append(__min__) extent.append(__max__) extent = list() get_extent(min_x, max_x) get_extent(min_y, max_y) return extent extent = gen_map_extent(df) ax.set_extent(extent) ax.add_image(img, 18) x, y = df.lon, df.lat ax.plot(x, y, transform=ccrs.Geodetic(), color='purple', linewidth=5) plt.savefig("./maps/strava_map_" + f.name.strip(f.name[-4:]) + ".png", bbox_inches="tight") plt.close()
def patch_image_cache(style, cache_dir='tilecache'): """ Monkey patch the ``get_image()`` method of ``tiles`` to read and write image tiles from ``cache_dir`` before trying to download them. """ from cartopy.io.img_tiles import GoogleTiles tiles = GoogleTiles(style=style) # Ensure cache directory exists. os.makedirs(cache_dir, exist_ok=True) def get_image(tile): cache_img = os.path.join(cache_dir, style + '_%d_%d_%d.png' % tile ) if os.path.exists(cache_img): img = Image.open(cache_img).convert(tiles.desired_tile_form) return img, tiles.tileextent(tile), 'lower' # Call get_image() method of tiles instance and store the downloaded image. img, extent, origin = type(tiles).get_image(tiles, tile) img.save(cache_img, 'PNG') return img, extent, origin tiles.get_image = get_image return tiles
def __init__(self, extend, zoom): # characteristics self.extent = extend self.zoomlevel = zoom self.figsize = [12, 9] # make basic figure size self.fig = plt.figure(figsize=self.figsize) # get and plot the Open Streetmap data request = GoogleTiles() self.ax = plt.axes(projection=request.crs) self.ax.set_extent(self.extent) self.ax.add_image(request, self.zoomlevel) # zoom level 10
def get_map_params(image='StamenTerrain', color_palette=None): # set color palette if color_palette: cmap = plt.get_cmap(color_palette) else: cmap = None # set background image if image == 'StamenTerrain': tiler = StamenTerrain() elif image == 'GoogleTiles': tiler = GoogleTiles() elif image == 'OSM': tiler = OSM() return cmap, tiler
def get_tile_rgb(tile_source, bbox, zoom_level, bbox_crs=ccrs.PlateCarree()): """ Returns an RGB element given a tile_source, bounding box and zoom level. Parameters ---------- tile_source: WMTS element or string URL The tile source to download the tiles from. bbox: tuple A four tuple specifying the (left, bottom, right, top) corners of the domain to download the tiles for. zoom_level: int The zoom level at which to download the tiles bbox_crs: ccrs.CRs cartopy CRS defining the coordinate system of the supplied bbox Returns ------- RGB element containing the tile data in the specified bbox """ from .element import RGB, WMTS if isinstance(tile_source, (WMTS, Tiles)): tile_source = tile_source.data if bbox_crs is not ccrs.GOOGLE_MERCATOR: bbox = project_extents(bbox, bbox_crs, ccrs.GOOGLE_MERCATOR) if '{Q}' in tile_source: tile_source = QuadtreeTiles(url=tile_source.replace('{Q}', '{tile}')) else: tile_source = GoogleTiles(url=tile_source) bounds = box(*bbox) rgb, extent, orient = tile_source.image_for_domain(bounds, zoom_level) if orient == 'lower': rgb = rgb[::-1] x0, x1, y0, y1 = extent l, b, r, t = bbox return RGB( rgb, bounds=(x0, y0, x1, y1), crs=ccrs.GOOGLE_MERCATOR, vdims=['R', 'G', 'B'], ).clone(datatype=['grid', 'xarray', 'iris'])[l:r, b:t]
def plot_cluster(ax, ride_cluster_bounding_box, ride_cluster, params): """ Given a list of rides and its bounding box, plots this cluster the matplotlib object <ax>, with satellite imagery as background """ tiler = GoogleTiles(style='satellite') mercator = tiler.crs fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection=mercator) bounding_box = [ ride_cluster_bounding_box["min_lon"], ride_cluster_bounding_box["max_lon"], ride_cluster_bounding_box["min_lat"], ride_cluster_bounding_box["max_lat"] ] ax.set_extent(bounding_box, crs=ccrs.PlateCarree()) logger.debug(f"Adding background image from Google with resolution level {params['resolution']}") ax.add_image(tiler, params['resolution']) for ride in ride_cluster: ride_longitudes = [coordinate[1] for coordinate in ride["coordinates"]] ride_latitudes = [coordinate[0] for coordinate in ride["coordinates"]] ax.plot( ride_longitudes, ride_latitudes, 'r-', alpha=params['alpha'], linewidth=params['linewidth'], transform=ccrs.PlateCarree() ) return ax
def get_gif(access_token: str, min_lon: float, max_lat: float, max_lon: float, min_lat: float, ratio: float, colour: str, backgroundColour: str, alpha: float, activity_type: str, bg_img: str, duration: int): activities = requests.get('https://www.strava.com/api/v3/activities' + '?access_token=' + access_token + '&per_page=200' + '&page=' + str(1)) activities = activities.json() # convert activities to pandas dataframe df = json_normalize(activities) # filter df by type of activity if activity_type == 'Run': df = df[df['type'] == 'Run'] elif activity_type == 'Ride': df = df[df['type'] == 'Ride'] else: df = df[(df['type'] == 'Run') | (df['type'] == 'Ride')] # filter df by start coordinates using the bounding box df_bbox = df[(df['start_latitude'] < max_lat) & (df['start_latitude'] > min_lat) & (df["start_longitude"] < max_lon) & (df["start_longitude"] > min_lon)] df_bbox = df_bbox.sort_values(by=['start_date']) # create imagery based on bg_img if bg_img == 'sat': imagery = GoogleTiles(style='satellite') elif bg_img == 'osm': imagery = OSM() else: imagery = OSM() # create figure to plot routes on fig = plt.figure(figsize=(8, ratio * 8), frameon=False) ax = fig.add_subplot(1, 1, 1, projection=imagery.crs) fig.patch.set_visible(False) ax.set_extent([min_lon, max_lon, min_lat, max_lat]) ax.set_axis_off() # filepaths fp_out = 'image.gif' imgs = [] for i in range(len(df_bbox)): try: lat, lng = zip( *polyline.decode(df_bbox.iloc[i]['map.summary_polyline'])) except: print(i) plt.plot(lng, lat, transform=ccrs.Geodetic(), color=colour, alpha=alpha) imgs.append(fig2img(fig)) # create background image if bg_img == 'none': bg = Image.new(mode='RGBA', size=imgs[0].size, color=ImageColor.getrgb(backgroundColour)) else: fig = plt.figure(figsize=(8, ratio * 8), frameon=False) ax = fig.add_subplot(1, 1, 1, projection=imagery.crs) ax.set_extent([min_lon, max_lon, min_lat, max_lat]) fig.patch.set_visible(False) ax.set_axis_off() # set background imagery if one was sent ax.add_image(imagery, 15) # converting background to image bg = fig2img(fig) imgs = map(lambda img: Image.alpha_composite(bg, img), imgs) bg.save(fp=fp_out, format='GIF', append_images=imgs, save_all=True, duration=duration, loop=0) file = open('image.gif', 'rb') return {'gif': base64.b64encode(file.read())}
def plot_map(gf, snwe, vectorFile=None, zoom=8): """Plot dinosar inventory on a static map. Parameters ---------- gf : GeoDataFrame A geopandas GeoDataFrame snwe : list bounding coordinates [south, north, west, east]. vectorFile: str path to region of interest polygon zoom: int zoom level for WMTS """ pad = 1 S, N, W, E = snwe plot_CRS = ccrs.PlateCarree() geodetic_CRS = ccrs.Geodetic() x0, y0 = plot_CRS.transform_point(W - pad, S - pad, geodetic_CRS) x1, y1 = plot_CRS.transform_point(E + pad, N + pad, geodetic_CRS) fig, ax = plt.subplots(figsize=(8, 8), dpi=100, subplot_kw=dict(projection=plot_CRS)) ax.set_xlim((x0, x1)) ax.set_ylim((y0, y1)) url = 'http://tile.stamen.com/terrain/{z}/{x}/{y}.png' tiler = GoogleTiles(url=url) # NOTE: going higher than zoom=8 is slow... ax.add_image(tiler, zoom) states_provinces = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='110m', facecolor='none') ax.add_feature(states_provinces, edgecolor='k', linestyle=':') ax.coastlines(resolution='10m', color='black', linewidth=2) ax.add_feature(cfeature.BORDERS) # Add region of interest polygon in specified if vectorFile: tmp = gpd.read_file(vectorFile) ax.add_geometries(tmp.geometry.values, ccrs.PlateCarree(), facecolor='none', edgecolor='m', lw=2, linestyle='dashed') orbits = gf.relativeOrbit.unique() colors = plt.cm.jet(np.linspace(0, 1, orbits.size)) for orbit, color in zip(orbits, colors): df = gf.query('relativeOrbit == @orbit') poly = df.geometry.cascaded_union if df.flightDirection.iloc[0] == 'ASCENDING': linestyle = '--' xpos, ypos = poly.centroid.x, poly.bounds[3] else: linestyle = '-' xpos, ypos = poly.centroid.x, poly.bounds[1] ax.add_geometries([poly], ccrs.PlateCarree(), facecolor='none', edgecolor=color, lw=2, linestyle=linestyle) ax.text(xpos, ypos, orbit, color=color, fontsize=16, fontweight='bold', transform=geodetic_CRS) gl = ax.gridlines(plot_CRS, draw_labels=True, linewidth=0.5, color='gray', alpha=0.5, linestyle='-') gl.xlabels_top = False gl.ylabels_left = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER plt.title('Orbital Footprints') plt.savefig('map.pdf', bbox_inches='tight')
import matplotlib.pyplot as plt import cartopy.crs as ccrs from cartopy.io.img_tiles import GoogleTiles fig = plt.figure(figsize=(10, 10)) google_tiles = GoogleTiles() ax = plt.axes(projection=google_tiles.crs) ax.set_extent((2.2, 2.5, 48.8, 48.93)) zoom = 12 ax.add_image(google_tiles, zoom) ax.scatter("longitude", "latitude", data=listing, s=1, transform=ccrs.PlateCarree()()), alpha = .1
def plotmap(flights, zoom=10, tracecolors=['black'], taskcolors=['Crimson'], aspectratio=None, terrain=False): ''' Plot one or more GliderFlight instances on a map. Arguments: * flights: A (list of) GliderFlight instance(s) * zoom: detail level of map image. 10 is recommended for large tasks, 12 for local (within gliding range of airfield) tasks * tracecolors: A (list of) colour(s) for the trace lines * taskcolors: A (list of) colour(s) for the task lines * aspectratio: float specifying aspect ration of map as width/height * terrain: boolean. False to plot OpenStreetMap map, True to plot Google terrain ''' if type(flights) is not list: flights = [flights] if type(taskcolors) is not list: taskcolors = [taskcolors] while len(taskcolors) < len(flights): taskcolors += taskcolors if type(tracecolors) is not list: tracecolors = [tracecolors] while len(tracecolors) < len(flights): tracecolors += tracecolors if terrain: tiler = GoogleTiles(style='terrain') else: tiler = MapboxTiles(mapboxkey, 'pirates') target_crs = tiler.crs ax = plt.axes(projection=target_crs) for flight, color1, color2 in zip(flights, taskcolors, tracecolors): if type(flight) is str: flight = GliderFlight(flight) if color1: flight.task.addtomap(ax, color1) flight.trace.addtomap(ax, color2) (minx, maxx, miny, maxy) = ax.get_extent(target_crs) # Add buffer space. buffer_size = 0.05 minx = minx - (maxx - minx) * buffer_size maxx = maxx + (maxx - minx) * buffer_size miny = miny - (maxy - miny) * buffer_size maxy = maxy + (maxy - miny) * buffer_size if aspectratio: oldratio = (maxx-minx)/(maxy-miny) if oldratio < aspectratio: newmaxx = (aspectratio * (maxy-miny) + maxx + minx) / 2.0 newminx = (maxx + minx - aspectratio * (maxy - miny)) / 2.0 newmaxy = maxy newminy = miny else: newmaxy = ((maxx-minx)/aspectratio + maxy + miny) / 2.0 newminy = (maxy + miny - (maxx - minx) / aspectratio) / 2.0 newmaxx = maxx newminx = minx ax.set_extent([newminx, newmaxx, newminy, newmaxy], crs=target_crs) ax.add_image(tiler, zoom, alpha=0.8, interpolation='spline36') print(ax.get_images()) if isinstance(tiler, MapboxTiles): ax.annotate('$\copyright$ Mapbox, $\copyright$ OpenStreetMap', xy=(2, 2), xycoords='axes points', fontsize='small') return ax
def gen_sat_map(df, place=False): ''' Takes pd.DataFrame of kayak session: `df`, and `place` kwarg. Prints shell notification. Sets figure size, map tile, and figure axes. Gets & sets map extent. Downloads map image. Uses `KMeans` Cluster Analysis to calculate clusters: n_clusters = 10 Rounds buoy placement coordinates to 6-figures of precision. Generates buoy placement pd.DataFrame: `df`. Sets lon & lat as x & y figure coordinates. Plots buoy locations. Writes buoy placement figure to file. Returns buoy placement pd.DataFrame: `df` ''' print("Downloading data and plotting map!") img = GoogleTiles( url='https://server.arcgisonline.com/ArcGIS/rest/services' '/World_Imagery/MapServer/tile/{z}/{y}/{x}.jpg') plt.figure(figsize=(100, 100)) ax = plt.axes(projection=img.crs) def gen_map_extent(df): ''' Takes pd.DataFrame: `df`. Finds the min & max of each axis. Calls `get_extent()` to get values. Returns the map extent coordinates as list: `extent`. ''' c = 0.05 min_x, max_x = min(df.lon), max(df.lon) min_y, max_y = min(df.lat), max(df.lat) def get_extent(min_num, max_num): ''' Takes a given axis's min & max values as floats. Calculates correct axis extent, regardless of hemisphere. Appends given axis extent floats to list: `extent`. ''' diff = max_num - min_num delta = (diff / min_num) * 100 if max_num > 0 and min_num > 0: __max__ = max_num + (c * delta) __min__ = min_num - (c * delta) elif max_num < 0 and min_num < 0: __max__ = max_num - (c * delta) __min__ = min_num + (c * delta) extent.append(__min__) extent.append(__max__) extent = list() get_extent(min_x, max_x) get_extent(min_y, max_y) return extent extent = gen_map_extent(df) ax.set_extent(extent) ax.add_image(img, 18) if place == True: locs = df.values kmeans = KMeans(n_clusters=10) kmeans.fit(locs) buoys = kmeans.cluster_centers_ r_buoys = buoys.round(6) df = pd.DataFrame(columns=['lat', 'lon'], data=r_buoys) x, y = df.lon, df.lat ax.plot(x, y, 'ro', markersize=35, transform=ccrs.Geodetic()) plt.savefig(f.name.strip(".gpx") + "_sites" + ".png", bbox_inches='tight') else: x, y = df.lon, df.lat ax.plot(x, y, transform=ccrs.Geodetic(), color='red', linewidth=5) plt.savefig("raw_map.png", bbox_inches='tight') return df
# <codecell> import matplotlib.pyplot as plt import cartopy.crs as ccrs from cartopy.io.img_tiles import GoogleTiles %matplotlib inline # <codecell> # Specify a region of interest, in this case, Sudelfeld Ski Resort (Germany) lat = 47 + 40 / 60.0 + 30 / 3600. lon = 12 + 3 / 60.0 + 2 / 3600. plt.figure(figsize=(10, 8)) ax = plt.subplot(111, projection=ccrs.PlateCarree()) ax.set_extent([12.0, 13.0, 47.0, 48.0]) gg_tiles = GoogleTiles() ax.add_image(gg_tiles, 10) plt.scatter(lon, lat, marker=(5, 1), color='red', s=200) plt.title("Welcome to Sudelfeld") gl = ax.gridlines(draw_labels=True,) gl.xlabels_top = False gl.ylabels_left = False # <codecell>
#!/usr/bin/env python # ====================================================================== # # Brad T. Aagaard, U.S. Geological Survey # # ====================================================================== """Test tile caching using GoogleTiles. """ import sys import matplotlib.pyplot as plt from cartopy.io.img_tiles import GoogleTiles sys.path.append("../cartopy_extra_tiles") from cached_tiler import CachedTiler tiler = CachedTiler(GoogleTiles(), cache_dir="~/data_scratch/images/tiles") ax = plt.axes(projection=tiler.crs) ax.set_extent([-123, -121.5, 37, 38.5]) ax.add_image(tiler, 8) plt.show() # End of file
def create_map(alert): ''' Create the alert map''' alert_map_info = (convert_geojson_to_geopandas_df(alert) if alert['geometry'] else calculate_ugc_geography(alert)) warning_cmap = { 'Flood Watch': '#2E8B57', 'Flash Flood Watch': '#2E8B57', 'Flash Flood Warning': '#8B0000', 'Flood Warning': '#00FF00', 'Coastal Flood Watch': '#66CDAA', 'Coastal Flood Warning': '#228B22', 'Severe Thunderstorm Watch': '#DB7093', 'Severe Thunderstorm Warning': '#FFA500', 'Special Weather Statement': '#FFE4B5', 'Tornado Watch': '#FFFF00', 'Tornado Warning': '#FF0000', 'Storm Surge Watch': '#DB7FF7', 'Storm Surge Warning': '#B524F7', 'Dense Fog Advisory': '#708090', 'Rip Current Statement': '#40E0D0', 'Red Flag Warning': '#FF1493' } google_tiles = GoogleTiles() data_crs = ccrs.PlateCarree() # Setup matplotlib figure fig = Figure(figsize=(1280 / 72, 720 / 72)) ax = fig.add_axes([0, 0, 1, 1], projection=data_crs) ax.add_image(google_tiles, 8) ax.set_extent([ alert_map_info['west_bound'] - 0.5, alert_map_info['east_bound'] + 0.5, alert_map_info['south_bound'] - 0.5, alert_map_info['north_bound'] + 0.6 ], data_crs) ax.set_adjustable('datalim') # Setup borders (states, countries, coastlines, etc) ax.add_feature(USCOUNTIES.with_scale('20m'), edgecolor='gray', zorder=5, linewidth=1.2) ax.add_feature(cfeature.STATES.with_scale('10m'), linewidth=3, zorder=5) # Add radar ax.add_wms( wms='https://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0q-t.cgi?', layers='nexrad-n0q-wmst', wms_kwargs={ 'transparent': True, 'time': get_radar_timestamp() }, zorder=4, alpha=0.4) # Plot alerts on the map for key in warning_cmap.keys(): if key == alert['properties']['event'] and alert['geometry']: ax.add_geometries(alert_map_info['polygon'], crs=data_crs, facecolor=warning_cmap[key], edgecolor='black', linewidth=4, zorder=6, alpha=0.04) elif key == alert['properties']['event'] and not alert['geometry']: for polys in alert_map_info['polygon']: ax.add_geometries(polys, crs=data_crs, facecolor=warning_cmap[key], edgecolor='black', linewidth=4, alpha=0.5, zorder=6) else: continue # Set title title = ('SIGNIFICANT WEATHER ALERT' if alert['properties']['event'] == 'Special Weather Statement' else alert['properties']['event'].upper()) ax.set_title(title, loc='left', ha='left', va='top', fontsize=48, color='white', fontweight='bold', fontname='Arial', y=0.96, x=0.03, zorder=11, bbox={ 'facecolor': '#0c3245', 'alpha': 1.0, 'edgecolor': 'none', 'boxstyle': 'square,pad=0.2' }) fig.savefig('alert_visual.png', dpi=72)
gps_points = df.loc[ df['topic'] == '/gps', 'data1':'data2'][target_times[1]:target_times[2]].values.tolist() print(gps_points) gps_path = rp.paths.ConstrainedPath(gps_points, time=gps_timestamps) gps_path.save('gps_path.json') utm_coords = np.array( [np.array(utm.from_latlon(lat, lon)[:2]) for lat, lon in gps_points]) mean_center = np.mean(utm_coords, axis=0) fig = plt.figure(figsize=(12, 12), dpi=100) imagery = GoogleTiles() data_crs = ccrs.UTM(17) ax = fig.add_subplot(1, 1, 1, projection=imagery.crs) extent_buffer = 80.0 bottom_left = mean_center - extent_buffer top_right = mean_center + extent_buffer extents = [bottom_left[0], top_right[0], bottom_left[1], top_right[1]] ax.set_extent(extents, crs=data_crs) ax.add_image(imagery, 18) #plt.plot(domain_boundary_coords[:,1], domain_boundary_coords[:,0], '-b', transform=ccrs.PlateCarree()) #plt.plot(planned_path_coords[:,1], planned_path_coords[:,0], '-g', transform=ccrs.PlateCarree()) plt.plot(utm_coords[:, 0], utm_coords[:, 1], '-r', transform=ccrs.UTM(17)) plt.show()