首页 > 解决方案 > 在 Cartopy 地图中实时更新国际空间站位置

问题描述

我正在编写简单的脚本,以使用 cartopy 在世界地图上定位 ISS。这是代码及其输出

import requests
from datetime import datetime
import cartopy.crs as ccrs
import matplotlib.pyplot as plt

# finding the current location   
url = 'http://api.open-notify.org/iss-now.json'

r = requests.get(url)
data = r.json()

dt = data['timestamp']
lat = data['iss_position']['latitude']
lon = data['iss_position']['longitude']

print('Date and time : ',datetime.fromtimestamp(dt))
print('Latitude :',lat)
print('Longitude :',lon)

# plotting the location on map
plt.figure(figsize=(10,8))   
ax = plt.axes(projection=ccrs.PlateCarree())
ax.stock_img()

# lon lat
plt.scatter(float(lon),float(lat),color='blue', marker='o')
plt.show()

这部分工作正常,这是输出。

目前国际空间站在澳大利亚附近

现在我想要的是每 30 秒向 url 发出请求,并在地图上绘制位置以清除先前的位置。是否可以与 matplotlib. 我对matplotlib了解不多。请帮忙。

我当前的代码每次都会创建带有散点的新图。我只想要一张当前位置和先前位置已被删除的地图。

这是我当前的代码

import requests
import matplotlib.pyplot as plt
import time
import cartopy.crs as ccrs

url = 'http://api.open-notify.org/iss-now.json'

plt.figure(figsize=(10,8))

ax = plt.axes(projection=ccrs.PlateCarree())
ax.stock_img()

plt.ion()

while True:
    r = requests.get(url)
    data = r.json()

    dt = data['timestamp']
    lat = data['iss_position']['latitude']
    lon = data['iss_position']['longitude']

    plt.scatter(float(lon),float(lat),color='blue', marker='o')
    plt.show()
    time.sleep(30)

标签: pythonmatplotlibmapscartopy

解决方案


matplotlib.animation.FuncAnimation专门为这种情节而存在。尝试这个

import requests
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import time
import cartopy.crs as ccrs

url = 'http://api.open-notify.org/iss-now.json'

plt.figure(figsize=(10,8))
ax = plt.axes(projection=ccrs.PlateCarree())
ax.stock_img()

plt.ion()
plt.show()
s = plt.scatter([], [], color='blue', marker='o')

def animate(i):
    r = requests.get(url)
    data = r.json()

    dt = data['timestamp']
    lat = data['iss_position']['latitude']
    lon = data['iss_position']['longitude']

    s.set_offsets([float(lon), float(lat)])
    time.sleep(30)

anim = FuncAnimation(plt.gcf(), animate)
plt.show()

这将显示(加速演示):

在此处输入图像描述


推荐阅读