User: write a function which uses folium map to plot multiple satellite groundtracks, each with a different color. It should use the timeline slider to show the orbit moving, assume lat lon data is already available
Assistant: To create a function that uses Folium to plot multiple satellite ground tracks with different colors and includes a timeline slider to visualize the orbits moving, you can follow these instructions. This function assumes that you have the latitude and longitude data for multiple satellites available in a specific format. Below is a basic implementation using Folium and the branca library for color mapping.
First, make sure to install the necessary libraries if you haven't done so:
bash
pip install folium branca
Then, you can use the following code:
python
Assistant
import folium
import numpy as np
import pandas as pd
from folium.plugins import TimestampedGeoJson
def plot_ground_tracks(lat_lon_data, satellite_names, timeline):
"""
Plots multiple satellite groundtracks on a Folium map with a timeline slider.
Parameters:
- lat_lon_data: Dictionary where keys are satellite names and values are lists of tuples (lat, lon, timestamp)
- satellite_names: List of satellite names for which to plot the tracks
- timeline: Time range for the timestamp slider
"""
# Initialize the Folium map
m = folium.Map(location=[0, 0], zoom_start=2)
# Define a color map for different satellites
color_map = {
'Satellite 1': 'blue',
'Satellite 2': 'green',
'Satellite 3': 'red',
'Satellite 4': 'orange',
'Satellite 5': 'purple'
}
# Create GeoJSON features for each satellite
features = []
for satellite in satellite_names:
if satellite not in lat_lon_data:
continue
# Retrieving latitude, longitude, and timestamps
data = lat_lon_data[satellite]
# Add paths to features list with color coding
features.append({
'type': 'Feature',
'geometry': {
'type': 'LineString',
'coordinates': [(lon, lat) for lat, lon, timestamp in data]
},
'properties': {
'times': [timestamp.isoformat() for lat, lon, timestamp in data], # Ensure timestamps are in ISO format
'style': {'color': color_map.get(satellite, 'black')},
'name': satellite
}
})
# Create the Timestamped GeoJson layer
timestamped_geojson = TimestampedGeoJson(
{'type': 'FeatureCollection', 'features': features},
period='PT1M', # Change the period as needed
add_last_point=True,
auto_play=True
)
# Add the layer to the map
m.add_child(timestamped_geojson)
return m
# Example usage
if __name__ == "__main__":
# Mock data: Replace this with your actual latitude, longitude, and timestamp data
example_data = {
'Satellite 1': [(34.05, -118.25, pd.Timestamp('2023-01-01T00:00:00'))],
'Satellite 2': [(40.71, -74.01, pd.Timestamp('2023-01-01T00:00:10'))],
'Satellite 3': [(51.51, -0.13, pd.Timestamp('2023-01-01T00:00:20'))],
'Satellite 4': [(48.85, 2.35, pd.Timestamp('2023-01-01T00:00:30'))],
'Satellite 5': [(35.68, 139.76, pd.Timestamp('2023-01-01T00:00:40'))]
}
satellites = ['Satellite 1', 'Satellite 2', 'Satellite 3', 'Satellite 4', 'Satellite 5']
timeline = ['2023-01-01T00:00:00', '2023-01-01T00:00:50']
# Create the map
folium_map = plot_ground_tracks(example_data, satellites, timeline)
# Save map to HTML file
folium_map.save("satellite_groundtracks.html")
Explanation of the Code
Function Definition: The function plot_ground_tracks accepts the lat_lon_data, a list of satellite_names, and a timeline.
Initialization: A Folium map is created centered at the equator.
Feature Creation: Each satellite's ground track is converted into a GeoJSON feature. It generates a LineString representing the orbit path and associates it with timestamps and a specific color.
Timestamped Layer: The TimestampedGeoJson layer is created for the individual satellite tracks.
Example Data: The example data simulates latitude, longitude, and timestamp information for different satellites.
Saving the Map: Finally, the map is saved as an HTML file, which you can view in a browser.
You can modify the colors and symbols as needed. Make sure to update the example_data with your actual satellite tracking data.
User: great, but dont use timestamped geojson. Instead use timelineslider
Assistant:
If you want to use the TimelineSlider for visualizing the ground tracks of multiple satellites rather than the TimestampedGeoJson, you can create your own function using Folium combined with a custom JavaScript solution. Unfortunately, Folium does not directly support a TimelineSlider, but we can achieve a similar effect using custom Leaflet elements within Folium.
Here's an improved version of the previous function that allows you to create a map with a timeline slider effect using a combination of custom JavaScript and Folium:
Step-by-step Code:
python
import folium
import pandas as pd
def plot_ground_tracks_with_slider(lat_lon_data, satellite_names):
"""
Plots multiple satellite groundtracks on a Folium map with a custom timeline slider.
Parameters:
- lat_lon_data: Dictionary where keys are satellite names and values are lists of tuples (lat, lon, timestamp)
- satellite_names: List of satellite names for which to plot the tracks
"""
# Create the base map
m = folium.Map(location=[0, 0], zoom_start=2)
# Define color mapping for different satellites
color_map = {
'Satellite 1': 'blue',
'Satellite 2': 'green',
'Satellite 3': 'red',
'Satellite 4': 'orange',
'Satellite 5': 'purple'
}
# Using an HTML string to incorporate the slider UI
slider_html = """
<div style="position: absolute; top: 10px; left: 10px; z-index: 999; background-color: white; padding: 10px;">
<input type="range" min="0" max="{max}" value="0" id="timeSlider" />
<label for="timeSlider">Time: <span id="timeValue">0</span></label>
</div>
<script>
const timeData = {timeData};
const satelliteTracks = {satelliteTracks};
const map = window.L.map(this._container);
document.getElementById('timeSlider').oninput = function () {
const timeIndex = parseInt(this.value);
document.getElementById('timeValue').innerText = timeData[timeIndex];
satelliteTracks.forEach((track, index) => {
if (track.length > timeIndex) {
const coord = track[timeIndex];
window.L.marker([coord[0], coord[1]], { color: track.color }).addTo(map);
}
});
};
</script>
"""
# Build satellite data for the JavaScript slider
max_time_index = 0
satellite_data = []
time_labels = []
for satellite in satellite_names:
if satellite not in lat_lon_data:
continue
data = lat_lon_data[satellite]
time_labels.extend([pd.Timestamp(ts).isoformat() for _, _, ts in data])
coords = [(lat, lon) for lat, lon, _ in data]
satellite_data.append({'name': satellite, 'coords': coords, 'color': color_map.get(satellite, 'black')})
max_time_index = max(max_time_index, len(data))
# Prepare JavaScript data structures
slider_html = slider_html.format(
max=max_time_index - 1,
timeData=time_labels,
satelliteTracks=[{"name": track['name'], "coords": track['coords'], "color": track['color']} for track in satellite_data]
)
m.get_root().html.add_child(folium.Element(slider_html))
return m
# Example usage
if __name__ == "__main__":
# Mock data: Replace this with your actual latitude, longitude, and timestamp data
example_data = {
'Satellite 1': [(34.05, -118.25, pd.Timestamp('2023-01-01T00:00:00')),
(34.06, -118.30, pd.Timestamp('2023-01-01T00:01:00')),
(34.07, -118.40, pd.Timestamp('2023-01-01T00:02:00'))],
'Satellite 2': [(40.71, -74.01, pd.Timestamp('2023-01-01T00:00:10')),
(40.72, -74.10, pd.Timestamp('2023-01-01T00:01:10')),
(40.73, -74.20, pd.Timestamp('2023-01-01T00:02:10'))],
'Satellite 3': [(51.51, -0.13, pd.Timestamp('2023-01-01T00:00:20')),
(51.52, -0.15, pd.Timestamp('2023-01-01T00:01:20')),
(51.53, -0.17, pd.Timestamp('2023-01-01T00:02:20'))]
}
satellites = ['Satellite 1', 'Satellite 2', 'Satellite 3']
# Create the map
folium_map = plot_ground_tracks_with_slider(example_data, satellites)
# Save map to HTML file
folium_map.save("satellite_groundtracks_with_slider.html")
Explanation of the Code
Function Definition: Similar to the previous code, plot_ground_tracks_with_slider accepts latitude, longitude, and timestamp data for multiple satellites.
HTML and JavaScript slider creation: A slider is created using an HTML string. The JavaScript handles the logic for moving through the time steps, updating the displayed satellite positions based on the current slider value.
Data Preparation: The function prepares the coordinates and timestamps for each satellite.
Map Rendering: The slider and interactivity are embedded into the Folium map. As you move the slider, the map updates to show the corresponding satellite position.
Example Data: Mock satellite data is provided. Replace this with your actual data as needed.
Save the Map: The map is saved as an HTML file, which can be opened in a browser.
Notes:
Ensure that the leaflet libraries (which Folium uses) support the features required for the slider functionality.
Modify the JavaScript logic to customize how the ground tracks are displayed, e.g., clearing previous markers, updating visualizations, etc., for better user experience.
This implementation provides a convenient way to visualize multiple satellite ground tracks over time, with each track distinctly colored.