'How to use TimestampedGeoJson and folium to create a plotting animation for GPS points?

This is my code:

import folium
from folium import plugins
import os
import json
import natsort

def plot_app_gps():
    arg_file = open('args.json', 'r+')
    args = json.load(arg_file)

    loc_files = [i for i in natsort.natsorted(os.listdir(os.path.join(args['imgs_loc'], 'location_data')))]
    lat, long = 0, 0
    for loc_file in loc_files:
        loc_json = json.load(open(os.path.join(args['imgs_loc'], 'location_data', loc_file), 'r+'))
        lat += round(float(loc_json['latitude']), 8)
        long += round(float(loc_json['longitude']), 8)

    # Create the map used to visualise the locations of the images.
    map_centre_lat = lat / len(loc_files)
    map_centre_lon = long / len(loc_files)

    my_map = folium.Map(location=[map_centre_lat, map_centre_lon], zoom_start=16, )

    # Draw a red circle on the centre of the map.
    folium.CircleMarker((map_centre_lat, map_centre_lon), radius=7, color='#FF0000', fill_color='#0080bb').add_to(my_map)

    features = []
    import datetime

    for loc_file in loc_files:
        loc_json = json.load(open(os.path.join(args['imgs_loc'], 'location_data', loc_file), 'r+'))
        '1970-01-01 00:00:00'
        feature = {
            'type': 'Feature',
            'geometry': {
                'type': 'Point',
                'coordinates': [float(loc_json['latitude']), float(loc_json['longitude'])]
            },
            'properties': {
                'time': str(datetime.datetime.now() + datetime.timedelta(0,1)).split('.')[0],
                'style': {'color': ''},
                'icon': 'circle',
                'iconstyle': {
                    'fillOpacity': 0.8,
                    'stroke': 'true',
                    'radius': 5
                }
            }
        }
        features.append(feature)

    plugins.TimestampedGeoJson(features,
                       period='PT1H',
                       duration='PT1H',
                       transition_time=1000,
                       auto_play=True).add_to(my_map)

    my_map.save(os.path.join(args['root_dir'], 'map_with_gps_locations.html'))

But I do not see the animation of plotting points? The time bar at the bottom left just stays at the starting time and never bothers moving. I have plotted all the GPS coordinates on the map using just folium and they are correct. Now, I want to animate the plotting process but the TimestampedGeoJson doesn't work.



Solution 1:[1]

I managed to finally make it work using the following code:

import folium
from folium import plugins
import os
import json
import natsort

def plot_app_gps():
    arg_file = open('args.json', 'r+')
    args = json.load(arg_file)

    loc_files = [i for i in natsort.natsorted(os.listdir(os.path.join(args['imgs_loc'], 'location_data')))]
    lat, long = 0, 0
    for loc_file in loc_files:
        loc_json = json.load(open(os.path.join(args['imgs_loc'], 'location_data', loc_file), 'r+'))
        lat += round(float(loc_json['latitude']), 8)
        long += round(float(loc_json['longitude']), 8)

    # Create the map used to visualise the locations of the images.
    map_centre_lat = lat / len(loc_files)
    map_centre_lon = long / len(loc_files)

    my_map = folium.Map(location=[map_centre_lat, map_centre_lon], zoom_start=16, )

    # Draw a red circle on the centre of the map.
    folium.CircleMarker((map_centre_lat, map_centre_lon), radius=7, color='#FF0000', fill_color='#0080bb').add_to(my_map)

    features = []
    import datetime

    current_time = datetime.datetime.now()
    extra_seconds = 0
    for loc_file in loc_files:
        loc_json = json.load(open(os.path.join(args['imgs_loc'], 'location_data', loc_file), 'r+'))
        now = str(current_time + datetime.timedelta(0, 60*extra_seconds)).split('.')[0]
        feature = {
            'type': 'Feature',
            'geometry': {
                'type': 'Point',
                'coordinates': [float(loc_json['longitude']), float(loc_json['latitude'])]
            },
            'properties': {
                'time': now,
                'style': {'color': ''},
                'icon': 'circle',
                'iconstyle': {
                    'fillColor': '#0000FF',
                    'fillOpacity': 0.8,
                    'stroke': 'true',
                    'radius': 5
                }
            }
        }
        features.append(feature)
        extra_seconds += 1

    plugins.TimestampedGeoJson(features,
                       period='PT1H',
                       duration='PT1M',
                       transition_time=1000,
                       auto_play=True).add_to(my_map)

    my_map.save(os.path.join(args['root_dir'], 'map_with_gps_locations.html'))

Solution 2:[2]

This is the sample code from the official website. enjoy it?

https://nbviewer.org/github/python-visualization/folium/blob/main/examples/Plugins.ipynb#Timestamped-GeoJSON

import os

import folium
from folium import plugins


m = folium.Map(location=[35.68159659061569, 139.76451516151428], zoom_start=16)

# Lon, Lat order.
lines = [
    {
        "coordinates": [
            [139.76451516151428, 35.68159659061569],
            [139.75964426994324, 35.682590062684206],
        ],
        "dates": ["2017-06-02T00:00:00", "2017-06-02T00:10:00"],
        "color": "red",
    },
    {
        "coordinates": [
            [139.75964426994324, 35.682590062684206],
            [139.7575843334198, 35.679505030038506],
        ],
        "dates": ["2017-06-02T00:10:00", "2017-06-02T00:20:00"],
        "color": "blue",
    },
    {
        "coordinates": [
            [139.7575843334198, 35.679505030038506],
            [139.76337790489197, 35.678040905014065],
        ],
        "dates": ["2017-06-02T00:20:00", "2017-06-02T00:30:00"],
        "color": "green",
        "weight": 15,
    },
    {
        "coordinates": [
            [139.76337790489197, 35.678040905014065],
            [139.76451516151428, 35.68159659061569],
        ],
        "dates": ["2017-06-02T00:30:00", "2017-06-02T00:40:00"],
        "color": "#FFFFFF",
    },
]

features = [
    {
        "type": "Feature",
        "geometry": {
            "type": "LineString",
            "coordinates": line["coordinates"],
        },
        "properties": {
            "times": line["dates"],
            "style": {
                "color": line["color"],
                "weight": line["weight"] if "weight" in line else 5,
            },
        },
    }
    for line in lines
]

plugins.TimestampedGeoJson(
    {
        "type": "FeatureCollection",
        "features": features,
    },
    period="PT1M",
    add_last_point=True,
).add_to(m)


m.save(os.path.join('D://test', 't.html'))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Allen