Python Folium – Adding New Marker to Existing Map File

foliumpython

I have the Python codes below to work on Folium map. I want to add a new marker to my old map file and focus the map on the new marker. However, it does not write the new marker; instead it seems to add the new marker on a new map file or it overwrites the markers in the old file. How can I fix this problem? Here are the codes;

import folium

# Specify the new latitude and longitude for the desired map focus
new_latitude = 15.0191
new_longitude = 120.7040

# Load the existing map from the HTML file
existing_map = '...map_with_multiple_pins.html'
existing_map = folium.Map(location=[0, 0], zoom_start=10)

# Create a new marker with a popup
popup = folium.Popup("You are here..")
marker = folium.Marker(location=[new_latitude, new_longitude], popup=popup)

# Add the marker to the existing map
existing_map.add_child(marker)

# Save the modified map to a new HTML file
modified_map_file = '..modified_map.html'
existing_map.save(modified_map_file)
print(f"Modified map saved to {modified_map_file}")

Best Answer

Please excuse my terminology misuse. Folium is a Python library that accesses and produces the JavaScript and HTML scripts required to produce a Leaflet map in Python.

Markers and data held within a Leaflet map are stored (hard-coded) in the HTML code itself of the map.

Your code as it stands, produces a new map everytime it runs and overwrites whatever was in the map to begin with.

existing_map = folium.Map(location=[0, 0], zoom_start=10)

Creates a new instance of the Leaflet map.

You should be able to test this by running the code, checking the HTML document and look for the map reference number. Re-run the code and look for the map reference again. They should be different.

To do what you want to do, I would suggest created a list of coordinates, appending the new coordinates to this list and then run your Folium script. This way you will not lose the initial coordinates.

The Answer provided here: https://stackoverflow.com/questions/42330802/can-i-add-a-sequence-of-markers-on-a-folium-map

Has a good example. You can also set the map extent by accessing the last coordinate in the list.

coord_list = [[0,0][1,1]] #Add your new coordinates to the end of this list
existing_map = folium.Map(location=[coord_list[-1][0], coord_list[-1][1], zoom_start=10)

Another option would be to create a GeoJSON file and store it on a server. Append your coordinates to this GeoJSON and ingest the data using JavaScript into your Folium map.

Related Question