在 Dash 仪表板中运行地图

时间:2021-05-31 07:04:18

标签: python plotly-dash

我编写了一些代码,用于在地图上返回国际空间站 (ISS) 的位置,并根据用户输入的纬度和经度计算 ISS 下次到达用户所在位置的时间。理想情况下,我想让地图通过 Dash 仪表板运行,但我不确定如何设置。我之前从未使用过 Dash,从我看过的教程来看,数据似乎是从电子表格或类似的东西中提取的。是否可以在 Dash 仪表板中运行我自己的地图代码?如果是这样,任何资源或指针将不胜感激。下面是我的代码供参考。

import ipyleaflet
import ipywidgets as widgets
from ipyleaflet import Map, Marker, basemaps, basemap_to_tiles, AwesomeIcon, Popup
from ipywidgets import HTML, interact
import json
import urllib.request
import time
import datetime
import dash
import dash_html_components as html
import dash_leaflet as dl
from dash.dependencies import Input, Output

url = 'http://api.open-notify.org/iss-now.json'
response = urllib.request.urlopen(url)
result = json.loads(response.read())

location = result['iss_position']
lat_iss = float(location['latitude'])
lon_iss = float(location['longitude'])

center = [lat_iss, lon_iss] # The centre of the map will be the latitude and longtitude of the ISS
zoom = 1.5
m = Map(basemap=basemaps.Esri.WorldImagery, center=center, zoom=zoom, close_popup_on_click=False)

icon1 = AwesomeIcon(name='space-shuttle', marker_color='blue', icon_color='white', spin=False)
marker = Marker(icon=icon1, location=(lat_iss, lon_iss), draggable=False) # Add a marker at the current location of the ISS that cannot be moved
m.add_layer(marker)

user_lat = input('What is your latitude? Remember to include minus sign if the latitude is south! ')
user_lon = input('What is your longitude?  Remember to include a minus sign if the longitude is west! ')
user_location = [user_lat, user_lon]

url ='http://api.open-notify.org/iss-pass.json'
url = url + '?lat=' + str(user_lat) + '&lon=' + str(user_lon) #The URL requires inputs for lat and lon. The users location are the inputs here.
response = urllib.request.urlopen(url)
result = json.loads(response.read())

over = (result['response'][1]['risetime'])
date_time = datetime.datetime.utcfromtimestamp(over).strftime('%d-%m-%Y at %H:%M:%S') #These place holders define the format of the displayed date and time.
print('The ISS will pass over you on the', date_time)

icon2 = AwesomeIcon(name='user', marker_color='lightred', icon_color='white', spin=False)
marker2 = Marker(icon=icon2, location=user_location, draggable=False) #Add  marker at the current location of the ISS that cannot be moved
m.add_layer(marker2) # Add layer that includes the users position
message1 = HTML()
message1.value = str(date_time)
popup = Popup(location=user_location, child=message1, close_button=True, auto_close=False, close_on_escape_key=False)
m.add_layer(popup) # Add layer that includes the popup message at the users location.

print('Current position of the International Space Station:')
print('Latitude of the ISS: ',lat_iss)
print('Longitude of the ISS: ',lon_iss)

m

1 个答案:

答案 0 :(得分:1)

如果您想使用 Dash,您需要使用 Dash 组件重写您的代码。对于 html 部分,您可以使用 dash_html_components。对于传单部分,您可以使用 dash-leaflet。 Dash 应用程序的数据源没有限制,为了简单起见,我假设教程使用电子表格数据。