def interactive_map(self, doc_id, db_name): Gmap_API_key = 'AIzaSyBL5mv0DEHyXuopWAqQ532y_JuEACbqfko' # retrieve data from db data = self.retrieve_data(doc_id=doc_id, db_name=db_name) style_str = """[{"featureType":"all","elementType":"geometry.fill","stylers":[{"weight":"2.00"}]},{"featureType":"all","elementType":"geometry.stroke","stylers":[{"color":"#9c9c9c"}]},{"featureType":"all","elementType":"labels.text","stylers":[{"visibility":"on"}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2f2f2"}]},{"featureType":"landscape","elementType":"geometry.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"landscape.man_made","elementType":"geometry.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"poi","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"all","stylers":[{"saturation":-100},{"lightness":45}]},{"featureType":"road","elementType":"geometry.fill","stylers":[{"color":"#eeeeee"}]},{"featureType":"road","elementType":"labels.text.fill","stylers":[{"color":"#7b7b7b"}]},{"featureType":"road","elementType":"labels.text.stroke","stylers":[{"color":"#ffffff"}]},{"featureType":"road.highway","elementType":"all","stylers":[{"visibility":"simplified"}]},{"featureType":"road.arterial","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"all","stylers":[{"color":"#46bcec"},{"visibility":"on"}]},{"featureType":"water","elementType":"geometry.fill","stylers":[{"color":"#c8d7d4"}]},{"featureType":"water","elementType":"labels.text.fill","stylers":[{"color":"#070707"}]},{"featureType":"water","elementType":"labels.text.stroke","stylers":[{"color":"#ffffff"}]}]""" AUS_BOUND_BOX = (113.338953078, -43.6345972634, 153.569469029, -10.6681857235) map_options = GMapOptions(lat=-28.7, lng=133.9, map_type="terrain", zoom=4, styles=style_str) plot = GMapPlot(map_options=map_options, api_key=Gmap_API_key, plot_height=450, plot_width=666) # h:573 w:925 for each in data['data']: if AUS_BOUND_BOX[0] <= each['coordinates'][0] <= AUS_BOUND_BOX[2] and \ AUS_BOUND_BOX[1] <= each['coordinates'][1] <= AUS_BOUND_BOX[3]: if each['sentiment'] >= 0.05: circle = Circle(x=each['coordinates'][0], y=each['coordinates'][1], size=5, fill_color='green') plot.add_glyph(circle) elif -0.05 < each['sentiment'] < 0.05: circle = Circle(x=each['coordinates'][0], y=each['coordinates'][1], size=5, fill_color='blue') plot.add_glyph(circle) elif each['sentiment'] <= -0.05: circle = Circle(x=each['coordinates'][0], y=each['coordinates'][1], size=5, fill_color='red') plot.add_glyph(circle) # add interactive tools pan = PanTool() wheel_zoom = WheelZoomTool() reset = ResetTool() save = SaveTool() plot.add_tools(pan, wheel_zoom, reset, save) # interactive Hover -- to be added script_map, div_map = components(plot) return script_map, div_map
def create_plot(center_coords, zoom_level=8): x_range = Range1d() y_range = Range1d() # JSON style string taken from: https://snazzymaps.com/style/1/pale-dawn map_options = GMapOptions(lat=center_coords['lat'], lng=center_coords['lng'], map_type="roadmap", zoom=zoom_level, styles=""" [{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"on"},{"lightness":33}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2e5d4"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#c5dac6"}]},{"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]},{"featureType":"road","elementType":"all","stylers":[{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#c5c6c6"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#e4d7c6"}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#fbfaf7"}]},{"featureType":"water","elementType":"all","stylers":[{"visibility":"on"},{"color":"#acbcc9"}]}] """) plot = GMapPlot(x_range=x_range, y_range=y_range, map_options=map_options, title=u"Тверь") pan = PanTool() wheel_zoom = WheelZoomTool() box_select = BoxSelectTool() plot.add_tools(pan, wheel_zoom, box_select) return plot
def trail_map(data): lon = (min(data.lon) + max(data.lon)) / 2 lat = (min(data.lat) + max(data.lat)) / 2 map_options = GMapOptions(lng=lon, lat=lat, zoom=13) plot = GMapPlot(plot_width=800, plot_height=800, map_options=map_options, api_key=API_KEY) plot.title.text = "%s - Trail Map" % name plot.x_range = Range1d() plot.y_range = Range1d() plot.add_tools(PanTool(), WheelZoomTool(), ResetTool()) line_source = ColumnDataSource(dict(x=data.lon, y=data.lat, dist=data.dist)) line = Line(x="x", y="y", line_color="blue", line_width=2) plot.add_glyph(line_source, line) if plot.api_key == "GOOGLE_API_KEY": plot.add_layout( Label(x=240, y=700, x_units='screen', y_units='screen', text='Replace GOOGLE_API_KEY with your own key', text_color='red')) return plot
def create_map_plot(self): lat=39.8282 lng=-98.5795 zoom=6 xr = Range1d() yr = Range1d() x_range = xr y_range = yr #map_options = GMapOptions(lat=39.8282, lng=-98.5795, zoom=6) map_options = GMapOptions(lat=lat, lng=lng, zoom=zoom) #map_options = GMapOptions(lat=30.2861, lng=-97.7394, zoom=15) plot = GMapPlot( x_range=x_range, y_range=y_range, map_options=map_options, plot_width=680, plot_height=600, title=" " ) plot.map_options.map_type="hybrid" xaxis = LinearAxis(axis_label="lon", major_tick_in=0, formatter=NumeralTickFormatter(format="0.000")) plot.add_layout(xaxis, 'below') yaxis = LinearAxis(axis_label="lat", major_tick_in=0, formatter=PrintfTickFormatter(format="%.3f")) plot.add_layout(yaxis, 'left') self.plot = plot
def create_map(tab_del_file): """ This function was adapted from bokeh tutorial, so it might have similar elements in it. """ data = pandas.read_csv(tab_del_file, sep="\\t", engine='python') lat_mean = data["Lat"].mean() long_mean = data["Long"].mean() map_options = GMapOptions(lat=lat_mean, lng=long_mean, map_type="hybrid", zoom=5) plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, title="PopART-XTREME" ) source = ColumnDataSource(data=dict(lat=[x for x in data["Lat"]], lon=[y for y in data["Long"]], name=[s for s in data["Sequence"]], local=[l for l in data["Locality"]])) circle = Circle(x="lon", y="lat", size=15, fill_color="blue", fill_alpha=0.8, line_color=None) tooltips = [("Sequence", "@name"), ("Locality", "@local")] render = plot.add_glyph(source, circle) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool(), BoxZoomTool(), PreviewSaveTool(), HoverTool(tooltips=tooltips, renderers=[render])) output_file("map_plot.html") show(plot)
def create_plot(center_coords,zoom_level = 8): x_range = Range1d() y_range = Range1d() # JSON style string taken from: https://snazzymaps.com/style/1/pale-dawn map_options = GMapOptions(lat=center_coords['lat'], lng=center_coords['lng'], map_type="roadmap", zoom=zoom_level, styles=""" [{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"on"},{"lightness":33}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2e5d4"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#c5dac6"}]},{"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]},{"featureType":"road","elementType":"all","stylers":[{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#c5c6c6"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#e4d7c6"}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#fbfaf7"}]},{"featureType":"water","elementType":"all","stylers":[{"visibility":"on"},{"color":"#acbcc9"}]}] """) plot = GMapPlot( x_range=x_range, y_range=y_range, map_options=map_options, title="Austin" ) # source = ColumnDataSource( # data=dict( # lat=[30.2861, 30.2855, 30.2869], # lon=[-97.7394, -97.7390, -97.7405], # fill=['orange', 'blue', 'green'] # ) # ) # circle = Circle(x="lon", y="lat", size=15, fill_color="fill", line_color="black") # plot.add_glyph(source, circle) pan = PanTool() wheel_zoom = WheelZoomTool() box_select = BoxSelectTool() plot.add_tools(pan, wheel_zoom, box_select) return plot
class GoogleMapPlot: def __init__(self, api_key, lat, long, type, zoom): map_options = GMapOptions(lat=lat, lng=long, map_type=type, zoom=zoom) self.plot = GMapPlot(api_key=api_key, x_range=Range1d(), y_range=Range1d(), map_options=map_options, width=1000, height=600, toolbar_location="above") self.layout = column(self.plot) def show(self): curdoc().add_root(self.layout) def draw_points_with_circle_glyph(self, data, attrs): data = ColumnDataSource(data=dict( lat=[x[0] for x in data], long=[x[1] for x in data], )) defaults = { 'x': 'long', 'y': 'lat', 'size': 2, 'fill_color': 'blue', 'fill_alpha': 0.8, 'line_color': None } defaults.update(attrs) circle = Circle(**defaults) self.plot.add_glyph(data, circle) return data def update(self, source, data): source.data = dict( lat=[x[0] for x in data], long=[x[1] for x in data], ) def add_slider(self, min, max, step, init, title, callback=None): slider = Slider(start=min, end=max, value=init, step=step, title=title) slider.on_change('value', self.slider_handler_callback) self.slider_callback = callback self.layout = column(self.plot, widgetbox(slider)) def slider_handler_callback(self, attr, old, new): if hasattr(self, 'slider_callback') and self.slider_callback is not None: self.slider_callback(new)
def createMap(data, selectorColumn='MetricName'): # unique names ops = list(data[selectorColumn].unique()) # data msk = data[selectorColumn] == ops[0] source = ColumnDataSource(data=dict(lat=data['Latitude'][msk], lon=data['Longitude'][msk], disp=data['DisplayName'][msk], metric=data['MetricName'][msk], name=data['OrganisationName'][msk], value=data['Value'][msk])) all = {} for o in ops: msk = data[selectorColumn] == o all[o] = dict(lat=data['Latitude'][msk], lon=data['Longitude'][msk], disp=data['DisplayName'][msk], metric=data['MetricName'][msk], name=data['OrganisationName'][msk], value=data['Value'][msk]) all = ColumnDataSource(all) # create figure bk.output_file("MetricsMap.html", mode="cdn") fig = GMapPlot(plot_width=800, plot_height=700, logo=None, x_range=Range1d(), y_range=Range1d(), map_options=GMapOptions(lat=53.4808, lng=-1.2426, zoom=7), api_key='AIzaSyBQH3HGn6tpIrGxekGGRAVh-hISYAPsM78') fig.map_options.map_type = "roadmap" fig.title.text = "Performance Metrics" # hovering information hover = HoverTool(tooltips=[("Name", "@name"), ("Metrics", "@metric"), ("Value", "@value")]) # add tools fig.add_tools(PanTool(), BoxZoomTool(), WheelZoomTool(), hover) # add data circle = Circle(x="lon", y="lat", size=5, fill_color="blue", fill_alpha=0.8, line_color=None) fig.add_glyph(source, circle) # create callback callback = CustomJS(args=dict(source=source), code=""" var f = cb_obj.get('value'); var d = all.get('data')[f]; source.set('data', d); source.trigger('change'); """) callback.args["source"] = source callback.args["all"] = all # Set up widgets select = Select(title="Select", value=ops[0], options=ops, callback=callback) # show the map bk.show(row(select, fig))
def main_map(self): #code for main page map for i in range(len(self.titles)): self.data_dict[self.titles[i]]=self.color_dict[i] for k in self.topics: if k in self.data_dict: self.color_main.append(self.data_dict[k]) map_options = GMapOptions(lat=23.3468, lng=78.5827, map_type='roadmap', zoom=5) my_hover = HoverTool() plot = GMapPlot(x_range=Range1d(), y_range=Range1d(), map_options=map_options) plot.title.text = "Tweet Data Analysis" plot.api_key = "AIzaSyAcvz_u0fGAyBE13pAnntsA1fn7Tu54RTU" source = ColumnDataSource(data=dict(lat=self.coord_x,lon=self.coord_y,colors=self.color_main[:len(self.coord_x)],tp=self.topics,tw=self.tweets)) my_hover.tooltips = [('Topic','@tp'),('Tweet','@{tw}')] circle = Circle(x="lon", y="lat", size=8, fill_color="colors", fill_alpha=0.7, line_color=None) plot.add_glyph(source, circle) plot.add_tools(my_hover) plot.add_tools( WheelZoomTool(), PanTool(), ResetTool()) output_file("F:\Final Year Project\Visualization\Website\static\main_page\map.html") save(obj=plot, filename="F:\Final Year Project\Visualization\Website\static\main_page\map.html")
def __init__(self, api_key, lat, long, type, zoom): map_options = GMapOptions(lat=lat, lng=long, map_type=type, zoom=zoom) self.plot = GMapPlot(api_key=api_key, x_range=Range1d(), y_range=Range1d(), map_options=map_options, width=1000, height=600, toolbar_location="above") self.layout = column(self.plot)
def create_heatmap(station_scores, plot_width=1000, plot_height=600): map_options = GMapOptions(lat=32.06, lng=34.87, map_type="roadmap", zoom=9) cmap = plt.get_cmap('jet') plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, title="Israel") plot.plot_width = plot_width plot.plot_height = plot_height lat_vec = list(map(lambda x: get_loc_by_id(x).lat, station_scores.keys())) lon_vec = list(map(lambda x: get_loc_by_id(x).lon, station_scores.keys())) for ind, station in enumerate(station_scores): source = ColumnDataSource(data=dict( lat=[lat_vec[ind]], lon=[lon_vec[ind]], )) cmap_indx = int(station_scores[station] * cmap.N) cmap_val = tuple(np.floor(255 * np.array(cmap(cmap_indx)[:3]))) circle = Circle(x="lon", y="lat", size=17, fill_color=cmap_val, fill_alpha=0.95, line_color=None) plot.add_glyph(source, circle) plot.add_tools(PanTool(), WheelZoomTool()) output_file("Mean Time to Tel-Aviv Hashalom.html") show(plot)
def plot_map(df, bs_latlong=None, bs=None, map_type="satellite", colorby='rssi'): map_options = GMapOptions(lat=.5*(df.latitude.min()+ df.latitude.max()), lng=.5*(df.longitude.min()+df.longitude.max()), map_type=map_type, zoom=11) plot = GMapPlot( x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options ) plot.title.text = "Test_API_Google" # For GMaps to function, Google requires you obtain and enable an API key: # # https://developers.google.com/maps/documentation/javascript/get-api-key # # Replace the value below with your personal API key: plot.api_key = "AIzaSyBn534zSTjx4L7l7yoklDismI0QXMiZSA8" normalize = (df[colorby] - df[colorby].min())/(df[colorby].max() - df[colorby].min()) source = ColumnDataSource( data=dict( lat=df.latitude, lon=df.longitude, color=[cm.colors.to_hex(c) for c in cm.jet(normalize)[:,:-1]] ) ) circle = Circle(x="lon", y="lat", size=3, fill_color="color", fill_alpha=0.8, line_color=None) plot.add_glyph(source, circle) if (bs is not None) & (bs_latlong is not None): bs = ColumnDataSource( data=dict( lat=np.array(bs_latlong[bs]['lat']).reshape(1,), lon=np.array(bs_latlong[bs]['long']).reshape(1,) ) ) circlebs = Square(x="lon", y="lat", size=9, fill_color="red", fill_alpha=0.8, line_color=None) plot.add_glyph(bs, circlebs) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool()) output_file("gmap_plot.html") show(plot)
def generate_heatmap(): #take date range from user input start_date_range = datetime.datetime.strptime(request.form['start_date'], "%Y-%m-%d").date() end_date_range = datetime.datetime.strptime(request.form['stop_date'], "%Y-%m-%d").date() #calls method to get Pandas data frame within given date range. #df = get_dataframe(start_date_range, end_date_range) #reads the data frame and stores the latitudes and longitudes for the #start stations and the end stations start_lats = pd.Series(df_init['start_station_latitude']).unique() start_long = pd.Series(df_init['start_station_longitude']).unique() small_occurrences = [] occurrences = df_init['start_station_latitude'].value_counts(sort=False) print len(occurrences) minimum = min(occurrences) #scaling to ensure 'blobs' will always be viewable on the map of NYC for o in occurrences: o /= (minimum * 2) small_occurrences.append(o) #Maps out an area of NYC based on the coordinates. Zoom=12 giving issue map_options = GMapOptions(lat=40.741557, lng=-73.990467, map_type="roadmap", zoom=11) #set the data to displayed on the map: latitudes, longitudes and occurences plot = GMapPlot( x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, title="NYC Baby" ) source = ColumnDataSource( data=dict( lat=start_lats, lon=start_long, sizes=small_occurrences, )) #choose the type of shape to plot, size is set to the number of occurrences circle = Circle(x="lon", y="lat", size='sizes', fill_color="blue", fill_alpha=1.8, line_color=None) #adding the plot and tools to the plot plot.add_glyph(source, circle) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool()) #return to the template scriptb, divb = components(plot) return render_template('heatmap.html', d1=start_date_range, d2=end_date_range, scriptb=scriptb, divb=divb)
def getHTML(self, params): df = self.getData(params) df.columns = ['lat','lon','value'] x_range = Range1d() y_range = Range1d() map_options = GMapOptions(lat=39.0, lng=-98.0, map_type="roadmap", zoom=5, styles=""" [{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"on"},{"lightness":33}]}, {"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2e5d4"}]}, {"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#c5dac6"}]}, {"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]}, {"featureType":"road","elementType":"all","stylers":[{"lightness":20}]}, {"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#c5c6c6"}]}, {"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#e4d7c6"}]}, {"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#fbfaf7"}]}, {"featureType":"water","elementType":"all","stylers":[{"visibility":"on"},{"color":"#acbcc9"}]}] """) pallete = ['#c1f1fe', '#85e3fd', '#5fd7f9', '#41b6fb', '#4254ff'] lats, lons = df['lat'].values, df['lon'].values bucket = (max(df['value']) - min(df['value'])) / 5 color_map = (df['value'] - min(df['value'])).apply(lambda x: min(int(x / bucket), 4)).tolist() colors = [pallete[x] for x in color_map] plot = GMapPlot( x_range=x_range, y_range=y_range, map_options=map_options, title="Historical Weather", plot_width=1350, plot_height=800 ) weather_source = ColumnDataSource( data=dict( lat=lats, lon=lons, fill=colors ) ) weather_circle = Circle(x="lon", y="lat", size=6, fill_color="fill", line_color=None, fill_alpha=0.2) plot.add_glyph(weather_source, weather_circle) pan = PanTool() wheel_zoom = WheelZoomTool() box_select = BoxSelectTool() # hover = HoverTool() plot.add_tools(pan, wheel_zoom, box_select) script, div = components(plot, CDN) html = "%s\n%s" % (script, div) return html
def plotMap(data): # output to static HTML file output_file("map.html", title="map example") p = GMapPlot( x_range=Range1d(-160, 160), y_range=Range1d(-80, 80), plot_width=1000,plot_height=500, map_options=GMapOptions(lat=42.55, lng=1.533, zoom=2), title="Cities with more than 5,000 people", webgl=True, responsive=True) print data circle = Circle(x="lng", y="lat", size=5, line_color=None, fill_color='firebrick', fill_alpha=0.3) #circle = Circle(x="LON", y="LAT", size=5, line_color=None, fill_color='firebrick', fill_alpha=0.3) #print ColumnDataSource(data) p.add_glyph(ColumnDataSource(data), circle) #p.add_tools(PanTool(), WheelZoomTool()) show(p)
def create_plot(fn): output_file(fn+'.html',title='Austin Home Prices') map_options = GMapOptions(lat=30.29, lng=-97.73, map_type="roadmap", zoom=11) plot = GMapPlot( x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, title="Austin", api_key='AIzaSyDfPR-VHUVIr3veDt-GKNZOpHyew6TER6Q' ) return plot
def bokeh_draw(lat, lon, callsign, t): m = GMapOptions(lat=25.084, lng=121.23, map_type="roadmap", zoom=14) plot = GMapPlot(x_range=Range1d(), y_range=Range1d(), map_options=m) plot.title.text = t plot.api_key = "AIzaSyCa4x7OjPPqH9Jt9_EFHbISoUZo6cRIo7Q " source = ColumnDataSource( data=dict( lat=lat, lon=lon, callsign=callsign, )) circle = Circle( x='lon', y='lat', size=4, fill_color="red", fill_alpha=0.8, line_color=None) plot.add_glyph(source, circle) labels = LabelSet( x='lon', y='lat', text='callsign', text_font_size='8pt', level='glyph', x_offset=1, y_offset=1, source=source, render_mode='canvas') plot.add_layout(labels) export_png(plot, filename='screenshots/' + t + '.png')
def hurricane_map_plot(): map_options = GMapOptions(lat=28.906000137329102, lng=-78.471000671386719, map_type="roadmap", zoom=3) plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options) plot.title.text = "Hurricane Kate" # For GMaps to function, Google requires you obtain and enable an API key: plot.api_key = API_KEY lat = list(df['latitude'].values) lon = list(-df['longitude'].values) colors = ['b'] * len(lat) buoy_lat = df_buoy.iloc[0]['latitude'] buoy_lon = df_buoy.iloc[0]['longitude'] source = ColumnDataSource(data=dict( lat=lat, lon=lon, )) source2 = ColumnDataSource(data=dict( lat=[buoy_lat], lon=[buoy_lon], )) circle = Circle(x="lon", y="lat", size=15, fill_color="blue", fill_alpha=0.8, line_color=None) plot.add_glyph(source, circle) circle2 = Circle(x="lon", y="lat", size=15, fill_color="red", fill_alpha=0.8, line_color=None) plot.add_glyph(source2, circle2) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool()) script, div = components(plot) return div, script
def create_heatmap(station_scores, plot_width=1000, plot_height=600): map_options = GMapOptions(lat=32.06, lng=34.87, map_type="roadmap", zoom=9) cmap = plt.get_cmap('jet') plot = GMapPlot( x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, title="Israel" ) plot.plot_width = plot_width plot.plot_height = plot_height lat_vec = list(map(lambda x: get_loc_by_id(x).lat, station_scores.keys())) lon_vec = list(map(lambda x: get_loc_by_id(x).lon, station_scores.keys())) for ind, station in enumerate(station_scores): source = ColumnDataSource( data=dict( lat=[lat_vec[ind]], lon=[lon_vec[ind]], ) ) cmap_indx = int(station_scores[station]*cmap.N) cmap_val = tuple(np.floor(255 * np.array(cmap(cmap_indx)[:3]))) circle = Circle(x="lon", y="lat", size=17, fill_color=cmap_val, fill_alpha=0.95, line_color=None) plot.add_glyph(source, circle) plot.add_tools(PanTool(), WheelZoomTool()) output_file("Mean Time to Tel-Aviv Hashalom.html") show(plot)
def plotHTML(location, latlongDict): ''' :param location: given a location & a dictionary of vicinity lat-longs of categories, this function will calculate bokeh map seperating the main locatin ( address) and the other vicinity based on the input and creates a object ( script & tag html ) of the chart which is rendered on the front end. :param latlongDict: :return: ''' print("Found : {0} latitudes".format(len(latlongDict["latarr"]))) print("Found : {0} longitudes".format(len(latlongDict["longarr"]))) map_options = GMapOptions(lat=location.latitude, lng=location.longitude, map_type="roadmap", zoom=15) plot = GMapPlot( x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, title="Austin" ) source = ColumnDataSource( data=dict( lat=latlongDict["latarr"], lon=latlongDict["longarr"], )) # print([location.latitude,latlongDict["latarr"]]) circle = Circle(x="lon", y="lat", size=10, fill_color="blue", fill_alpha=0.8, line_color=None) plot.add_glyph(source, circle) source = ColumnDataSource( data=dict( lat=[location.latitude], lon=[location.longitude], )) circle = Circle(x="lon", y="lat", size=15, fill_color="red", fill_alpha=0.8, line_color=None) plot.add_glyph(source, circle) plot.add_tools(PanTool(), BoxSelectTool(), BoxZoomTool()) # return file_html(plot, CDN, "my plot") return (components(plot, CDN)) # Will return a (script, tag)
def getHTML(self,params): df = self.getData(params) self.graph_type = params['graph_type'] df = df.ix[df['hot'] > self.graph_type,:] x_range = Range1d() y_range = Range1d() map_options = GMapOptions(lat=39.0, lng=-98.0, map_type="roadmap", zoom=5, styles=""" [{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"on"},{"lightness":33}]}, {"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2e5d4"}]}, {"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#c5dac6"}]}, {"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]}, {"featureType":"road","elementType":"all","stylers":[{"lightness":20}]}, {"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#c5c6c6"}]}, {"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#e4d7c6"}]}, {"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#fbfaf7"}]}, {"featureType":"water","elementType":"all","stylers":[{"visibility":"on"},{"color":"#acbcc9"}]}] """) lats, lons = df['lat'].values, df['lon'].values plot = GMapPlot( x_range=x_range, y_range=y_range, map_options=map_options, title="Historical Weather", plot_width=1350, plot_height=800 ) weather_source = ColumnDataSource( data=dict( lat=lats, lon=lons, fill=['purple']*len(lats) ) ) weather_circle = Circle(x="lon", y="lat", size=6, fill_color="fill", line_color=None, fill_alpha=0.2) plot.add_glyph(weather_source, weather_circle) pan = PanTool() wheel_zoom = WheelZoomTool() box_select = BoxSelectTool() # hover = HoverTool() plot.add_tools(pan, wheel_zoom, box_select) script, div = components(plot, CDN) html = "%s\n%s"%(script, div) return html
def PlotMap(data_, bs=None, map_type="roadmap"): data = data_.sample(5000) lat_min, lat_max = data.latitude.min(), data.latitude.max() lon_min, lon_max = data.longitude.min(), data.longitude.max() map_options = GMapOptions(lat=.5 * (lat_min + lat_max), lng=.5 * (lon_min + lon_max), map_type=map_type, zoom=9) plot = GMapPlot(x_range=Range1d(), y_range=Range1d(), map_options=map_options) plot.title.text = "Visualisation des données" # For GMaps to function, Google requires you obtain and enable an API key: # # https://developers.google.com/maps/documentation/javascript/get-api-key # # Replace the value below with your personal API key: # plot.api_key = "AIzaSyDthyCGiKTxBwB7JUA0FP0g3cjGhWWPuC4" plot.api_key = "AIzaSyD-n_DViUNpTmYRgb2JCsC_gIHXpUMyMhQ" source = ColumnDataSource(data=dict( lat=data.latitude, lon=data.longitude, )) if bs is not None: bs = ColumnDataSource(data=dict( lat=bs.lat, lon=bs.lng, )) patch = Square(x="lon", y="lat", size=7, fill_color="yellow", fill_alpha=1, line_color=None) plot.add_glyph(bs, patch) circle = Circle(x="lon", y="lat", size=2, fill_color="red", fill_alpha=.3, line_color=None) plot.add_glyph(source, circle) #@TODO change output file to notebook (no writing to html) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool()) output_file("gmap_.html") show(plot)
def create_map_plot(self): lat=39.8282 lng=-98.5795 zoom=6 xr = Range1d() yr = Range1d() x_range = xr y_range = yr #map_options = GMapOptions(lat=39.8282, lng=-98.5795, zoom=6) map_options = GMapOptions(lat=lat, lng=lng, zoom=zoom) #map_options = GMapOptions(lat=30.2861, lng=-97.7394, zoom=15) plot = GMapPlot( x_range=x_range, y_range=y_range, map_options=map_options, title = "Hotel Review Explorer", plot_width=680, plot_height=600 ) plot.map_options.map_type="hybrid" xaxis = LinearAxis(axis_label="lon", major_tick_in=0, formatter=NumeralTickFormatter(format="0.000")) plot.add_layout(xaxis, 'below') yaxis = LinearAxis(axis_label="lat", major_tick_in=0, formatter=PrintfTickFormatter(format="%.3f")) plot.add_layout(yaxis, 'left') #pan = PanTool() #wheel_zoom = WheelZoomTool() #box_select = BoxSelectTool() #box_select.renderers = [rndr] #tooltips = "@name" #tooltips = "<span class='tooltip-text'>@names</span>\n<br>" #tooltips += "<span class='tooltip-text'>Reviews: @num_reviews</span>" #hover = HoverTool(tooltips="@num_reviews") #hover = HoverTool(tooltips="@names") #hover = HoverTool(tooltips=tooltips) #tap = TapTool() #plot.add_tools(pan, wheel_zoom, box_select, hover, tap) #plot.add_tools(hover, tap) #overlay = BoxSelectionOverlay(tool=box_select) #plot.add_layout(overlay) #plot.add_glyph(self.source, circle) #county_xs, county_ys = get_some_counties() #apatch = Patch(x=county_xs, y=county_ys, fill_color=['white']*len(county_xs)) #plot.add_glyph(apatch) self.plot = plot
def cities_visualization(): scale = 5 lat_tpl=() long_tpl=() cities_tpl=() ''' create a dataframe without null row or column values ''' halfComplete_dataFrame= df1[df1['City, State'].str.contains(',', na=False)] cities_dataFrame=pd.DataFrame(halfComplete_dataFrame['City, State']) cities_dataFrame=cities_dataFrame.rename(columns={'City, State':'City'}) top_cities_dataFrame=cities_dataFrame.groupby(['City']).size().reset_index().rename(columns={0:'count'}) top_ten_cities_dataFrame=top_cities_dataFrame.sort_values(by='count', ascending=False).head(10) geolocator = Nominatim() lat_long_list=[] for row in top_ten_cities_dataFrame['City']: topTenCitiesList.append(str(row)) #print topTenCitiesList for row in top_ten_cities_dataFrame['count']: topTenCitiesCount.append(row) #print topTenCitiesCount for i,val in enumerate(topTenCitiesList): loc=geolocator.geocode(val) #cities_tpl=cities_tpl+(val,) #long_tpl=long_tpl+(loc.longitude,) #lat_tpl=lat_tpl+(loc.latitude,) city_lat_list.append(loc.latitude) city_long_list.append(loc.longitude) #print topTenCitiesList #print topTenCitiesCount #print city_lat_list #print city_long_list #print cities_tpl map_options = GMapOptions(lat=39.8282, lng=-98.5795, map_type="roadmap", zoom=5) plot = GMapPlot( x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, plot_width=1100, plot_height=800) plot.title.text = "Top ten cities" plot.api_key = "AIzaSyBfcQ8lTsXC5du_Mj0IyFLuXepDt_Euawo" source = ColumnDataSource( data=dict( lat=city_lat_list, lon=city_long_list, #text=topTenCitiesList, )) circle = Circle(x="lon", y="lat", tags=topTenCitiesList, size=15, fill_color="blue", fill_alpha=0.8, line_color=None) plot.add_glyph(source, circle) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool()) output_file("gmap_plot.html") show(plot)
def plot_gmap(zones, trips=None, **map_options): """Plot zones over a Google Map. Examples: - plot_gmap(['Astoria', 'Manhattan'], zoom=12) - plot_gmap(['Astoria', 'Midtown', 'Greenpoint', 'Sunnyside', 'Harlem']) """ # Gather zone data polygons = [ GeoJSONDataSource(geojson=json.dumps(load_geojson(z))) for z in zones ] u = unary_union([load_geojson(z, make_shape=True) for z in zones]) m_polygons = u.centroid plot = GMapPlot( api_key=GOOGLE_API_KEY, x_range=Range1d(), y_range=Range1d(), map_options=GMapOptions( lat=m_polygons.y, lng=m_polygons.x, map_type="roadmap", **map_options, ), ) plot.toolbar.logo = None plot.toolbar_location = "above" plot.title.text = None # Toolbar wheel_zoom = WheelZoomTool() plot.add_tools( PanTool(), BoxZoomTool(), BoxSelectTool(), wheel_zoom, ZoomInTool(), ZoomOutTool(), ResetTool(), SaveTool(), ) plot.toolbar.active_scroll = wheel_zoom # Add neighborhood polygons for geo_source in polygons: glyph = Patches(xs="xs", ys="ys", fill_color="Blue", fill_alpha=0.2) plot.add_glyph(geo_source, glyph) # Add trips if trips is not None: add_trips_to_plot(plot, trips) output_file("plots/plot.html") show(plot) return plot
def time_select(): val = slider.value print(val) data = getChosenData(1, val, sYDir, sDir) sLat, sLon, sTemp = plotFormat(data) print(len(data)) #plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, api_key = "AIzaSyATf-qiN-NRPnEUchZqGHEjPUYESAdjavY") #plot.title.text = "Queensland" map_options = GMapOptions(lat=-23, lng=144, map_type="roadmap", zoom=5) source.data = dict( lat=sLat, lon=sLon, ) plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, api_key = "AIzaSyATf-qiN-NRPnEUchZqGHEjPUYESAdjavY") plot.add_glyph(source, circle) #circle = Circle(x="lon", y="lat", size=15, fill_color="blue", fill_alpha=0.8, line_color=None) #plot.add_glyph(source, circle) #source.trigger('data', source.data, source.data) return
def google(): print("Working") # sys.exit(0) coords = (35.383, 24.606) coords_2 = (35.22, 24.36) map_options = GMapOptions(lat=coords_2[0], lng=-coords_2[1], map_type="roadmap", zoom=5) plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options) plot.title.text = "Looking for the map" # For GMaps to function, Google requires you obtain and enable an API key: # # https://developers.google.com/maps/documentation/javascript/get-api-key # # Replace the value below with your personal API key: plot.api_key = "AIzaSyBbO8RFHc9EC1DKSkUCrT3LiwSVD0lwFBk" source = ColumnDataSource(data=dict( lat=[coords[0]], lon=[coords[1]], )) circle = Circle(x="lon", y="lat", size=55, fill_color="red", fill_alpha=0.8, line_color=None) # plot.add_glyph(source, circle) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool()) output_file("gmap_plot.html") show(plot)
def plotthis(): map_options = GMapOptions(lat=67.97, lng=-97.73, map_type="roadmap", zoom=2) plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, title="Runners IOS") df = pd.read_csv("runners.csv") df = df.dropna() df = df.head(500) source = ColumnDataSource(data=dict( lat=df["start_latitude"], lon=df["start_longitude"], )) #source = ColumnDataSource( data=dict(lat=[30.29, 30.20, 30.29],lon=[-97.70, -97.74, -97.78],)) circle = Circle(x="lon", y="lat", size=15, fill_color="blue", fill_alpha=0.8, line_color=None) plot.add_glyph(source, circle) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool()) output_file("gmap_plot.html") show(plot)
def create_map_plot(self): lat = 39.8282 lng = -98.5795 zoom = 6 xr = Range1d() yr = Range1d() x_range = xr y_range = yr #map_options = GMapOptions(lat=39.8282, lng=-98.5795, zoom=6) map_options = GMapOptions(lat=lat, lng=lng, zoom=zoom) #map_options = GMapOptions(lat=30.2861, lng=-97.7394, zoom=15) plot = GMapPlot(x_range=x_range, y_range=y_range, map_options=map_options, plot_width=680, plot_height=600, title=" ") plot.map_options.map_type = "hybrid" xaxis = LinearAxis(axis_label="lon", major_tick_in=0, formatter=NumeralTickFormatter(format="0.000")) plot.add_layout(xaxis, 'below') yaxis = LinearAxis(axis_label="lat", major_tick_in=0, formatter=PrintfTickFormatter(format="%.3f")) plot.add_layout(yaxis, 'left') self.plot = plot
def create_plot(center_coords,zoom_level = 8): x_range = Range1d() y_range = Range1d() # JSON style string taken from: https://snazzymaps.com/style/1/pale-dawn map_options = GMapOptions(lat=center_coords['lat'], lng=center_coords['lng'], map_type="roadmap", zoom=zoom_level, styles=""" [{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"on"},{"lightness":33}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2e5d4"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#c5dac6"}]},{"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]},{"featureType":"road","elementType":"all","stylers":[{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#c5c6c6"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#e4d7c6"}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#fbfaf7"}]},{"featureType":"water","elementType":"all","stylers":[{"visibility":"on"},{"color":"#acbcc9"}]}] """) plot = GMapPlot( x_range=x_range, y_range=y_range, map_options=map_options, title=u"Тверь" ) pan = PanTool() wheel_zoom = WheelZoomTool() box_select = BoxSelectTool() plot.add_tools(pan, wheel_zoom, box_select) return plot
def hpd(): hpdf = pd.read_csv('hpd.csv') print(hpdf.head()) print(len(hpdf)) #print(hpdf.long.tolist()) map_options = GMapOptions(lat=40.80, lng=-73.94, map_type="roadmap", zoom=13, styles=""" [{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"on"},{"lightness":33}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2e5d4"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#c5dac6"}]},{"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]},{"featureType":"road","elementType":"all","stylers":[{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#c5c6c6"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#e4d7c6"}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#fbfaf7"}]},{"featureType":"water","elementType":"all","stylers":[{"visibility":"on"},{"color":"#acbcc9"}]}] """) #do NOT change zoom to 12, map won't load! plot = GMapPlot( x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, plot_width=600, plot_height=750, api_key=API_KEY #, tools=TOOLS #title=title, tools=[hover] ) source = ColumnDataSource(data=dict(x=[], y=[])) source.data = dict( x = hpdf.long.tolist(), y = hpdf.lat.tolist() ) circle = Circle(x='x', y='y', size=5, fill_color="orange", fill_alpha=0.2, line_color=None) plot.add_glyph(source, circle) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool())#, hover) script, div = components(plot) return render_template('hpd.html', script=script, div=div)
def run(): """plot all stations on google map """ #get the stations data stations = build_station_list() #get the coordinate of the mid points of the most east and west stations sort_station_one = sorted(stations, key=lambda station: station.coord[0]) mid_lat = (sort_station_one[0].coord[0] + sort_station_one[-1].coord[0]) / 2 sort_station_two = sorted(stations, key=lambda station: station.coord[1]) mid_lng = (sort_station_two[0].coord[1] + sort_station_two[-1].coord[1]) / 2 #show the map map_options = GMapOptions(lat=mid_lat, lng=mid_lng, map_type="roadmap", zoom=6) plot = GMapPlot(x_range=Range1d(), y_range=Range1d(), map_options=map_options) plot.title.text = "Flood warning" plot.api_key = "AIzaSyDu680hgb23BsVmnej1GC5XnALbj0DbjTE" #bulid a list of coordinates of the stations #probably need improvement in terms of speed list_of_lat = [] list_of_lng = [] for station in stations: list_of_lat.append(station.coord[0]) list_of_lng.append(station.coord[1]) #plot points on the map source = ColumnDataSource(data=dict( lat=list_of_lat, lng=list_of_lng, )) circle = Circle(x="lng", y="lat", size=5, fill_color="blue", fill_alpha=0.8, line_color=None) plot.add_glyph(source, circle) plot.add_tools(PanTool(), WheelZoomTool()) output_file("gmap_plot.html") show(plot)
def _initialize(self, figsize, **kwargs): map_options = GMapOptions(**kwargs) self.map = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, plot_width=figsize[0], plot_height=figsize[1]) self.map.api_key = self.key self.source = ColumnDataSource(dict( lat=[], lon=[], index=[], )) self.text = ColumnDataSource(dict( x=[], y=[], text=[], )) mapper = LinearColorMapper(palette=Magma[256]) circle = Circle(x="lon", y="lat", size=15, fill_color={ "field": "index", "transform": mapper }) text = Text(x="x", y="y", text="text") self.map.add_glyph(self.source, circle) self.map.add_glyph(self.text, text) self.map.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool()) session = push_session(curdoc()) curdoc().add_root(self.map) session.show()
def plot_map(self, estados, ano): lati = [] long = [] for i in range(0, len(estados)): lati.append(estados['Latitude'][i]) long.append(estados['Longitude'][i]) vinculo = self.__appendData(ano) map_options = GMapOptions(lat=-16.1610697, lng=-59.8988937, map_type="roadmap", zoom=5) plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options) plot.title.text = "Mapa de gastos do Brasil de " + ano # Para pegar uma chave acesse: # https://developers.google.com/maps/documentation/javascript/get-api-key plot.api_key = "API GOOGLE" source = ColumnDataSource( data=dict(lat=lati, lon=long, size=vinculo, color=vinculo)) color_mapper = LinearColorMapper(palette=Viridis5) circle = Circle(x="lon", y="lat", size="size", fill_color={ 'field': 'color', 'transform': color_mapper }, fill_alpha=0.4, line_color=None) plot.add_glyph(source, circle) color_bar = ColorBar(color_mapper=color_mapper, ticker=BasicTicker(), label_standoff=12, border_line_color=None, location=(0, 0)) plot.add_layout(color_bar, 'right') plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool()) output_notebook() show(plot)
def plot(lats, lons, count): x_range = Range1d() y_range = Range1d() # JSON style string taken from: https://snazzymaps.com/style/1/pale-dawn map_options = GMapOptions(lat=51.5034091928929, lng=-0.151864316576549, map_type="roadmap", zoom=5, styles=""" [{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"on"},{"lightness":33}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2e5d4"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#c5dac6"}]},{"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]},{"featureType":"road","elementType":"all","stylers":[{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#c5c6c6"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#e4d7c6"}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#fbfaf7"}]},{"featureType":"water","elementType":"all","stylers":[{"visibility":"on"},{"color":"#acbcc9"}]}] """) API_KEY = "AIzaSyBIQD3thSiRfIw1FRJcSbr0-GBo6Yv6r8Q" plot = GMapPlot( x_range=x_range, y_range=y_range, map_options=map_options, api_key=API_KEY, ) plot.title.text = "Property Sales Transaction Clusters for 2010" source = ColumnDataSource(data=dict( lat=lats, lon=lons, count=count, )) circle = Circle(x="lon", y="lat", size=15, fill_color="green", line_color="black") plot.add_glyph(source, circle) pan = PanTool() wheel_zoom = WheelZoomTool() box_select = BoxSelectTool() hover_tool = HoverTool() plot.add_tools(pan, wheel_zoom, box_select, hover_tool) hover = plot.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([("# Transactions:", "@count")]) doc = Document() doc.add_root(plot) filename = "maps.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "UK home sales")) print("Wrote %s" % filename)
def create_plot(center_coords, zoom_level=8): x_range = Range1d() y_range = Range1d() # JSON style string taken from: https://snazzymaps.com/style/1/pale-dawn map_options = GMapOptions(lat=center_coords['lat'], lng=center_coords['lng'], map_type="roadmap", zoom=zoom_level, styles=""" [{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"on"},{"lightness":33}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2e5d4"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#c5dac6"}]},{"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]},{"featureType":"road","elementType":"all","stylers":[{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#c5c6c6"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#e4d7c6"}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#fbfaf7"}]},{"featureType":"water","elementType":"all","stylers":[{"visibility":"on"},{"color":"#acbcc9"}]}] """) plot = GMapPlot(x_range=x_range, y_range=y_range, map_options=map_options, title="Austin") # source = ColumnDataSource( # data=dict( # lat=[30.2861, 30.2855, 30.2869], # lon=[-97.7394, -97.7390, -97.7405], # fill=['orange', 'blue', 'green'] # ) # ) # circle = Circle(x="lon", y="lat", size=15, fill_color="fill", line_color="black") # plot.add_glyph(source, circle) pan = PanTool() wheel_zoom = WheelZoomTool() box_select = BoxSelectTool() plot.add_tools(pan, wheel_zoom, box_select) return plot
def plotByCountries(self): from bokeh.io import output_file, show from bokeh.models import GMapPlot, GMapOptions, ColumnDataSource, Circle, Range1d, PanTool, WheelZoomTool, BoxSelectTool map_options = GMapOptions(lat=0, lng=0, zoom=3) plot = GMapPlot(x_range=Range1d(), y_range=Range1d(), map_options=map_options) plot.title.text = "Number of IP addresses by country" plot.api_key = "AIzaSyBhp55aOUd89Uj3KDP3cvbZJkeHviiA8Qc" # Now we create a ColumnDataSource object and pass in the latitude # and longitude, and the number of IPV4 to have a differnet size of plots source = ColumnDataSource( data=dict(lats=list(self.country.latitude), lons=list(self.country.longitude), sizes=[(x**(1 / 2)) / 2 for x in self.country.numberOfIp])) # Next we use the Circle()class to define how the points will look on the map: circle1 = Circle(x="lons", y="lats", size="sizes", fill_color="red", fill_alpha=0.35, line_color=None) plot.add_glyph(source, circle1) circle2 = Circle(x="lons", y="lats", size=3, fill_color="red", fill_alpha=1, line_color=None) plot.add_glyph(source, circle2) # Then we add the tools we want to use (Paning, Wheel Zoom, and general box selection) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool()) # Now we show the plot (you should see a new tab or window open here) #output_file("Country_Ip.html") show(plot)
def plot_points_gmaps(coords_blue, coords_red, filename="gmap_plot.html"): """ Plot a collection of points via google maps """ def coords_to_ColumnDataSource(coords): """ Convert coordinates as above to a column data source as required by Google's API """ longs, lats = extract_longs_lats(coords) return ColumnDataSource(data=dict(lon=longs, lat=lats)) center = coord_from_string(coords_blue[0]) map_options = GMapOptions(lng=center[0], lat=center[1], map_type="roadmap", zoom=11) plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, api_key="AIzaSyB3_kW006gZmQJA929W7794Q4GbIn2fLnU") source_blue = coords_to_ColumnDataSource(coords_blue) source_red = coords_to_ColumnDataSource(coords_red) circle_blue = Circle(x="lon", y="lat", size=5, fill_color="blue", fill_alpha=0.8, line_color=None) circle_red = Circle(x="lon", y="lat", size=5, fill_color="red", fill_alpha=0.8, line_color=None) plot.add_glyph(source_blue, circle_blue) plot.add_glyph(source_red, circle_red) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool()) output_file(filename) show(plot)
def trail_map(data): lon = (min(data.lon) + max(data.lon)) / 2 lat = (min(data.lat) + max(data.lat)) / 2 map_options = GMapOptions(lng=lon, lat=lat, zoom=13) plot = GMapPlot(plot_width=800, plot_height=800, map_options=map_options, api_key=API_KEY) plot.title.text = "%s - Trail Map" % name plot.x_range = Range1d() plot.y_range = Range1d() plot.add_tools(PanTool(), WheelZoomTool(), ResetTool()) line_source = ColumnDataSource(dict(x=data.lon, y=data.lat, dist=data.dist)) line = Line(x="x", y="y", line_color="blue", line_width=2) plot.add_glyph(line_source, line) if plot.api_key == "GOOGLE_API_KEY": plot.add_layout(Label(x=240, y=700, x_units='screen', y_units='screen', text='Replace GOOGLE_API_KEY with your own key', text_color='red')) return plot
def drawMap(title, datas): """ color : [(lat, lon)] """ lat = [] lon = [] c = [] for color in datas: c_lat, c_lon = zip(*datas[color]) #print (c_lat) lat.extend(map(float, c_lat)) lon.extend(map(float, c_lon)) c.extend([color]*len(datas[color])) center_lat = np.median(lat) center_lon = np.median(lon) x_range = Range1d() y_range = Range1d() source = ColumnDataSource( data=dict( lat=lat, lon=lon, fill=c ) ) map_options = GMapOptions(lat=center_lat, lng=center_lon, map_type="roadmap", zoom=11) plot = GMapPlot( x_range=x_range, y_range=y_range, map_options=map_options, title=title ) # Glyphs (dots on graph) circle = Circle(x="lon", y="lat", size=6, line_width=0, fill_color="fill", fill_alpha=0.5, line_alpha=0.0) plot.add_glyph(source, circle) #Navigation pan = PanTool() wheel_zoom = WheelZoomTool() box_select = BoxSelectTool() plot.add_tools(pan, wheel_zoom, box_select) overlay = BoxSelectionOverlay(tool=box_select) plot.add_layout(overlay) return display.HTML(file_html(plot, INLINE, "Google Maps Example"))
def trail_map(data): lon = (min(data.lon) + max(data.lon)) / 2 lat = (min(data.lat) + max(data.lat)) / 2 map_options = GMapOptions(lng=lon, lat=lat, zoom=13) plot = GMapPlot(title="%s - Trail Map" % title, map_options=map_options, plot_width=800, plot_height=800) plot.x_range = DataRange1d() plot.y_range = DataRange1d() plot.add_tools(PanTool(), WheelZoomTool(), ResetTool()) line_source = ColumnDataSource(dict(x=data.lon, y=data.lat, dist=data.dist)) line = Line(x="x", y="y", line_color="blue", line_width=2) plot.add_glyph(line_source, line) return plot
def search(request): location = request.POST['search'] api_key = 'AIzaSyB4WAP0dZG2f6avZ6EYiMBolrtVrxgqtlU' gm = googlemaps.Client(key=api_key) address = location lat = gm.geocode(address)[0]['geometry']['location']['lat'] lng = gm.geocode(address)[0]['geometry']['location']['lng'] map_options = GMapOptions(lat=lat, lng=lng, map_type='roadmap', zoom=8) plot = GMapPlot(x_range=Range1d(), y_range=Range1d(), map_options=map_options, api_key=api_key) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool(), PolySelectTool()) scale = 2.5 source = ColumnDataSource( data=dict(lat=[lat], lon=[lng], rad=[2], size=[100])) circle = Circle(x=lng, y=lat, size="rad", fill_color='red', fill_alpha=0.5) global latitude, longitude latitude = lat longitude = lng square = Square(x=lng, y=lat, size="size", fill_color="red", fill_alpha=0.5) plot.add_glyph(source, square) output_file( 'C:/Users/pkt01/django_projects/geokno/geoproj/templates/geoproj/plot.html' ) save(plot) return render(request, 'geoproj/Query.html')
def graph(): map_options = GMapOptions(lat=40.699389, lng=-73.955454, map_type="roadmap", zoom=10) plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, title="NYC") df = pd.read_csv('csvs/Over60percent_apprec.csv', low_memory=False) source = ColumnDataSource(data=dict( lat=np.array(df.Lat), lon=np.array(df.Long), )) circle = Circle(x="lon", y="lat", size=2.5, fill_color="red", fill_alpha=0.8, line_color=None) plot.add_glyph(source, circle) df2 = pd.read_csv('csvs/Loss_of_Over60percent.csv', low_memory=False) source2 = ColumnDataSource(data=dict( lat=np.array(df2.Lat), lon=np.array(df2.Long), )) circle2 = Circle(x="lon", y="lat", size=2.5, fill_color="blue", fill_alpha=0.8, line_color=None) plot.add_glyph(source2, circle2) plot.add_tools(PanTool(), WheelZoomTool()) script, div = components(plot) return render_template('graph.html', script=script, div=div)
def graph(lats, lans): map_option = GMapOptions(lat=0, lng=0, zoom=3) plot = GMapPlot(x_range=Range1d(), y_range=Range1d(), map_options=map_option) plot.title.text = 'example' #plot.api_key='AIzaSyDg82cXIhKEGCTYt2XtWZhp6r5EuJbB94E' plot.api_key = 'AIzaSyAtt_C5_5WTwW-0bTHYi4aSDmURoU1UzvE' source = ColumnDataSource(data=dict(lat=lats, lon=lans)) circle = Circle(x='lon', y='lat', size=15, fill_color='red', fill_alpha=0.6) plot.add_glyph(source, circle) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool()) output_file('google.html') show(plot)
def plotonmap(df, data, plotname='plot on map', color='blue'): import os from bokeh.embed import file_html from bokeh.resources import CDN from bokeh.io import show, output_file from bokeh.models import (GMapPlot, GMapOptions, ColumnDataSource, Circle, DataRange1d, PanTool, WheelZoomTool, BoxSelectTool) os.environ.get("foo") lat = 35.6892 lon = 51.3890 zoom = 7 api_key = 'AIzaSyCvllwPPFlcF6SF8e2WJBhErb9IYOuqUyk' map_type = 'roadmap' if "lat" in data: lat = data['lat'] if "lon" in data: lon = data['lon'] if "zoom" in data: zoom = data['zoom'] if "api_key" in data: api_key = data['api_key'] if "map_type" in data: map_type = data['map_type'] map_options = GMapOptions(lat=lat, lng=lon, map_type=map_type, zoom=zoom) api_key = os.environ.get('API_KEY') api_key = 'AIzaSyCvllwPPFlcF6SF8e2WJBhErb9IYOuqUyk' plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, api_key=api_key) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool()) baseline = df['count merchant'].min() m = df['count merchant'].mean() / zoom source = ColumnDataSource( data=dict(lat=df['lat'].values.tolist(), lon=df['lon'].values.tolist(), rad=[((i - baseline) / m) + zoom for i in df['count merchant'].values.tolist()])) circle = Circle(x="lon", y="lat", size="rad", fill_color=color, fill_alpha=0.3) plot.add_glyph(source, circle) return file_html(plot, CDN, "my plot", plotname)
lat_lon_df = pickle.load(open("data/dep_times_lat_lon.p","rb")) #lat_lon_df = lat_lon_df.ix[:,['lat','lon']] map_options = GMapOptions(lat=23.29, lng=78.73,map_type="roadmap", zoom=4) col_vals = lat_lon_df['num_deps'].values colors = [ "#%02x%02x%02x" % (int(r), int(g), int(b)) for r, g, b, _ in 255*mpl.cm.Blues(mpl.colors.Normalize()(col_vals)) ] lat_lon_df['col_vals'] = colors plot = GMapPlot( x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, title="India" ) source = ColumnDataSource(lat_lon_df) #circle = Circle(x="lon", y="lat", size=5, fill_color="blue", fill_alpha=0.7, line_color=None) circle = Circle(x ='lon', y = 'lat',size = 5, fill_color = 'col_vals') plot.add_glyph(source, circle) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool(), HoverTool(tooltips = [('name','@name'),('No. of deps/week', '@num_deps'),('Code','@code')]),ResetTool(),TapTool()) output_file("gmap_plot.html") show(plot)
def make_map(pkts): NUMBER_OF_COORDINATES = 30 # How many IPs to plot ipdict = defaultdict(int) # Count all IP addresses in capture file for pkt in pkts: ipdict[pkt.src] += 1 ipdict[pkt.dst] += 1 # Filter out the private/local IPs publicips = { ip: count for (ip, count) in ipdict.iteritems() if get_ip_type(ip) == 'PUBLIC'} if not publicips: print "Could not find any parseable public IPs. Exiting.." return Document() # Get the top 30 public IPs that occur the most often top_items = Counter(publicips).most_common(NUMBER_OF_COORDINATES) top_ips = [ip for ip, count in top_items] top_counts = [publicips[ip] for ip in top_ips] # Scale the counts so that maximum circle size is 100px sizes = [100 * count // top_counts[0] for count in top_counts] # Get random colors for circles colors = get_n_colors(NUMBER_OF_COORDINATES) # Get lists of latitude and longitude for IPs. lat, lon, org = reverse_lookup_ips(top_ips, top_counts) lat, lon = fuzz_locations(lat, lon) # Drawing logic starts here centerx, centery = lat[0], lon[0] # JSON style string taken from: https://snazzymaps.com/style/1/pale-dawn map_options = GMapOptions(lat=centerx, lng=centery, map_type="satellite", zoom=5, styles=""" [{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"on"},{"lightness":33}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2e5d4"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#c5dac6"}]},{"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]},{"featureType":"road","elementType":"all","stylers":[{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#c5c6c6"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#e4d7c6"}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#fbfaf7"}]},{"featureType":"water","elementType":"all","stylers":[{"visibility":"on"},{"color":"#acbcc9"}]}] """) x_range = Range1d() y_range = Range1d() plot = GMapPlot( x_range=x_range, y_range=y_range, map_options=map_options, title="Top public IP addresses", plot_width=1000 ) source = ColumnDataSource( data=dict( lat=lat, lon=lon, fill=colors, ip=top_ips, count=top_counts, organization=org, size=sizes, rank=range(1, len(top_ips) + 1), # Circles become more opaque as you go from largest to smallest opacity=list(frange(0.1, 0.9, (0.9 - 0.1) / len(top_ips))) ) ) circle = Circle(x="lon", y="lat", size="size", fill_color="fill", fill_alpha=0.7, line_color="black") plot.add_glyph(source, circle) # Adds the ability to see IP address, location, index on hover hover = HoverTool( tooltips=[ ("Rank", "@rank"), ("IP address", "@ip"), ("Packet count", "@count"), ("Hosted by", "@organization"), ("Location", "(@lat, @lon)") ], # not sure if I prefer follow_mouse or snap_to_data # point_policy="snap_to_data" ) # add tools to pan, zoom and hover to plot plot.add_tools(PanTool(), WheelZoomTool(), hover) doc = Document() doc.add_root(plot) return doc
GMapPlot, Range1d, ColumnDataSource, PanTool, WheelZoomTool, BoxSelectTool, BoxSelectionOverlay, GMapOptions) from bokeh.resources import INLINE x_range = Range1d() y_range = Range1d() # JSON style string taken from: https://snazzymaps.com/style/1/pale-dawn map_options = GMapOptions(lat=30.2861, lng=-97.7394, map_type="roadmap", zoom=13, styles=""" [{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"on"},{"lightness":33}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2e5d4"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#c5dac6"}]},{"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]},{"featureType":"road","elementType":"all","stylers":[{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#c5c6c6"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#e4d7c6"}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#fbfaf7"}]},{"featureType":"water","elementType":"all","stylers":[{"visibility":"on"},{"color":"#acbcc9"}]}] """) plot = GMapPlot( x_range=x_range, y_range=y_range, map_options=map_options, title="Austin" ) source = ColumnDataSource( data=dict( lat=[30.2861, 30.2855, 30.2869], lon=[-97.7394, -97.7390, -97.7405], fill=['orange', 'blue', 'green'] ) ) circle = Circle(x="lon", y="lat", size=15, fill_color="fill", line_color="black") plot.add_glyph(source, circle) pan = PanTool()
coll_lons = [colls_with_pothole_reported[i][1] for i in range(len(colls_with_pothole_reported))] coll_lats = [colls_with_pothole_reported[i][0] for i in range(len(colls_with_pothole_reported))] coll_pv_lons = [colls_pv[i][1] for i in range(len(colls_pavement))] coll_pv_lats = [colls_pv[i][0] for i in range(len(colls_pavement))] output_file("pothole_related_collisions.html") print "number of collisions due to pavement: " + str(len(coll_bors)) b = Counter(coll_bors) print b map_options = GMapOptions(lat=40.7127, lng=-74.0059, map_type="hybrid", zoom=10) plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, title="Potholes Open Past Days") source = ColumnDataSource(data=dict(lat=coll_pv_lats, lon=coll_pv_lons)) circle = Circle(x="lon",y="lat", size=2, fill_color="blue", fill_alpha=0.8, line_color=None) circle_larger = Circle(x="lon",y="lat", size=5, fill_color="blue", fill_alpha=0.8, line_color=None) plot.add_glyph(source, circle_larger) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool(), ResetTool()) show(plot) ##m = Basemap(projection='tmerc',width=55000,height=55000,lon_0=-74.0059,lat_0=40.7127,resolution='h') ##m.drawcounties() ##m.fillcontinents(color='lemonchiffon',lake_color='#99ffff') ###m.scatter(coll_lons,coll_lats,latlon=True,marker='o',color='b',zorder=10) ##m.scatter(coll_pv_lons,coll_pv_lats, latlon=True,marker='o',color='b',zorder=10)
# JSON style string taken from: https://snazzymaps.com/style/1/pale-dawn map_options = GMapOptions(lat=48.8003394, lng=2.2508597, map_type="roadmap", zoom=11, styles="""[{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"on"},{"lightness":33}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2e5d4"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#c5dac6"}]},{"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]},{"featureType":"road","elementType":"all","stylers":[{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#c5c6c6"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#e4d7c6"}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#fbfaf7"}]},{"featureType":"water","elementType":"all","stylers":[{"visibility":"on"},{"color":"#acbcc9"}]}] """) # Google Maps now requires an API key. You can find out how to get one here: # https://developers.google.com/maps/documentation/javascript/get-api-key API_KEY = "" x_range = DataRange1d() y_range = DataRange1d() plot = figure() plot = GMapPlot( x_range=x_range, y_range=y_range, map_options=map_options, api_key=API_KEY, ) source = ColumnDataSource( data=dict( lat=PrixParis['La'].tolist(), lon=PrixParis['Lo'].tolist(), cols=PrixParis['Color'], ) ) circle = Circle(x="lon", y="lat", size=15, fill_color="cols", fill_alpha=0.6, line_color='#FFFFFF',line_width=2) plot.add_glyph(source, circle)
# test for gmaps integration p = Patches(xs = 'x', ys = 'y', fill_color='color', fill_alpha=0.5, line_color="white", line_width=0.5) # with gmaps #circle = Circle(x="lon", y="lat", size=15, fill_color="blue", fill_alpha=0.8, line_color=None) styles1 = """[{"featureType": "landscape","stylers": [{"hue": "#FFBB00"},{"saturation": 43.400000000000006},{"lightness": 37.599999999999994},{"gamma": 1}]},{"featureType": "road.highway","stylers": [{"hue": "#FFC200"},{"saturation": -61.8},{"lightness": 45.599999999999994},{"gamma": 1}]},{"featureType": "road.arterial","stylers": [{"hue": "#FF0300"},{"saturation": -100},{"lightness": 51.19999999999999},{"gamma": 1}]},{"featureType": "road.local","stylers": [{"hue": "#FF0300"},{"saturation": -100},{"lightness": 52},{"gamma": 1}]},{"featureType": "water","stylers": [{"hue": "#0078FF"},{"saturation": -13.200000000000003},{"lightness": 2.4000000000000057},{"gamma": 1}]},{"featureType": "poi","stylers": [{"hue": "#00FF6A"},{"saturation": -1.0989010989011234},{"lightness": 11.200000000000017},{"gamma": 1}]}]""" map_options1 = GMapOptions(lat=38, lng=-79, map_type="roadmap", zoom=7, styles=styles1) plot = GMapPlot(title="", # x_axis_label='Longitude', y_axis_label='Latitude', plot_width=900, plot_height=500, x_range = Range1d(), y_range = Range1d(), border_fill = "#FFFFFF", map_options=map_options1) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool(), HoverTool(), ResetTool(), PreviewSaveTool()) plot_glyph = plot.add_glyph(source, p) #circle = Circle(x="lon", y="lat", size=15, fill_color="blue", fill_alpha=0.8, line_color=None) #plot.add_glyph(source, circle) hover = plot.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([ ("Name", "@name"), ("EST 2016 Population", "@pop"),
def main(): if request.method == 'GET': return render_template('species_MC.html') else: #request was a POST app.vars['species'] = request.form['selected_species'] response = requests.get("http://api.erg.kcl.ac.uk/AirQuality/Hourly/MonitoringIndex/GroupName=London") root = ET.fromstring(response.content) info_response = requests.get("http://api.erg.kcl.ac.uk/AirQuality/Information/Species") info_root = ET.fromstring(info_response.content) latitudes = [] longitudes =[] sites =[] AQIs = [] AQI_colors = [] if app.vars['species'] == 'nitrogen dioxide': for child in root.findall(".//*[@SpeciesCode='NO2']/..[@Latitude]"): x = child.get('Latitude') latitudes.append(x) x = child.get('SiteName') sites.append(x) x = child.get('Longitude') longitudes.append(x) x = child.get('BulletinDate') app.vars['date'] = x for child in root.findall(".//*[@SpeciesCode='NO2']"): x = child.get('AirQualityIndex') AQIs.append(x) for child in info_root.findall(".//*[@SpeciesCode='NO2']"): descr = child.get('Description') healtheffect = child.get('HealthEffect') elif app.vars['species'] == 'PM10 particulate matter': app.vars['species'] = 'PM10' for child in root.findall(".//*[@SpeciesCode='PM10']/..[@Latitude]"): x = child.get('Latitude') latitudes.append(x) x = child.get('SiteName') sites.append(x) x = child.get('Longitude') longitudes.append(x) x = child.get('BulletinDate') app.vars['date'] = x for child in root.findall(".//*[@SpeciesCode='PM10']"): x = child.get('AirQualityIndex') AQIs.append(x) for child in info_root.findall(".//*[@SpeciesCode='PM10']"): descr = child.get('Description') healtheffect = child.get('HealthEffect') elif app.vars['species'] == 'PM25 particulate matter': app.vars['species'] = 'PM25' for child in root.findall(".//*[@SpeciesCode='PM25']/..[@Latitude]"): x = child.get('Latitude') latitudes.append(x) x = child.get('SiteName') sites.append(x) x = child.get('Longitude') longitudes.append(x) x = child.get('BulletinDate') app.vars['date'] = x for child in root.findall(".//*[@SpeciesCode='PM25']"): x = child.get('AirQualityIndex') AQIs.append(x) for child in info_root.findall(".//*[@SpeciesCode='PM25']"): descr = child.get('Description') healtheffect = child.get('HealthEffect') elif app.vars['species'] == 'ozone': for child in root.findall(".//*[@SpeciesCode='O3']/..[@Latitude]"): x = child.get('Latitude') latitudes.append(x) x = child.get('SiteName') sites.append(x) x = child.get('Longitude') longitudes.append(x) x = child.get('BulletinDate') app.vars['date'] = x for child in root.findall(".//*[@SpeciesCode='O3']"): x = child.get('AirQualityIndex') AQIs.append(x) for child in info_root.findall(".//*[@SpeciesCode='O3']"): descr = child.get('Description') healtheffect = child.get('HealthEffect') elif app.vars['species'] == 'sulphur dioxide': for child in root.findall(".//*[@SpeciesCode='SO2']/..[@Latitude]"): x = child.get('Latitude') latitudes.append(x) x = child.get('SiteName') sites.append(x) x = child.get('Longitude') longitudes.append(x) x = child.get('BulletinDate') app.vars['date'] = x for child in root.findall(".//*[@SpeciesCode='SO2']"): x = child.get('AirQualityIndex') AQIs.append(x) for child in info_root.findall(".//*[@SpeciesCode='SO2']"): descr = child.get('Description') healtheffect = child.get('HealthEffect') for AQI in AQIs: if AQI =='0': AQI_color = AQI.replace('0','grey') if AQI =='1': AQI_color = AQI.replace('1','forestgreen') if AQI =='2': AQI_color = AQI.replace('2','lawngreen') if AQI =='3': AQI_color = AQI.replace('3','gold') if AQI =='4': AQI_color = AQI.replace('4','darkorange') if AQI =='5': AQI_color = AQI.replace('5','orangered') if AQI =='6': AQI_color = AQI.replace('6','red') if AQI =='7': AQI_color = AQI.replace('7','magenta') if AQI =='8': AQI_color = AQI.replace('6','blueviolet') if AQI =='9': AQI_color = AQI.replace('9','blue') if AQI =='10': AQI_color = AQI.replace('10','black') AQI_colors.append(AQI_color) map_options = GMapOptions(lat=51.4908308, lng=-0.1407765, map_type="roadmap", zoom=10) plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, plot_width=740, plot_height=650, toolbar_location="below") # plot.title.text= "AQIs" plot.api_key="AIzaSyA7Adc9av0W2hSf72F3VwepL-MqQvs5Hes" # source = ColumnDataSource( data = dict( lat = latitudes, lon = longitudes, color = AQI_colors, sites = sites, AQIs = AQIs)) # # circle = Circle(x = "lon", y = "lat", size=14, fill_color="color", fill_alpha=0.5, line_color=None) plot.add_glyph(source, circle) # # plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool(), HoverTool()) # # hover = plot.select(dict(type=HoverTool)) # # # hover.tooltips=""" <!DOCTYPE html> <html lang="en"> <head> <link rel=stylesheet type=text/css href='{{ url_for('static',filename='style_input_ht.css')}}'> <div> <div> <span style="font-size: 17px; color:black;">@sites</span> </div> <div> <span style="font-size: 15px; color: black;">AQI</span> <span style="font-size: 15px; color: black;">@AQIs</span> </div> </div> """ script, div = components(plot) output_file('templates/map.html') # save(plot) return render_template('map.html', script=script, div=div, species=app.vars['species'], date=app.vars['date'])#, descr=descr, healtheffect=healtheffect)
def plotPoints(latLonData, category, year): latitude = [] longitude = [] fillLatAndLon(latitude, longitude, latLonData) index = 0 for value in longitude: if value == 0: category[index] = '' year[index] = '' index += 1 latitude = [x for x in latitude if x != 0] longitude = [x for x in longitude if x != 0] category = [x for x in category if len(x) != 0] year = [x for x in year if len(x) != 0] moddedLat = [] moddedLon = [] moddedCat = [] moddedYear = [] for x in range(0, len(latitude), 20): moddedLat.append(latitude[x]) moddedLon.append(longitude[x]) moddedCat.append(category[x]) moddedYear.append(year[x]) latitude = moddedLat longitude = moddedLon category = moddedCat year = moddedYear dataSource = ColumnDataSource( data=dict( lat = latitude, lon = longitude, cat = category, year = year ) ) hover = HoverTool( tooltips=[ ("Case#", "$index"), ("Category", "@cat"), ("Year", "@year"), ] ) map_options = GMapOptions(lat=47.60, lng=-122.33, map_type="hybrid", zoom=3) plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, title="U.S. Chronic Disease Locations (2008-2013)") diamond = Diamond(x="lon", y="lat", size=10, fill_color="red", fill_alpha=0.2, line_color='white') plot.add_glyph(dataSource, diamond) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool(), hover) output_file("disease.html", title="Diseases") show(plot)
from bokeh.sampledata.world_cities import data x_range = Range1d(-160, 160) y_range = Range1d(-80, 80) # Google Maps now requires an API key. You can find out how to get one here: # https://developers.google.com/maps/documentation/javascript/get-api-key API_KEY = "GOOGLE_API_KEY" map_options = GMapOptions(lat=15, lng=0, zoom=2) plot = GMapPlot( x_range=x_range, y_range=y_range, plot_width=1000, plot_height=500, map_options=map_options, api_key=API_KEY, webgl=True, ) if plot.api_key == "GOOGLE_API_KEY": plot.add_layout(Label(x=500, y=320, x_units='screen', y_units='screen', text='Replace GOOGLE_API_KEY with your own key', text_color='red', text_align='center')) plot.title.text = "Cities of the world with a population over 5,000 people." circle = Circle(x="lng", y="lat", size=5, line_color=None, fill_color='firebrick', fill_alpha=0.2) plot.add_glyph(ColumnDataSource(data), circle) plot.add_tools(PanTool(), WheelZoomTool())
from bokeh.models.glyphs import Circle from bokeh.models import ( GMapPlot, ColumnDataSource, PanTool, WheelZoomTool, BoxSelectTool, GMapOptions, LinearAxis, MercatorTickFormatter, MercatorTicker, Label) from bokeh.resources import INLINE # JSON style string taken from: https://snazzymaps.com/style/1/pale-dawn map_options = GMapOptions(lat=30.2861, lng=-97.7394, map_type="roadmap", zoom=13, styles=""" [{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"on"},{"lightness":33}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2e5d4"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#c5dac6"}]},{"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]},{"featureType":"road","elementType":"all","stylers":[{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#c5c6c6"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#e4d7c6"}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#fbfaf7"}]},{"featureType":"water","elementType":"all","stylers":[{"visibility":"on"},{"color":"#acbcc9"}]}] """) # Google Maps now requires an API key. You can find out how to get one here: # https://developers.google.com/maps/documentation/javascript/get-api-key API_KEY = "GOOGLE_API_KEY" plot = GMapPlot(map_options=map_options, api_key=API_KEY) if plot.api_key == "GOOGLE_API_KEY": plot.add_layout(Label(x=140, y=400, x_units='screen', y_units='screen', text='Replace GOOGLE_API_KEY with your own key', text_color='red')) plot.title.text = "Austin" source = ColumnDataSource( data=dict( lat=[30.2861, 30.2855, 30.2869], lon=[-97.7394, -97.7390, -97.7405], fill=['orange', 'blue', 'green'] ) )
for i in range(num_color + 1): price_range.append(min_price + i * interval) # give color to each location loc_color = [] for p in price: for i in range(num_color): if p >= price_range[i] and p <= price_range[i + 1]: loc_color.append(colors[i]) break # Plot and google map map_options = GMapOptions(lat=37.87, lng=-122.27, map_type="roadmap", zoom=14) plot = GMapPlot( x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, title="Austin", plot_width=1200, plot_height=600, webgl=True ) source = ColumnDataSource( data=dict( lat = latitude, lon = longitude, color = loc_color, rprice = price, dis = distance, addr = address, restaurant = food, cafe = cafes, pub = pubs, size = sqft, )
from bokeh.models import ( GMapPlot, Range1d, ColumnDataSource, LinearAxis, PanTool, WheelZoomTool, BoxSelectTool, BoxSelectionOverlay, GMapOptions, NumeralTickFormatter, PrintfTickFormatter) from bokeh.resources import INLINE from bokeh.sampledata.us_cities import data x_range = Range1d() y_range = Range1d() map_options = GMapOptions(lat=35, lng=-100, zoom=4) plot = GMapPlot( x_range=x_range, y_range=y_range, map_options=map_options, title = "US Cities", webgl=True, ) plot.map_options.map_type="hybrid" source = ColumnDataSource(data=data) circle = Circle(x="lon", y="lat", size=10, line_color=None, fill_color='cyan', fill_alpha=0.1) plot.add_glyph(source, circle) pan = PanTool() wheel_zoom = WheelZoomTool() box_select = BoxSelectTool() plot.add_tools(pan, wheel_zoom, box_select)
from bokeh.models import HoverTool from bokeh.plotting import figure from bokeh.plotting import ColumnDataSource as plotColumnDataSource from bokeh.io import output_file, show from bokeh.models import ( GMapPlot, GMapOptions, ColumnDataSource, Circle, DataRange1d, PanTool, WheelZoomTool, BoxSelectTool ) map_options = GMapOptions(lat=42.3601, lng=-71.0589, map_type="hybrid", zoom=9) plot = GMapPlot( x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, title="Massachusetts" ) # source = ColumnDataSource( # data=dict( # lat=[42.3601, 42.2926], # lon=[-71.0589, -71.2644], # ) # ) source = plotColumnDataSource(data=dict( x=[-71.0589, -71.2644], y=[42.3601, 42.2926], name=['Boston', 'Olin'], address=['Boston Rite Aid', 'Olin The Awesomest'] )) circle = Circle(x="x", y="y", size=15, fill_color="blue", fill_alpha=0.8, line_color=None) plot.add_glyph(source, circle)
GMapPlot, Range1d, ColumnDataSource, LinearAxis, PanTool, WheelZoomTool, BoxSelectTool, GMapOptions, NumeralTickFormatter, PrintfTickFormatter,HoverTool, TapTool, OpenURL,) from bokeh.resources import INLINE x_range = Range1d() y_range = Range1d() # JSON style string taken from: https://snazzymaps.com/style/1/pale-dawn map_options = GMapOptions(lat=39, lng=-98, map_type="roadmap", zoom=4, styles=""" [{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"on"},{"lightness":33}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2e5d4"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#c5dac6"}]},{"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]},{"featureType":"road","elementType":"all","stylers":[{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#c5c6c6"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#e4d7c6"}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#fbfaf7"}]},{"featureType":"water","elementType":"all","stylers":[{"visibility":"on"},{"color":"#acbcc9"}]}] """) plot = GMapPlot( x_range=x_range, y_range=y_range, map_options=map_options, title = "NIST Fire Studies",plot_width=1100, plot_height=700 ) data = pd.read_csv('study_data.csv') source = ColumnDataSource({'lat':data['Latitude'],'lon':data['Longitude'],'studys': data['Study'],'report': data['Report'],'fill':data['Color'],'type':data['Type'],'date':data['Date']}) circle = Circle(x="lon",y="lat",size=15,fill_color="fill") plot.add_glyph(source, circle) pan = PanTool() wheel_zoom = WheelZoomTool() hover = HoverTool() tap = TapTool() hover.tooltips = [('Study Title','@studys'),('Date','@date'),('Type','@type')] url = "@report"