大家好,歡迎來到 Crossin的編程教室 !
今天給大家分享一個開源項目:Open Notify。它的目的是將 NASA(美國國家航空航天局)的一些數據開放為簡單的編程接口。
open-notify.org 的作者做了一些工作,以獲取原始數據並將其轉換為與太空和太空飛行器有關的API。
本文將通過這個接口,獲取得到國際空間站的位置,並實時地繪製到地圖上:
感謝 cr0sis/Real-time-International-space-station-tracker 的貢獻。
為了實現本文的目標,你得先安裝 ISS_Info:
下面分步驟講解整套繪製流程
為了實時展示國際空間站的路徑,需要使用turtle繪製曲線,因此可以創建一個turtle畫布,將背景設為地球:
import ISS_Infoimport turtleimport timeimport jsonimport urllib.request
screen = turtle.Screen()screen.setup(720,360)screen.setworldcoordinates(-180,-90,180,90)screen.bgpic("map.png")screen.bgcolor("black")screen.register_shape("isss.gif")screen.title("Real time ISS tracker")
iss = turtle.Turtle()iss.shape("isss.gif")2.獲取空間站的人數如果能知道空間站上的太空人人數,我們就能更加準確的跟蹤國際空間站。幸運的是open-notify確實提供了這樣的接口。
為了獲取人數信息,我們必須向下列接口請求拿到數據,並將相應的太空人名字寫在左上角:
http://api.open-notify.org/astros.jsonastronauts = turtle.Turtle()astronauts.penup()astronauts.color('black')astronauts.goto(-178,86)astronauts.hideturtle()url = "http://api.open-notify.org/astros.json"response = urllib.request.urlopen(url)result = json.loads(response.read())print("There are currently " + str(result["number"]) + " astronauts in space:")print("")astronauts.write("People in space: " + str(result["number"]), font=style)astronauts.sety(astronauts.ycor() - 5)
people = result["people"]
for p in people: print(p["name"] + " on: " + p["craft"]) astronauts.write(p["name"] + " on: " + p["craft"], font=style) astronauts.sety(astronauts.ycor() - 5)3.繪製空間站位置為了能夠繪製空間站的實時位置,我們需要請求拿到空間站的位置信息。請求的接口是:
http://api.open-notify.org/iss-now.json不過作者將其封裝成了一個函數,我們直接調用 iss_current_loc 即可,循環獲取國際空間站位置:
while True: location = ISS_Info.iss_current_loc() lat = location['iss_position']['latitude'] lon = location['iss_position']['longitude'] print("Position: \n latitude: {}, longitude: {}".format(lat,lon)) pos = iss.pos() posx = iss.xcor() if iss.xcor() >= (179.1): iss.penup() iss.goto(float(lon),float(lat)) time.sleep(5) else: iss.goto(float(lon),float(lat)) iss.pendown() time.sleep(5)我們還可以標出自己目前所處的位置,以查看和國際空間站的距離及空間站經過你上空的時間點(UTC)。
while True: location = ISS_Info.iss_current_loc() lat = location['iss_position']['latitude'] lon = location['iss_position']['longitude'] print("Position: \n latitude: {}, longitude: {}".format(lat,lon)) pos = iss.pos() posx = iss.xcor() if iss.xcor() >= (179.1): iss.penup() iss.goto(float(lon),float(lat)) time.sleep(5) else: iss.goto(float(lon),float(lat)) iss.pendown() time.sleep(5)不過這裡值得注意的是,iss-pass.json這個接口的緯度計算必須在-90到90之內,因此深圳的緯度需要減去90.
最終效果如下:
在公眾號Crossin的編程教室回復關鍵字「國際空間站」可獲取本文完整源碼
_往期文章推薦_