It is very easy to work with geo coordinates and maps with Python thanks to so many libraries such as folium, geopy.
Let’s create a map with python that shows swimming water measurement stations; this will be a short script that outputs the html with the map.
The first we need is data; where do we find the list of swimming water measurement stations? Luckily California has an open data source for these type of information, for our example we can use the data from: https://data.ca.gov/datastore/dump/848d2e3f-2846-449c-90e0-9aaf5c45853e?q=&sort=_id+asc&fields=StationName,StationCode,LastSampleDate,TargetLatitude,TargetLongitude,Datum&filters={}&format=json
response = requests.get(url, allow_redirects=True)
#save the response json
open('safe2swim.json', 'wb').write(response.content)
We can download the data and save it to a json file:
I wan
Now that we have the file, we can read it and load it to json structure. I would like to draw the map, and put the user’s location on the center; so I need to find out the user’s location. If you don’t have the package; please install geocoder library, using this library you can get user’s ip address and convert that into. longitude and latitude.
#if you dont have geocoder : pip install gecoder
mylocation = geocoder.ip('me')
myLong = mylocation.latlng[1]
myLat = mylocation.latlng[0]
The rest of the code is simply iterating through the json data we downloaded and put the marks on the map; here is the rest of the script:
waterMap = folium.Map([myLat,myLong],
zoom_start=12,
fill_color="RdYlGn_r",
fill_opacity=0.8,
line_opacity=0.3,
nan_fill_color="white",
legend_name="Safe Swimming Water Measurement Stations in California",
)
#iterate through the dataset to calculate the distance to me
for measurement in swimDataJson["records"]:
if(measurement[3]== "NaN" or measurement[4] == "NaN"):
continue
folium.Marker(
location=[measurement[3], measurement[4]],
popup=measurement[0],
).add_to(waterMap)
#save map
waterMap.save("text.html")
You can find the full script here: https://github.com/vlknzn/-Safe2Swim