How can we get tooltips and popups to show in Folium - python

I am trying to get a tooltip and/or a popup to show on a map. When I zoom in, this is all that I see.
Here is the code that I am testing.
import folium
import requests
from xml.etree import ElementTree
from folium import plugins
m = folium.Map(location=[40.6976701, -74.2598704], zoom_start=10)
m.save('path')
for lat,lon,name,tip in zip(df_final['Latitude(DecDeg)'], df_final['Latitude(DecDeg)'], df_final['Market Description'], df_final['Project Description']):
folium.Marker(location=[lat,lon], tooltip = tip, popup = name)
m.add_child(cluster)
m
I feel like I'm missing a library, or some such thing. Any idea why this is not working correctly?

It seems you forgot to use .add_to(m) to add it to map
folium.Marker(...).add_to(m)
or
marker = folium.Marker(...)
marker.add_to(m)
Minimal working code:
import folium
import webbrowser # open file in webbrowser
m = folium.Map(location=[40.6976701, -74.2598704], zoom_start=10)
marker = folium.Marker(location=[40.6976701, -74.2598704],
tooltip='<b>Stackoverflow</b><br><br>2021.01.01',
popup='<h1>Happy New Year!</h1><br><br>www: Stackoverflow.com<br><br>date: 2021.01.01')
marker.add_to(m)
m.save('map.html')
webbrowser.open('map.html') # open file in webbrowser

Related

interactive plot geopandas doesn't show

I have this code from this website:
https://geopandas.org/en/stable/docs/user_guide/interactive_mapping.html
import geopandas as gpd
import matplotlib.pyplot as plt
world_filepath = gpd.datasets.get_path('naturalearth_lowres')
world = gpd.read_file(world_filepath)
print(world.head())
world.explore(column='pop_est',cmap='Set2')
plt.show()
I try to run the code, the geodataframe data is printed but no plot is shown.
What am i missing?
Thnx in advanced.
world.explore(column='pop_est',cmap='Set2') should return and display a folium map object so you shouldn't need that plt.show() as the bottom.
Also, since you're using an IDE (not jupyter) we need to write the map to disk then open it up in the broswer.
Try
import geopandas as gpd
import webbrowser
import os
world_filepath = gpd.datasets.get_path('naturalearth_lowres')
world = gpd.read_file(world_filepath)
print(world.head())
# world.explore() returns a folium map
m = world.explore(column='pop_est',cmap='Set2')
# and then we write the map to disk
m.save('my_map.html')
# then open it
webbrowser.open('file://' + os.path.realpath('my_map.html'))
export() creates a folium object, not a matplotlib figure
in jupyter just have m as last item in code cell
in other environments you can save as HTML and launch into a browser
import geopandas as gpd
import webbrowser
from pathlib import Path
world_filepath = gpd.datasets.get_path('naturalearth_lowres')
world = gpd.read_file(world_filepath)
print(world.head())
m = world.explore(column='pop_est',cmap='Set2')
f = Path.cwd().joinpath("map.html")
m.save(str(f))
webbrowser.open("file://" + str(f))

How to convert html map into image (png or jpg )

I am trying to save a map containing markers and also heatmap into an image.
Here is the code to display the map.
from ipywidgets import Layout
import geopandas
defaultLayout=Layout(width='3000px', height='3000px') # A very large image.
lat_lgn = [39.74248, 254.993622]
m_f = Map(center=lat_lgn, zoom=12, layout=defaultLayout)
marker_m = Marker(location=lat_lgn, draggable=False)
m_f.add_layer(marker_m)
m_f
Add some markers on it
arr_test1 = [39.74258, 254.993682]
arr_test2 = [39.76288, 254.988932]
arr_test3 = [39.79998, 254.991982]
all_loc = [arr_test1, arr_test2, arr_test3]
for cur_loc in all_loc:
point = CircleMarker(
radius=10,
location=cur_loc,
color='red',
fill_color="black",
)
m_f.add_layer(point)
time.sleep(0.001)
Save the map as html file. Works fine.
m_f.save('f_map.html', title='My Map')
The problem occurs, when I try to get an image, or pdf from the html.
import imgkit
import pdfkit
config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf')
pdfkit.from_file('f_map.html', 'outpdf.pdf', configuration=config)
pdfkit.from_file('f_map.html', 'outjpg.jpg', configuration=config)
pdfkit.from_file('f_map.html', 'outpng.png', configuration=config)
The pdf file is blank
And macBook is not able the open neither the jpeg nor the png file.
To ckeck my dependencies, I have tried this:
import pdfkit
pdfkit.from_url('http://stackoverflow.com', 'out.pdf', configuration=config)
which works fine. However, once I change out.pdf to out.png, I cannot open the obtained file.
Does anyone has an idea, how I can solve the issue ?
I am trying to get hurge image. But it also did not work with a 300px X 300px image.
Any hints will be welcome.
One option (which admittedly is a little crude) is to use the selenium library to automatically open the HTML and from there take a screenshot which then is saved as an image.
The code will look like (I have given the code here according to MS Edge, but the code should be similar for other browsers):
from selenium import webdriver
from time import sleep
filename = '<Name (without path) of your HTML file here>'
MyBrowser = webdriver.Edge(r"<path to webdriver here>\\msedge.exe")
murl = r'file:\\{path}\{mapfile}'.format(path='<path to HTML here>',mapfile=mfilename)
MyBrowser.get(murl)
sleep(10) #this is not strictly necessary but is here in case you need time for map tiles to load
MyBrowser.save_screenshot('<Image_file_name>')
MyBrowser.quit()
Note that this will require you to install a webdriver for your browser in advance.

How do I make data orderly on the message box? python-tkinter

My current goal is to display data onto a
message box.
As this picture shows, the data is all over the place, but if I send it to Excel it looks perfectly fine whereas the message box is just not even.
How can I even out the displayed data on messagebox just to look like the excel?
Here is my code:
import tkinter as tk
import tkinter.messagebox as tm
import pandas
import datetime
def currency_rate():
dfs=pandas.read_html('https://rate.bot.com.tw/xrt?Lang=en-US')
currency=dfs[1]
currency= currency.iloc[:,0:5]
currency.columns=['currency','cash-buying','cash-selling','spot-buying','spot-selliing']
currency['currency'] =currency['currency'].str.extract('\((\w+)\)')
date=datetime.datetime.now()
result_date="Update: Date {:4}.{:02}.{:02}-Time {:02}:{:02}:{:02}".format(date.year,date.month,date.day,date.hour,date.minute,date.second)
tm.showinfo(title =str(result_date), message =str(currency))
def currency_rate_import():
dfs=pandas.read_html('https://rate.bot.com.tw/xrt?Lang=en-US')
currency=dfs[1]
currency= currency.iloc[:,0:5]
currency.columns=['currency','cash-buying','cash\nselling','spot\nbuying','spot-selliing']
currency['currency'] =currency['currency'].str.extract('\((\w+)\)')
date=datetime.datetime.now()
currency.to_excel('Currency Rate{:4}{:02}{:02}-Daily.xlsx'.format(date.year,date.month,date.day))
my_window=tk.Tk()
btn2=tk.Button(my_window,text="Export (Excel)",font="Calibri 14",width=25,height=1,command=currency_rate_import)
btn2.pack(side=tk.BOTTOM)
btn1=tk.Button(my_window,text="Today\'s exchange rate",font="Calibri 14",background="yellow",width=25,height=1,command=currency_rate)
btn1.pack(side=tk.BOTTOM)
my_window.mainloop()
I have good experience using pandas with tabulate and then inserting in Tkinter window with tkinterhtml.
You have "stralign" and "numalign" in tabulate and even "floatfmt" for all sorts of formats and alignment while creating tables.
example for usage:
from tabulate import tabulate
from tkinterhtml import HtmlFrame
html = tabulate(df,
headers='keys',
floatfmt=",.1f", tablefmt='html',
numalign='center', stralign='center')
top = tk.Toplevel()
hf = HtmlFrame(top)
hf.pack()
hf.set_content(html)

How to get Bokeh's 'PointDrawTool' working with a NetworkX Spring_Layout

I am working on a network node graph using NetworkX and Bokeh. I am using NetworkX's spring_layout to automatically generate positions for each of my nodes. However, I cannot figure out how to drag the nodes around on my graph (and also have the edges follow along with any dragged nodes).
How do I enable node-dragging for my NetworkX/Bokeh graph?
I have tried using Bokeh's 'PointDrawTool' tool, however, even though the tool renders and shows up in the toolbar next to my graph, it isn't functional.
plot = Plot(plot_width=1000, plot_height=1000,
x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1))
plot.title.text = "Network Graph"
graph_renderer = from_networkx(G, nx.spring_layout)
plot.add_tools(HoverTool(tooltips=[("ID", "#index"), ("Internal IP", "#Internal")]), PointDrawTool(renderers = [graph_renderer.node_renderer], empty_value = 'black'), TapTool(), BoxSelectTool(), BoxEditTool(), BoxZoomTool(), PanTool(), WheelZoomTool(), ZoomInTool(), ZoomOutTool(), SaveTool(), UndoTool())
graph_renderer.node_renderer.glyph = Circle(size=10, fill_color=Spectral4[0])
graph_renderer.node_renderer.selection_glyph = Circle(size=10, fill_color=Spectral4[2])
graph_renderer.node_renderer.hover_glyph = Circle(size=10, fill_color=Spectral4[1])
graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=1)
graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2], line_width=3)
graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=3)
graph_renderer.selection_policy = NodesAndLinkedEdges()
graph_renderer.inspection_policy = NodesAndLinkedEdges()
plot.renderers.append(graph_renderer)
output_file("interactive_graphs.html")
show(plot)
I expect the nodes to be draggable. I want to click on a node and drag it so that it changes its position.
14/05/2019 Edit:
My imports:
import pandas as pd
import numpy as np
import networkx as nx
from bokeh.io import show, output_file
from bokeh.models import Plot, Range1d, MultiLine, Circle, HoverTool, TapTool, BoxEditTool, BoxSelectTool, BoxZoomTool, ResetTool, PanTool, WheelZoomTool, ZoomInTool, ZoomOutTool, SaveTool, UndoTool, PointDrawTool
from bokeh.models.graphs import from_networkx, NodesAndLinkedEdges, EdgesAndLinkedNodes
from bokeh.palettes import Spectral4
import warnings
import matplotlib.pyplot as plt
%matplotlib notebook
from IPython.display import display, HTML
from IPython.core.interactiveshell import InteractiveShell
From: https://discourse.bokeh.org/t/networkx-import-and-pointdrawtool/3512
"The proximate cause of the problem is that the tool requires access to
glyph.x.field and glyph.y.field but both of these are null for the Circle node
renderer. The GraphRenderer is the only example of a “composite” renderer, so it’s
entirely possible (probable) that there is some interaction problem specific to it
with the PointDrawTool. The next appropriate step would be to make a bug report
issue on GitHub 5 with details."
It would be nice if they solved it.

How to add icon and fanart to xbmc addon on menu

I can get them to show up within the addon, but I can't get them to show up on the addon select screen. Can someone show me what I'm doing wrong? (this is my first addon and I'm new at this so please forgive if it's a rookie mistake.)
import sys
import xbmcgui
import xbmcplugin
addon_handle = int(sys.argv[1])
xbmcplugin.setContent(addon_handle, 'audio')
url = 'http://chadmasta5.weebly.com/uploads/6/0/1/9/6019696/listen.pls'
li = xbmcgui.ListItem('Listen', iconImage='http://i60.tinypic.com/2hnozec.png')
li.setProperty('fanart_image', 'http://i59.tinypic.com/b669vt.jpg')
xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li)
xbmcplugin.endOfDirectory(addon_handle)

Categories