问题
Im trying to visualize data using folium maps, and I have to plot all Finlands' city names to the map. I've tried to use pandas dataframe since all my data is in csv format. Here's the code I've tried so far.
import folium
from folium import plugins
import ipywidgets
import geocoder
import geopy
import numpy as np
import pandas as pd
from vega_datasets import data as vds
m = folium.Map(location=[65,26], zoom_start=5)
# map
map_layer_control = folium.Map(location=[65, 26], zoom_start=5)
# add tiles to map
folium.raster_layers.TileLayer('Open Street Map').add_to(map_layer_control)
folium.raster_layers.TileLayer('Stamen Terrain').add_to(map_layer_control)
folium.raster_layers.TileLayer('Stamen Toner').add_to(map_layer_control)
folium.raster_layers.TileLayer('Stamen Watercolor').add_to(map_layer_control)
folium.raster_layers.TileLayer('CartoDB Positron').add_to(map_layer_control)
folium.raster_layers.TileLayer('CartoDB Dark_Matter').add_to(map_layer_control)
# add layer control to show different maps
folium.LayerControl().add_to(map_layer_control)
# display map
map_layer_control
list = {'REGION': ['Kajaani','Lappeenranta','Pudasjärvi'],
'CUSTOMERS':['7','4','64']}
list = pd.DataFrame(list)
# geocode address and place marker on map
# map
map_zoo = folium.Map(location=[65,26], zoom_start=4)
# get location information for address
for i in range(0,len(list)):
address = geocoder.osm(list['REGION'])
# address latitude and longitude
address_latlng = [address.lat, address.lng]
# add marker to map
folium.Marker(address_latlng, popup='INFO', tooltip='Click for more information!').add_to(map_zoo)
# display map
map_zoo
However this code only adds a marker to the last city 'Pudasjärvi'
回答1:
You can use geopy to get coordinates and then use a loop to add markers to your map:
import folium
from geopy.geocoders import Nominatim
import pandas as pd
geolocator = Nominatim(user_agent="example")
l = {'REGION': ['Kajaani','Lappeenranta','Pudasjärvi'],
'CUSTOMERS':['7','4','64']}
l['COORDS'] = []
for k in l['REGION']:
loc = geolocator.geocode(k).raw
l['COORDS'].append((loc['lat'], loc['lon']))
df = pd.DataFrame(l)
map_zoo = folium.Map(location=[65,26], zoom_start=4)
for i,r in df.iterrows():
folium.Marker(location=r['COORDS'],
popup = r['REGION'],
tooltip='Click for more information!').add_to(map_zoo)
map_zoo
and you get:
来源:https://stackoverflow.com/questions/62538253/adding-multiple-markers-to-a-folium-map-using-city-names-from-pandas-dataframe