Search code examples
pythonfoliumcolormap

Folium and ColorMap -- is not JSON serializable


The problem in question is: Object of type LinearColormap is not JSON serializable

maps['Zona de tarifa'] = maps['Zona de tarifa'].astype('int')
linear = cm.LinearColormap(["green", "yellow", "red"], vmin=maps['Zona de tarifa'].min(), vmax=maps['Zona de tarifa'].max())
map = folium.Map(location=[maps.new_latitud.mean(), maps.new_longitud.mean()], zoom_start=14, control_scale=True)
for index, location_info in maps.iterrows():
    folium.Marker([location_info["new_latitud"], location_info["new_longitud"]],icon=folium.Icon(color=linear),popup=location_info["Cliente"]+' '+location_info["Conductor"]).add_to(map)
map

I want to add color to my markers but that markers related to the variable or atributte "zona de tarifa" but i can't make it


Solution

  • Since the colors available for markers are limited, you can color-code them by specifying colors from the color list. We have applied your code using sample data.

    import folium
    import pandas as pd
    import random
    
    maps = pd.DataFrame({'new_latitud': [random.uniform(36, 43.48) for _ in range(10)],
                       'new_longitud': [random.uniform(-9.18, 3.19) for _ in range(10)],
                       'Zona de tarifa': [random.randint(0,10) for _ in range(10)]})
    
    # List of colors available for icons
    colors= ['lightgray', 'darkred', 'lightgreen', 'green', 'pink', 'darkgreen', 'lightblue', 'darkpurple', 'black', 
     'lightred', 'gray', 'orange', 'cadetblue', 'blue', 'purple', 'beige', 'white', 'darkblue', 'red']
    
    m = folium.Map(location=[maps.new_latitud.mean(), maps.new_longitud.mean()], zoom_start=6, control_scale=True)
    
    for index, location_info in maps.iterrows():
        folium.Marker([location_info["new_latitud"], location_info["new_longitud"]],
                      icon=folium.Icon(color=colors[int(location_info['Zona de tarifa'])]),
                      #popup=location_info["Cliente"]+' '+location_info["Conductor"]
                     ).add_to(m)
    m
    

    enter image description here