在编写有关 OpenStreetMap API 的代码时,我的代码在
route_coordinates
变量(行 route_coordinates = response['routes'][0]['geometry']['coordinates']
)上出现错误。
错误是:
TypeError: string indices must be integers
即使经过深思熟虑和重组,我也无法弄清楚。
import folium
import requests
# set up the OpenStreetMap API endpoint and parameters
endpoint = 'https://nominatim.openstreetmap.org/search'
params = {
'format': 'json',
'limit': 1,
'q': ''
}
# prompt the user to enter their starting location and destination
start_location = input('Enter your starting location: ')
end_location = input('Enter your destination: ')
# get the latitude and longitude of the starting location
params['q'] = start_location
response = requests.get(endpoint, params=params).json()
start_lat = response[0]['lat']
start_lon = response[0]['lon']
# get the latitude and longitude of the destination
params['q'] = end_location
response = requests.get(endpoint, params=params).json()
end_lat = response[0]['lat']
end_lon = response[0]['lon']
# create a map centered on the starting location
map = folium.Map(location=[start_lat, start_lon], zoom_start=12)
# add a marker for the starting location and the destination
start_marker = folium.Marker(location=[start_lat, start_lon], popup=start_location)
end_marker = folium.Marker(location=[end_lat, end_lon], popup=end_location)
start_marker.add_to(map)
end_marker.add_to(map)
# add a polyline to show the route between the starting location and the destination
route_url = 'https://router.project-osrm.org/route/v1/driving/{},{};{},{}?overview=full'.format(start_lon,
start_lat,
end_lon,
end_lat)
response = requests.get(route_url).json()
route_coordinates = response['routes'][0]['geometry']['coordinates']
polyline = folium.PolyLine(locations=route_coordinates, weight=5, color='blue')
polyline.add_to(map)
# display the map
map