I have a folium map of a neighborhood in New York City generated using the following code:
m = folium.Map(location=[40.7035, -73.990],
zoom_start=16.5,
tiles='cartodbpositron')
I then try to add lines connecting points on the map using folium.PolyLine()
, but even though I see them listed when I call m._children
, they don't show up on the map.
Here's the code to create the lines, where G is a networkx graph:
for x, y in G.edges():
points = [nx.get_node_attributes(G, 'loc')[x], nx.get_node_attributes(G, 'loc')[y]]
egde = folium.PolyLine(locations=points, weight=5, color='red')
edge.add_to(m)
A sample point
:
[(-73.986635, 40.703988), (-73.988683, 40.702674)]
Output of m.children
(first few lines):
OrderedDict([('cartodbpositron',
<folium.raster_layers.TileLayer at 0x12279feb8>),
('poly_line_ae5785771a2148c5a8559cb0085b10a4',
<folium.vector_layers.PolyLine at 0x122892128>),
('poly_line_ee73b495559940d484064e8c8492eda5',
<folium.vector_layers.PolyLine at 0x1229734a8>),
('poly_line_415a7ed70a2a425e876c8a6711408a6a', ...
Any idea what I might be doing wrong?
This is kind of odd that folium polyline expects coordinates in [latitude, longitude]
format, whereas in general accepted format is [longitude, latitude]
.
Let's take an example: I'm assuming you are using OSRM to get geometries.
OSRM geometries returns coordinates in the form of [[longitude,latitude],...]
.
If you'll directly use them with folium, it'll not show the polyline.
Reverse the geometry coordinates using following function:
def reverse_lon_lat(x):
a = [[p[1], p[0]] for p in x]
return a
and draw the polylines you intend to.