Home > Software design >  How to make cluster on Folium with Dataframe?
How to make cluster on Folium with Dataframe?

Time:04-29

I have tried to make a Cluster on a Folium map. I have a dataframe as below.

enter image description here

The code for making the Cluster on Folium map is below

import os
import folium
import webbrowser
import shutil
import pandas as pd
from folium import plugins
from collections import defaultdict
from pathlib import Path
from folium.plugins import MarkerCluster

my_dir_path = "C:\\Users\\xxx\\Sub_Folder"

results = defaultdict(list)
for file in Path(my_dir_path).iterdir():
    with open(file, "r") as file_open:
        results["Latitude"].append(file.name[0:9])
        results["Longitude"].append(file.name[10:19])
        results["Date"].append(file.name[23:25])
        results["Month"].append(file.name[20:22])
        results["Year"].append(file.name[26:30])
        results["Time"].append(file.name[31:36])
        results["Type"].append(file_open.read(1))
        
df_full = pd.DataFrame(results)

#Delete duplicate data
df = df_full.drop_duplicates()

df['Type'] = df['Type'].replace(
    to_replace=['0', '1', '2', '3'], 
    value=['Buffalo', 'Elephant', 'Rhino', 'Zebra'])
df

m = folium.Map(location=[15.170121, 99.159373], zoom_start=11)
folium.LayerControl().add_to(m)
marker_cluster = MarkerCluster().add_to(m)

for row in df.itertuples():
    folium.Marker(location=[row.Latitude,row.Longitude],popup=row.Type).add_to(marker_cluster)

m

I ran the code but map doesn't show anything. How do correct this?

enter image description here

CodePudding user response:

The cause is probably that the cluster is set up first and the marker settings are made later. Therefore, the cluster setting was done after the loop process.

import folium
from folium.plugins import MarkerCluster

m = folium.Map(location=[15.170121, 99.159373], zoom_start=12)
marker_cluster = MarkerCluster(
    name="clustered name",
).add_to(m)

for row in df.itertuples():
    #print(row)
    folium.Marker(location=[row.Latitude,row.Longitude],popup=row.Type).add_to(marker_cluster)

folium.LayerControl().add_to(m)

m

enter image description here

  • Related