Search code examples
python-3.xtwittergeojsonargparsefolium

Understanding argparse to get dynamic maps with Geo-Location of tweets


I have found this python code online (twitter_map_clustered.py) which (I think) help create a map using the geodata of different tweets.:

from argparse import ArgumentParser
import folium
from folium.plugins import MarkerCluster
import json

def get_parser():
    parser = ArgumentParser()
    parser.add_argument('--geojson')
    parser.add_argument('--map')
    return parser

def make_map(geojson_file, map_file):

    tweet_map = folium.Map(Location=[50, 5], max_zoom=20)

    marker_cluster = MarkerCluster().add_to(tweet_map)

    geodata= json.load(open(geojson_file))

    for tweet in geodata['features']:
        tweet['geometry']['coordinates'].reverse()
        marker = folium.Marker(tweet['geometry']['coordinates'], popup=tweet['properties']['text'])
        marker.add_to(marker_cluster)

    #Save to HTML map file
    tweet_map.save(map_file)

if __name__ == '__main__':
    parser = get_parser()
    args = parser.parse_args()
    make_map(args.geojson, args.map)

I managed to extract the geo information of different tweets and save it into a geo_data.json file. However, I have trouble understanding the code, specially the function def get_parser().

It seems that we need to add argument when running the file in the command prompt. The argument should be geo_data.json. However, it is also asking for a map ? parser.add_argument('--map')

Why is it the case? In the code, aren't we creating the map here?

#Save to HTML map file
tweet_map.save(map_file)

Can you please help me. How would you run the python script ? Is there anything important I am missing ?


Solution

  • As explained by argparse documentation, it simply asks for the name of the geojson file and a name that your code will use to save the map.

    Therefore, you will run:

    python twitter_map_clustered.py --geojson geo_data.json --map mymap.html
    

    and you will get a map named mymap.html.