Heatmaps with google-map-react

Sergey Royz
2 min readDec 15, 2018

--

Since this topic is poorly covered in the documentation I decided to build a sample app showing some use cases.

Demo can be found here: https://zjor.github.io/google-heat-map/

In this article I’ll demonstrate how to change data points dynamically and how to turn on/off heatmap layer. I’ll be using this library throughout the article: https://github.com/google-map-react/google-map-react

Enabling heatmap layer

<GoogleMapReact          
ref={(el) => this._googleMap = el}
bootstrapURLKeys={apiKey}
defaultCenter={this.props.center}
defaultZoom={this.props.zoom}
heatmapLibrary={true}
heatmap={heatMapData}
onClick={this.onMapClick.bind(this)}
>

Heatmap data format

{    
positions: [
{lat: 55.5, lng: 34.56},
{lat: 34.7, lng: 28.4},
...
],
options: {
radius: 20,
opacity: 0.6,
...
}

For more options see https://developers.google.com/maps/documentation/javascript/heatmaplayer

Changing heatmap data dynamically

In order to change data points it’s not enough to replace heatMapData object, instead it’s necessary to manipulate with internal objects of GoogleMapReact. The following piece of code shows how to add data points dynamically.

onMapClick({x, y, lat, lng, event}) {
if (this._googleMap !== undefined) {
const point = new google.maps.LatLng(lat, lng)
this._googleMap.heatmap.data.push(point)
}
}

In order to make google.maps.LatLng visible it’s necessary to add this line of code at the top of the file:

/* global google */

Toggle heatmap layer

toggleHeatMap() {
this.setState({
heatmapVisible: !this.state.heatmapVisible
}, () => {
if (this._googleMap !== undefined) {
this._googleMap.heatmap.setMap(this.state.heatmapVisible ?
this._googleMap.map_ : null)
}
})
}

--

--

Sergey Royz
Sergey Royz

Written by Sergey Royz

Co-founder and CTO of a crypto startup. A full-stack software engineer with a passion for creating innovative tech solutions that make a difference.

Responses (8)