Skip to content

Displaying Interactive Maps in Streamlit: Easy Tutorials & Examples | st.map

Streamlit has revolutionized the way we build data applications. It's a powerful open-source Python library that allows data scientists and developers to create interactive web applications with ease. One of its most compelling features is st.map, a function that enables users to create and display interactive maps. This article will delve into the intricacies of st.map, providing you with practical examples and tutorials to enhance your data visualization skills.

In the world of data analysis and machine learning, location data plays a crucial role. Whether it's tracking the spread of a disease, analyzing traffic patterns, or understanding customer demographics, maps provide a visual representation that's easy to understand and interpret. Streamlit's st.map function is a tool that makes displaying this location data a breeze.

Understanding st.map in Streamlit

What is st.map in Streamlit?

In Streamlit, st.map is a function that allows you to create a map and plot data points onto it. It's a wrapper around the folium library, a powerful Python library used for visualizing geospatial data. The st.map function takes a pandas DataFrame that has either named columns "lat" and "lon" or "latitude" and "longitude" and plots it onto a map.

import streamlit as st
import pandas as pd
 
## Create a sample DataFrame with latitude and longitude values
data = pd.DataFrame({
    'latitude': [37.7749, 34.0522, 40.7128],
    'longitude': [-122.4194, -118.2437, -74.0060]
})
 
## Create a map with the data
st.map(data)

This simple piece of code will create a map and plot the data points from the DataFrame onto it. The map will automatically center itself around the data points and adjust the zoom level accordingly.

Displaying Maps in Streamlit

Displaying maps in Streamlit is as straightforward as calling the st.map function with the appropriate data. However, to make the most out of this feature, it's important to understand how to manipulate the data and customize the map to suit your needs.

For instance, you can adjust the zoom level of the map manually by passing an integer value to the zoom parameter. A higher value will zoom in closer to the data points, while a lower value will zoom out.

## Create a map with a specified zoom level
st.map(data, zoom=10)

Adding GeoJSON Maps to Streamlit App

What is GeoJSON?

GeoJSON is a format for encoding a variety of geographic data structures. It supports a variety of geographical data types including Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, and GeometryCollection. GeoJSON uses the JSON standard to create maps, which makes it easy to use in a wide variety of applications.

How to Add GeoJSON Maps to Streamlit App

Adding GeoJSON maps to your Streamlit app involves reading the GeoJSON data into a DataFrame and then passing that DataFrame to the st.map function. Here's an example of how you can do this:

import geopandas as gpd
 
# Read GeoJSON data into a GeoDataFrame
gdf = gpd.read_file('path_to_your_geojson_file.geojson')
 
# Convert the GeoDataFrame to a DataFrame
df = pd.DataFrame(gdf)
 
# Create a map with the GeoJSON data
st.map(df)

In this example, we're using the geopandas library to read the GeoJSON data into a GeoDataFrame. We then convert this GeoDataFrame into a regular pandas DataFrame, which we can pass to the st.map function.

Enhancing Maps with st.map Features

Streamlit's st.map function comes with a variety of features that allow you to enhance your maps. These include adding custom markers, adjusting the zoom level, and auto-centering the map around your data points.

Adding Custom Markers

Adding custom markers to your map can help you highlight specific data points. To add custom markers, you need to create a separate DataFrame that contains the latitude and longitude values of the points you want to highlight.

# Create a DataFrame with the points you want to highlight
highlight = pd.DataFrame({
    'latitude': [37.7749],
    'longitude': [-122.4194]
})
 
# Add the highlight points to the map
st.map(data, highlight)

In this example, we're highlighting a single point on the map. The highlight DataFrame contains the latitude and longitude values of this point. We then pass this DataFrame to the st.map function along with our original data.

Zooming and Auto-Centering

The st.map function automatically centers the map around your data points and adjusts the zoom level to fit all the points. However, you can also manually adjust the zoom level and center of the map.

# Create a map with a specified zoom level and center
st.map(data, zoom=10, center=[37.7749, -122.4194])

In this example, we're setting the zoom level to 10 and centering the map around the coordinates [37.7749, -122.4194]. The center parameter takes a list of two values: the latitude and longitude of the point you want to center the map around.

Troubleshooting st.map Issues

While st.map is a powerful tool, you may encounter some issues while using it. One common issue is the "st.map not working" error. This usually occurs when the DataFrame passed to st.map does not contain the correct columns or the columns are not named correctly. Remember, st.map requires a DataFrame with either named columns "lat" and "lon" or "latitude" and "longitude".

If you encounter this issue, check your DataFrame to ensure it has the correct columns and they are named appropriately.

Creating Interactive Maps in Streamlit

Interactive maps are a powerful tool for data visualization. They allow users to zoom in and out, pan across different regions, and even click on data points to get more information. Streamlit's st.map function makes it easy to create these interactive maps.

Easy Ways to Include Interactive Maps

Including an interactive map in your Streamlit app is as simple as passing a DataFrame with latitude and longitude values to the st.map function. However, you can also enhance your maps by adding interactivity such as custom markers, pop-up information, and more.

For example, you can add a pop-up feature that displays more information about a data point when it's clicked. This can be done by adding an additional column to your DataFrame with the information you want to display.

# Add an additional column for pop-up information
data['info'] = ['San Francisco', 'Los Angeles', 'New York']
 
# Create a map with the data
st.map(data)

In this example, when a data point is clicked, it will display the name of the city.

Displaying Maps with Streamlit and Folium

While st.map is a powerful tool for creating maps, you can also use other libraries like Folium to create more complex maps. Folium is a Python library that allows you to create interactive maps using Leaflet.js, a popular open-source JavaScript library for mobile-friendly interactive maps.

To display a Folium map in Streamlit, you can use the st.pydeck_chart function. Here's an example:

import folium
 
# Create a Folium map
m = folium.Map(location=[37.7749, -122.4194], zoom_start=10)
 
# Display the map in Streamlit
st.pydeck_chart(m)

In this example, we're creating a Folium map centered around the coordinates [37.7749, -122.4194] with a zoom level of 10. We then display this map in Streamlit using the st.pydeck_chart function.

This is just the tip of the iceberg when it comes to creating interactive maps in Streamlit. With the power of Python and libraries like Streamlit and Folium, the possibilities are endless. Whether you're a data scientist looking to visualize your data or a developer building a data-driven web app, interactive maps are a powerful tool to have in your arsenal.

Enhancing Your Data Visualization with Streamlit

Streamlit's st.map function is a powerful tool for data visualization. By allowing you to create interactive maps, it provides a visual representation of your data that can be easily understood and interpreted. This section will delve into some advanced features of st.map and how you can use them to enhance your data visualization.

Advanced Features of st.map

One of the key features of st.map is its ability to handle large datasets. It can efficiently plot thousands of data points on a map without slowing down your app. This makes it an ideal tool for visualizing large datasets.

Another advanced feature of st.map is its compatibility with other Python libraries. You can use libraries like pandas for data manipulation, numpy for numerical computations, and matplotlib for additional visualization options. This interoperability makes st.map a versatile tool for data visualization.

Examples of Data Visualization with st.map

To illustrate the power of st.map, let's look at some examples of data visualization. Suppose we have a dataset of Airbnb listings in New York City. We can use st.map to plot these listings on a map and gain insights into the distribution of Airbnb listings in the city.

# Load the dataset
data = pd.read_csv('nyc_airbnb_listings.csv')
 
# Create a map with the data
st.map(data)

In this example, each data point on the map represents an Airbnb listing. By visualizing this data on a map, we can easily see which areas in New York City have the most Airbnb listings.

Easily Create Interactive Data Visualizations in Streamlit with PyGWalker

PyGWalker (opens in a new tab) is also another awesome tool that works wonders as the alternative to Streamlit AgGrid.

PyGWalker + Streamlit Online Demo (opens in a new tab)

PyGWalker (opens in a new tab) is a Python Library that helps you easily embed a tableau-alternative UI into your own Streamlit app effortlessly.

Check out this amazing video how to explore data with pygwalker (opens in a new tab) demonstrating the detailed steps for empowering your Streamlit app with this powerful Data Visualization Python Library!


Special Thanks to Sven and his great contribution (opens in a new tab) to PyGWalker community!

Additionally, you can also check out these resources:

Visualize Data in Streamlit with PyGWalker (opens in a new tab)

Conclusion

Streamlit's st.map function is a powerful tool for creating interactive maps and visualizing geospatial data. Whether you're a data scientist looking to visualize your data or a developer building a data-driven web app, st.map offers a simple and efficient way to create interactive maps. With its advanced features and compatibility with other Python libraries, st.map is a versatile tool that can enhance your data visualization and analysis.

Frequently Asked Questions

How to do a map in streamlit?

Creating a map in Streamlit is straightforward. You need to have a pandas DataFrame that contains latitude and longitude values. You can then pass this DataFrame to the st.map function to create a map.

How do I create an interactive location map?

You can create an interactive location map in Streamlit using the st.map function. This function creates a map and plots data points onto it. The map is interactive, meaning you can zoom in and out and pan across different regions. You can also add custom markers and pop-up information to enhance the interactivity of the map.

Does Streamlit have an API?

Yes, Streamlit has a simple and intuitive API that allows you to create interactive web applications. The API provides a variety of functions for creating different types of visualizations, including maps, charts, and tables. You can also use the API to add interactivity to your app, such as buttons, sliders, and text input.