Search code examples
pythonpandascsvfolium

Python Folium map not displaying when certain column is read from CSV?


I'm trying to create a Folium map for internal marketing purposes for my company. The map loads fine the way it is. However, when I want a certain column to display in the popup text the map fails to load. Here's what the code looks like:

#read csv and create dataframe
df = pd.read_csv(sheet_url, delimiter=",", header=0, encoding='latin-1', engine='python') 
#turn dataframe from dict into a list
csv = [list(x) for x in df.values]
#organize data into array
locations = []
for location in csv:
    coords = [location[0], location[1]]
    try:
        locations.append({'company' : location[2], 'country' : location[3], 'products' : location[3], 'potential' : location[4], 'method' : location[13], 'note' : location[14], 'hover': f"{location[3]}<br>{location[2]}", 'click': f"<a href={location[9]}>Website</a><br>{location[13]}<br>{location[14]}", 'coordinates' : coords})
    except:
        print("failed because of some error")

The problem occurs when I try to add location[14] to the popup, but it does not throw an error here. Nor does it throw an error with the iteration to add the markers to the map:

for x in locations:
    try:
        if x['potential'] == "Current Customer":
            folium.Marker(location = (x['coordinates']), popup = x['click'], tooltip = x['hover'], icon=folium.Icon(color='green')).add_to(current_cluster)
        else:
            folium.Marker(location = (x['coordinates']), popup = x['click'], tooltip = x['hover'], icon=folium.Icon(color='red')).add_to(potential_cluster)
    except:
        print("failed")

The column labeled 'note' is the one I'm having problems with.

I've tried so far:

  1. Using ' '.join(map(str, location[14])), while looping through the csv. The map loads, the text is in the popup, but separated by spaces (L i k e t h i s).
  2. Changing the delimiter from , to anything else, but it creates a parser error. There are a lot of different characters used in each row, but I'm not sure the delimiter is the issue.
  3. On Chrome, the debugger says Uncaught SyntaxError: Octal escape sequences are not allowed in template strings.

I think the issue is occurring when I'm adding the markers to the map? But there are no errors thrown, just the map won't load if I include the 'notes' into the popup. Any help is appreciated, thank you.


Solution

  • It's likely due to a special character in the string. I have two ideas:

    • Make sure you have the newest version of folium (0.7.0), this behavior was improved.
    • Try escaping your text before passing it: html.escape(my_string)

    Can you share the exact value in location[14].note? That would definitely help debugging this. Furthermore, use the developer tools of your browser to see the error message in your console.