What is react-map-gl?
react-map-gl is a React wrapper for Mapbox GL JS, which is a powerful library for interactive, customizable maps. It allows developers to integrate Mapbox maps into their React applications with ease, providing a range of features for map rendering, user interaction, and data visualization.
What are react-map-gl's main functionalities?
Basic Map Rendering
This code demonstrates how to render a basic map using react-map-gl. It sets up a map centered on a specific latitude and longitude with a given zoom level. The map style is set to 'streets-v11' from Mapbox, and the viewport state is managed to allow for user interaction.
```jsx
import React from 'react';
import ReactMapGL from 'react-map-gl';
const Map = () => {
const [viewport, setViewport] = React.useState({
latitude: 37.7577,
longitude: -122.4376,
zoom: 8
});
return (
<ReactMapGL
{...viewport}
width="100%"
height="100%"
mapStyle="mapbox://styles/mapbox/streets-v11"
onViewportChange={nextViewport => setViewport(nextViewport)}
mapboxApiAccessToken={process.env.REACT_APP_MAPBOX_TOKEN}
/>
);
};
export default Map;
```
Adding Markers
This code sample shows how to add a marker to the map. The Marker component is used to place a marker at a specific latitude and longitude. In this example, a simple red dot is used as the marker.
```jsx
import React from 'react';
import ReactMapGL, { Marker } from 'react-map-gl';
const MapWithMarkers = () => {
const [viewport, setViewport] = React.useState({
latitude: 37.7577,
longitude: -122.4376,
zoom: 8
});
return (
<ReactMapGL
{...viewport}
width="100%"
height="100%"
mapStyle="mapbox://styles/mapbox/streets-v11"
onViewportChange={nextViewport => setViewport(nextViewport)}
mapboxApiAccessToken={process.env.REACT_APP_MAPBOX_TOKEN}
>
<Marker latitude={37.7577} longitude={-122.4376}>
<div style={{ backgroundColor: 'red', width: '10px', height: '10px', borderRadius: '50%' }} />
</Marker>
</ReactMapGL>
);
};
export default MapWithMarkers;
```
Handling Map Events
This example demonstrates how to handle map events, such as clicks. The handleClick function is triggered when the map is clicked, displaying an alert with the coordinates of the click.
```jsx
import React from 'react';
import ReactMapGL from 'react-map-gl';
const MapWithEvents = () => {
const [viewport, setViewport] = React.useState({
latitude: 37.7577,
longitude: -122.4376,
zoom: 8
});
const handleClick = (event) => {
alert(`Clicked at ${event.lngLat}`);
};
return (
<ReactMapGL
{...viewport}
width="100%"
height="100%"
mapStyle="mapbox://styles/mapbox/streets-v11"
onViewportChange={nextViewport => setViewport(nextViewport)}
mapboxApiAccessToken={process.env.REACT_APP_MAPBOX_TOKEN}
onClick={handleClick}
/>
);
};
export default MapWithEvents;
```
Other packages similar to react-map-gl
leaflet
Leaflet is a popular open-source JavaScript library for interactive maps. It is lightweight and easy to use, with a wide range of plugins available for additional functionality. Compared to react-map-gl, Leaflet is more lightweight but may not offer the same level of performance and customization as Mapbox GL JS.
google-maps-react
google-maps-react is a library for integrating Google Maps into React applications. It provides a set of React components for Google Maps, allowing for easy map rendering and interaction. While it offers robust features and the reliability of Google Maps, it may not provide the same level of customization and styling options as react-map-gl.
react-leaflet
react-leaflet is a React wrapper for Leaflet, providing a set of React components for Leaflet maps. It combines the simplicity of Leaflet with the power of React, making it easy to create interactive maps in React applications. Compared to react-map-gl, react-leaflet is more lightweight but may not offer the same advanced features and performance.
react-map-gl
react-map-gl provides a React friendly
API wrapper around Mapbox GL JS. A webGL
based vector tile mapping library.
WARNING: This project is new and the API may change. There also may be Mapbox
APIs that haven't yet been exposed.

See the interactive docs at: https://uber.github.io/react-map-gl
Overview
Installation
npm install react-map-gl --save
Usage
import MapGL from 'react-map-gl';
<MapGL width={400} height={400} latitude={37.7577} longitude={-122.4376}
zoom={8} onChangeViewport={(viewport) => {
const {latitude, longitude, zoom} = viewport;
// Optionally call `setState` and use the state to update the map.
}}
/>
Using overlays
react-map-gl provides an overlay API so you can use the built-in visualization
overlays, or create your own. Here's an example of using the build in
ScatterplotOverlay.
import ScatterplotOverlay from 'react-map-gl/src/overlays/scatterplot.react';
<MapGL {...viewport}>
<ScatterplotOverlay
{...viewport}
locations={locations}
dotRadius={4}
globalOpacity={1}
compositeOperation="screen" />
// Add additional overlays here...
])
Built-in Overlays
- ChoroplethOverlay
- ScatterplotOverlay
- DraggablePointsOverlay
- SVGOverlay
- CanvasOverlay
Note: These overlays are currently not compatible with perspective mode.
deck.gl overlays
deck.gl is a companion module to
react-map-gl
that provide a number of classic data visualization overlays
(scatterplots, choropleths etc) implemented in WebGL. These overlays are
suitable for large or dynamic data sets, or for use in perspective mode
applications
Third party overlays
Third party overlays can also be created. For example, the
heatmap-overlay uses
webgl-heatmap to create geographic
heatmaps.

Example usage:
import HeatmapOverlay from 'react-map-gl-heatmap-overlay';
import cities from 'example-cities';
render() {
return <MapGL {...viewport}>
return <HeatmapOverlay locations={cities} {...viewport}/>
</MapGL>;
}
Want to create and share your own overlay? Fork the
react-map-gl-example-overlay
project to get started.
Perspective Mode
Perspective mode is exposed using the pitch
and bearing
props
(both default to 0
), which will show the map "tilted" pitch
degrees
(overhead being 0 degrees), looking towards bearing
(0 degrees is north).
In addition, the perspectiveEnabled
prop (default: false
)
will activate mouse handlers that allow the user to change pitch
and
bearing
using the mouse while holding down the "command" key.
If perspectiveEnabled
is not set to true
then the user will not be able to
change the pitch and bearing, which means that the default props will show
an overhead map and only enable standard pan and zoom mouse actions on that map.
Note: Mapbox-gl-js limits the pitch to 60 degrees.
Note: When using pitch, several additional fields are passed in the
onViewportChange callback, make sure to pass all received props back to
the component.
Note: not all overlays are compatible with perspective mode.
For a set of overlays that do work with perspective mode, look at
deck.gl.
Transitions
react-map-gl
does not expose the transition API for mapbox-gl-js
since it is designed to be a stateless component.
Instead it is recommended to use a separate module like
react-motion
to animate properties. An example:
<Motion style={{
latitude: spring(viewport.latitude, { stiffness: 170, damping: 26, precision: 0.000001 }),
longitude: spring(viewport.longitude, { stiffness: 170, damping: 26, precision: 0.000001 })
}}>
{({ latitude, longitude }) => <MapGL
{...viewport}
latitude={latitude}
longitude={longitude}
mapStyle={mapboxStyle}
/>}
</Motion>
ImmutableJS all the things
The mapStyle
property of the MapGL
as well as several of the built in
overlay properties must be provided as
ImmutableJS objects. This allows
the library to be fast since computing changes to props only involves checking
if the immutable objects are the same instance.
Development
To develop on this component, install the dependencies and then build and watch
the static files.
$ npm install
To serve example app:
$ npm start &
$ open "http://localhost:9966/?access_token="`echo $MapboxAccessToken`
Where echo $MapboxAccessToken
returns your Mapbox access token.
Once complete, you can view the component in your browser at
localhost:9966. Any changes you make will automatically
run the compiler to build the files again.
Testing
It's particularly difficult to write tests for this component beacuse it uses WebGL. There are some tests in test/
but for the most part, as new features are added, we typically test drive them by running npm run start
and play with the demos.
CHANGE LOG
See change log