Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Folium PolyLine not showing up on map - folium 0.7.0 with python 3.6 (anaconda) in Jupyter notebook

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?

like image 368
Prratek Ramchandani Avatar asked Oct 30 '25 13:10

Prratek Ramchandani


2 Answers

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.

like image 84
mufassir Avatar answered Nov 01 '25 05:11

mufassir


This is because folium expects coords in [latitude, longitude] format. And if you have data in [longitude, latitude], then you can use the below helper function.

PATHC = [
    [90.422974, 23.825237],
    [90.419884, 23.82084],
    [90.410957, 23.816757],
    [90.404778, 23.812046],
    [90.402031, 23.803879],
    [90.401001, 23.792884],
    [90.398941, 23.780946],
    [90.395851, 23.770578],
    [90.394821, 23.762723],
    [90.394478, 23.759267],
]
PATHC = list(map(lambda x: [x[1], x[0]], PATHC))
like image 45
Mobasshir Bhuiya Avatar answered Nov 01 '25 05:11

Mobasshir Bhuiya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!