├── .babelrc ├── .eslintignore ├── .eslintrc ├── .flowconfig ├── .gitignore ├── .npmignore ├── .nvmrc ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── example ├── index.html ├── index.js ├── realworld.10000.js └── webpack.config.js ├── lib └── HeatmapLayer.js ├── package.json ├── screenshot.jpg └── src └── HeatmapLayer.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": [ 3 | "babel-plugin-transform-do-expressions", 4 | "babel-plugin-transform-function-bind", 5 | "babel-plugin-transform-class-constructor-call", 6 | ["babel-plugin-transform-class-properties", { "loose": true }], 7 | "babel-plugin-transform-decorators", 8 | "babel-plugin-transform-export-extensions", 9 | "babel-plugin-syntax-trailing-function-commas", 10 | "babel-plugin-transform-object-rest-spread", 11 | "babel-plugin-transform-async-to-generator", 12 | "babel-plugin-transform-exponentiation-operator", 13 | 14 | "babel-plugin-transform-react-jsx", 15 | "babel-plugin-transform-flow-strip-types", 16 | "babel-plugin-syntax-flow", 17 | "babel-plugin-syntax-jsx", 18 | "babel-plugin-transform-react-display-name", 19 | 20 | ["babel-plugin-transform-es2015-template-literals", { "loose": true }], 21 | "babel-plugin-transform-es2015-literals", 22 | "babel-plugin-transform-es2015-function-name", 23 | "babel-plugin-transform-es2015-arrow-functions", 24 | "babel-plugin-transform-es2015-block-scoped-functions", 25 | ["babel-plugin-transform-es2015-classes", { "loose": true }], 26 | "babel-plugin-transform-es2015-object-super", 27 | "babel-plugin-transform-es2015-shorthand-properties", 28 | ["babel-plugin-transform-es2015-computed-properties", { "loose": true }], 29 | ["babel-plugin-transform-es2015-for-of", { "loose": true }], 30 | "babel-plugin-transform-es2015-sticky-regex", 31 | "babel-plugin-transform-es2015-unicode-regex", 32 | ["babel-plugin-transform-es2015-spread", { "loose": true }], 33 | "babel-plugin-transform-es2015-parameters", 34 | ["babel-plugin-transform-es2015-destructuring", { "loose": true }], 35 | "babel-plugin-transform-es2015-block-scoping", 36 | "babel-plugin-transform-es2015-typeof-symbol", 37 | ["babel-plugin-transform-es2015-modules-commonjs", { "loose": true }], 38 | "babel-plugin-transform-regenerator" 39 | ] 40 | } 41 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/** 2 | lib/** 3 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "eslint-config-airbnb", 3 | "parser": "babel-eslint", 4 | "env": { 5 | "browser": true, 6 | "mocha": true, 7 | "node": true 8 | }, 9 | "globals": { 10 | "__data": true, 11 | "expect": true, 12 | "ga": true, 13 | "Intercom": true, 14 | "spy": true, 15 | "sinon": true, 16 | "Raven": true, 17 | "Highcharts": true 18 | }, 19 | "rules": { 20 | "comma-dangle": 0, 21 | "no-wrap-func": 0, 22 | "spaced-comment": 0, 23 | "eqeqeq": [2, "smart"], 24 | 25 | // Portal uses some camelcase 26 | "camelcase": 1, 27 | 28 | // used for creating new Immutable Lists and Maps 29 | "new-cap": [1, {"capIsNewExceptions": ["Immutable"]}], 30 | 31 | // Sometimes short variable names are okay 32 | "id-length": 0, 33 | 34 | // Doesn't play nice with chai's assertions 35 | "no-unused-expressions": 0, 36 | 37 | "react/jsx-uses-react": 2, 38 | "react/jsx-uses-vars": 2, 39 | "react/react-in-jsx-scope": 2, 40 | "react/jsx-no-duplicate-props": 2, 41 | 42 | 43 | // Discourages microcomponentization 44 | "react/no-multi-comp": 0, 45 | 46 | //Temporarirly disabled due to a possible bug in babel-eslint (todomvc example) 47 | "block-scoped-var": 0, 48 | // Temporarily disabled for test/* until babel/babel-eslint#33 is resolved 49 | "padded-blocks": 0, 50 | "no-param-reassign": 0 51 | }, 52 | "plugins": [ 53 | "react", 54 | "lean-imports" 55 | ] 56 | } 57 | -------------------------------------------------------------------------------- /.flowconfig: -------------------------------------------------------------------------------- 1 | [ignore] 2 | .*/node_modules/babel-cli/.* 3 | .*/node_modules/babel-generator/.* 4 | .*/node_modules/babel-helper-builder-binary-assignment-operator-visitor/.* 5 | .*/node_modules/babel-helper-explode-assignable-expression/.* 6 | .*/node_modules/babel-helper-remap-async-to-generator/.* 7 | .*/node_modules/babel-helper-regex/.* 8 | .*/node_modules/babel-plugin-transform-regenerator/.* 9 | .*/node_modules/babel-template/.* 10 | .*/node_modules/babel-types/.* 11 | .*/node_modules/jsxhint/.* 12 | .*/node_modules/fbjs/.* 13 | .*/node_modules/flow-bin/.* 14 | .*/node_modules/flux/.* 15 | .*/node_modules/node-sass/.* 16 | .*/node_modules/phantomjs/.* 17 | .*/node_modules/react-styleguidist/.* 18 | .*/node_modules/config-chain/.* 19 | .*/node_modules/findup/.* 20 | 21 | 22 | [include] 23 | 24 | [libs] 25 | 26 | [options] 27 | esproposal.class_instance_fields=enable 28 | suppress_comment= \\(.\\|\n\\)*\\$FlowFixMe 29 | esproposal.class_static_fields=enable 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Runtime data 6 | pids 7 | *.pid 8 | *.seed 9 | 10 | # Directory for instrumented libs generated by jscoverage/JSCover 11 | lib-cov 12 | 13 | # Coverage directory used by tools like istanbul 14 | coverage 15 | 16 | # Compiled binary addons (http://nodejs.org/api/addons.html) 17 | build/Release 18 | build 19 | 20 | # Dependency directory 21 | # Commenting this out is preferred by some people, see 22 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- 23 | node_modules 24 | bower_components 25 | 26 | # Users Environment Variables 27 | .lock-wscript 28 | .sass-cache 29 | 30 | .idea/ 31 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .babelrc 2 | .gitignore 3 | .npmignore 4 | .nvmrc 5 | screenshot.jpg 6 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | 4.3.0 2 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 2.0.0 Release 2 | - React-leaflet v2.x support. For react-leaflet v1.x please use react-leaflet-heatmep-layer v1.x. 3 | 4 | # 1.0.4 Release 5 | - Allow the latest versions of `react` and `react-dom` (i.e. 16 and up). 6 | 7 | # 1.0.3 Release 8 | - Fixed warning "Accessing PropTypes via the main React package is deprecated" 9 | 10 | # 1.0.2 Release 11 | - Fix bug where radius, blur, and max were not being used when passed in as props. 12 | 13 | # 1.0.1 Release 14 | - Fix bug in componentWillUnmount->safeRemoveLayer where getPanes doesn't return anything so .contains is called on undefined. 15 | 16 | # 1.0.0 Release 17 | - Leaflet 1.0.0 support 18 | - React-Leaflet 1.0.0 support 19 | - List eslint as an explicit devDependency 20 | - upgrade the eslint related packages 21 | - fix linting errors using current config 22 | - Add notes about maintaining absence of lint errors and warnings in Contributing guide 23 | - This should make it easier to ensure code quality as others contribute in the open 24 | - Also, drop unused jest and enzyme deps 25 | 26 | # 0.2.3 Release 27 | - Missed Transpilation 28 | 29 | # 0.2.2 Release 30 | - Change `getHeatmapProps` signature to take a `props` argument to support passing `nextProps` from `componentWillReceiveProps` and `this.props` from `componentDidMount` 31 | 32 | # 0.2.1 Release 33 | 34 | - Fix getMaxZoom returning props.radius instead of props.maxZoom, fix misnamed call to getMax instead of getMaxZoom in redraw() 35 | 36 | # 0.2.0 Release 37 | 38 | - adds an `onStatsUpdate` prop which is called on redraw with a { min, max } object containing the min and max number of items found for a single coordinate 39 | 40 | # 0.1.0 Release 41 | 42 | - Handle invalid points gracefully 43 | - Add `fitBoundsOnUpdate` prop to indicate that the map should fit the data in the map on update 44 | 45 | # 0.0.2 Release 46 | 47 | - Fix an issue with the gradient property being applied 48 | 49 | # 0.0.1 Release 50 | 51 | - Initial implementation of package 52 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Things you can do to contribute include: 4 | 5 | 1. Report a bug by [opening an issue](https://github.com/OpenGov/react-leaflet-heatmap-layer/issues/new) 6 | 2. Suggest a change by [opening an issue](https://www.github.com/OpenGov/react-leaflet-heatmap-layer/issues/new) 7 | 3. Fork the repository and fix [an open issue](https://github.com/OpenGov/react-leaflet-heatmap-layer/issues) 8 | 9 | ### Technology 10 | 11 | `react-leaflet-heatmap-layer` is a custom layer for the `react-leaflet` package. This package is a convenient wrapper around Leaflet, a mapping library, for React. The source code is written with ES6/ES2015 syntax as well as [FlowType](http://flowtype.org) type annotations. 12 | 13 | ### Install dependencies 14 | 15 | 1. Install Node via [nodejs.org](http://nodejs.org) 16 | 2. After cloning the repository, run `npm install` in the root of the project 17 | 18 | This project is developed with Node version 4.3.0 and NPM 3.3.10. 19 | 20 | ### Contributing via Github 21 | 22 | The entire project can be found [on Github](https://github.com/OpenGov/react-leaflet-heatmap-layer). We use the [fork and pull model](https://help.github.com/articles/using-pull-requests/) to process contributions. 23 | 24 | #### Fork the Repository 25 | 26 | Before contributing, you'll need to fork the repository: 27 | 28 | 1. Fork the repository so you have your own copy (`your-username/react-leaflet-heatmap-layer`) 29 | 2. Clone the repo locally with `git clone https://github.com/your-username/react-leaflet-heatmap-layer` 30 | 3. Move into the cloned repo: `cd react-leaflet-heatmap-layer` 31 | 4. Install the project's dependencies: `npm install` 32 | 33 | You should also add `OpenGov/react-leaflet-heatmap-layer` as a remote at this point. We generally call this remote branch 'upstream': 34 | 35 | ``` 36 | git remote add upstream https://github.com/OpenGov/react-leaflet-heatmap-layer 37 | ``` 38 | 39 | #### Development 40 | 41 | You can work with a live, hot-reloading example of the component by running: 42 | 43 | ```bash 44 | npm run example 45 | ``` 46 | 47 | And then visiting [localhost:8000](http://localhost:8000). 48 | 49 | As you make changes, please describe them in `CHANGELOG.md`. 50 | 51 | #### Submitting a Pull Request 52 | 53 | Before submitting a Pull Request please ensure you have completed the following tasks: 54 | 55 | 1. Describe your changes in `CHANGELOG.md` 56 | 2. Make sure your copy is up to date: `git pull upstream master` 57 | 3. Run `npm run compile`, to compile your changes to the exported `/lib` code. 58 | 4. Bump the version in `package.json` as appropriate, see `Versioning` in the section below. 59 | 4. Run `npm run lint` to verify code style, all pull requests should have zero lint errors and warnings 60 | 4. Commit your changes 61 | 5. Push your changes to your fork: `your-username/react-leaflet-heatmap-layer` 62 | 6. Open a pull request from your fork to the `upstream` fork (`OpenGov/react-leaflet-heatmap-layer`) 63 | 64 | ## Versioning 65 | 66 | This project follows Semantic Versioning.This means that version numbers are basically formatted like `MAJOR.MINOR.PATCH`. 67 | 68 | #### Major 69 | 70 | Breaking changes are signified with a new **first** number. For example, moving from 1.0.0 to 2.0.0 implies breaking changes. 71 | 72 | #### Minor 73 | 74 | New components, new helper classes, or substantial visual changes to existing components and patterns are *minor releases*. These are signified by the second number changing. So from 1.1.2 to 1.2.0 there are minor changes. 75 | 76 | #### Patches 77 | 78 | The final number signifies patches such as fixing a pattern or component in a certain browser, or fixing an existing bug. Small changes to the documentation site and the tooling around the Calcite-Web library are also considered patches. 79 | 80 | ## Developer's Certificate of Origin 1.1 81 | 82 | By making a contribution to this project, I certify that: 83 | 84 | * (a) The contribution was created in whole or in part by me and I 85 | have the right to submit it under the open source license 86 | indicated in the file; or 87 | 88 | * (b) The contribution is based upon previous work that, to the best 89 | of my knowledge, is covered under an appropriate open source 90 | license and I have the right under that license to submit that 91 | work with modifications, whether created in whole or in part 92 | by me, under the same open source license (unless I am 93 | permitted to submit under a different license), as indicated 94 | in the file; or 95 | 96 | * (c) The contribution was provided directly to me by some other 97 | person who certified (a), (b) or (c) and I have not modified 98 | it. 99 | 100 | * (d) I understand and agree that this project and the contribution 101 | are public and that a record of the contribution (including all 102 | personal information I submit with it, including my sign-off) is 103 | maintained indefinitely and may be redistributed consistent with 104 | this project or the open source license(s) involved. 105 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | Copyright (c) 2016 OpenGov, Inc. 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 5 | 6 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 7 | 8 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # react-leaflet-heatmap-layer 2 | 3 | `react-leaflet-heatmap-layer` provides a simple `` component for creating a heatmap layer in a `react-leaflet` map. 4 | 5 | ![A screenshot of a heatmap on a leaflet map](../master/screenshot.jpg?raw=true) 6 | 7 | ## Usage 8 | 9 | Use directly as a fixed layer: 10 | 11 | ```js 12 | import React from 'react'; 13 | import { render } from 'react-dom'; 14 | import { Map, Marker, Popup, TileLayer } from 'react-leaflet'; 15 | import HeatmapLayer from '../src/HeatmapLayer'; 16 | import { addressPoints } from './realworld.10000.js'; 17 | 18 | class MapExample extends React.Component { 19 | 20 | render() { 21 | return ( 22 |
23 | 24 | m[1]} 29 | latitudeExtractor={m => m[0]} 30 | intensityExtractor={m => parseFloat(m[2])} /> 31 | 35 | 36 |
37 | ); 38 | } 39 | 40 | } 41 | 42 | render(, document.getElementById('app')); 43 | ``` 44 | 45 | Or use it inside a layer control to toggle it: 46 | 47 | ```js 48 | import React from 'react'; 49 | import { render } from 'react-dom'; 50 | import { Map, Marker, Popup, TileLayer } from 'react-leaflet'; 51 | import HeatmapLayer from '../src/HeatmapLayer'; 52 | import { addressPoints } from './realworld.10000.js'; 53 | 54 | class MapExample extends React.Component { 55 | 56 | render() { 57 | return ( 58 |
59 | 60 | 61 | 62 | 66 | 67 | 68 | 69 | 70 | 71 | A pretty CSS3 popup.
Easily customizable.
72 |
73 |
74 | m[1]} 79 | latitudeExtractor={m => m[0]} 80 | intensityExtractor={m => parseFloat(m[2])} 81 | /> 82 |
83 |
84 | 85 | 86 | 87 | 88 | A pretty CSS3 popup.
Easily customizable.
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 | ); 97 | } 98 | } 99 | 100 | render(, document.getElementById('app')); 101 | ``` 102 | 103 | 104 | ## API 105 | 106 | The `HeatmapLayer` component takes the following props: 107 | 108 | - `points`: *required* an array of objects to be processed 109 | - `longitudeExtractor`: *required* a function that returns the object's longitude e.g. `marker => marker.lng` 110 | - `latitudeExtractor`: *required* a function that returns the object's latitude e.g. `marker => marker.lat` 111 | - `intensityExtractor`: *required* a function that returns the object's intensity e.g. `marker => marker.val` 112 | - `fitBoundsOnLoad`: boolean indicating whether map should fit data in bounds of map on load 113 | - `fitBoundsOnUpdate`: boolean indicating whether map should fit data in bounds of map on Update 114 | - `max`: max intensity value for heatmap (default: 3.0) 115 | - `radius`: radius for heatmap points (default: 30) 116 | - `maxZoom`: maximum zoom for heatmap (default: 18) 117 | - `minOpacity`: minimum opacity for heatmap (default: 0.01) 118 | - `blur`: blur for heatmap points (default: 15) 119 | - `gradient`: object defining gradient stop points for heatmap e.g. `{ 0.4: 'blue', 0.8: 'orange', 1.0: 'red' }` (default: `simpleheat` package default gradient) 120 | - `onStatsUpdate`: called on redraw with a { min, max } object containing the min and max number of items found for a single coordinate 121 | 122 | ## Example 123 | 124 | To try the example: 125 | 126 | 1. Clone this repository 127 | 2. run `npm install` in the root of your cloned repository 128 | 3. run `npm run example` 129 | 4. Visit [localhost:8000](http://localhost:8000) 130 | 131 | ## Contributing 132 | 133 | See [CONTRIBUTING.md](https://www.github.com/OpenGov/react-leaflet-heatmap-layer/blob/master/CONTRIBUTING.md) 134 | 135 | ## Credits 136 | 137 | This package was inspired by [Leaflet.heat](https://github.com/Leaflet/Leaflet.heat). 138 | 139 | ## License 140 | 141 | `react-leaflet-heatmap-layer` is MIT licensed. 142 | 143 | See [LICENSE.md](https://www.github.com/OpenGov/react-leaflet-heatmap-layer/blob/master/LICENSE.md) for details. 144 | -------------------------------------------------------------------------------- /example/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | react-leaflet-heatmap-layer example 6 | 7 | 8 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /example/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render } from 'react-dom'; 3 | import { Map, TileLayer } from 'react-leaflet'; 4 | import HeatmapLayer from '../src/HeatmapLayer'; 5 | import { addressPoints } from './realworld.10000.js'; 6 | 7 | class MapExample extends React.Component { 8 | 9 | state = { 10 | mapHidden: false, 11 | layerHidden: false, 12 | addressPoints, 13 | radius: 4, 14 | blur: 8, 15 | max: 0.5, 16 | limitAddressPoints: true, 17 | }; 18 | 19 | /** 20 | * Toggle limiting the address points to test behavior with refocusing/zooming when data points change 21 | */ 22 | toggleLimitedAddressPoints() { 23 | if (this.state.limitAddressPoints) { 24 | this.setState({ addressPoints: addressPoints.slice(500, 1000), limitAddressPoints: false }); 25 | } else { 26 | this.setState({ addressPoints, limitAddressPoints: true }); 27 | } 28 | } 29 | 30 | render() { 31 | if (this.state.mapHidden) { 32 | return ( 33 |
34 | this.setState({ mapHidden: !this.state.mapHidden })} 38 | /> 39 |
40 | ); 41 | } 42 | 43 | const gradient = { 44 | 0.1: '#89BDE0', 0.2: '#96E3E6', 0.4: '#82CEB6', 45 | 0.6: '#FAF3A5', 0.8: '#F5D98B', '1.0': '#DE9A96' 46 | }; 47 | 48 | return ( 49 |
50 | 51 | {!this.state.layerHidden && 52 | m[1]} 57 | latitudeExtractor={m => m[0]} 58 | gradient={gradient} 59 | intensityExtractor={m => parseFloat(m[2])} 60 | radius={Number(this.state.radius)} 61 | blur={Number(this.state.blur)} 62 | max={Number.parseFloat(this.state.max)} 63 | /> 64 | } 65 | 69 | 70 | this.setState({ mapHidden: !this.state.mapHidden })} 74 | /> 75 | this.setState({ layerHidden: !this.state.layerHidden })} 79 | /> 80 | 85 | 86 |
87 | Radius 88 | this.setState({ radius: e.currentTarget.value })} 94 | /> {this.state.radius} 95 |
96 | 97 |
98 | Blur 99 | this.setState({ blur: e.currentTarget.value })} 105 | /> {this.state.blur} 106 |
107 | 108 |
109 | Max 110 | this.setState({ max: e.currentTarget.value })} 117 | /> {this.state.max} 118 |
119 |
120 | ); 121 | } 122 | 123 | } 124 | 125 | render(, document.getElementById('app')); 126 | -------------------------------------------------------------------------------- /example/webpack.config.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | var webpack = require('webpack'); 3 | 4 | module.exports = { 5 | debug: true, 6 | devtool: 'source-map', 7 | entry: { 8 | app: __dirname + '/index.js' 9 | }, 10 | module: { 11 | loaders: [ 12 | { 13 | test: /\.js$/, 14 | exclude: /node_modules/, 15 | loader: 'babel', 16 | query: { 17 | plugins: [ 18 | ['react-transform', { 19 | transforms: [{ 20 | transform: 'react-transform-hmr', 21 | imports: ['react'], 22 | locals: ['module'] 23 | }] 24 | }] 25 | ] 26 | } 27 | }, 28 | ] 29 | }, 30 | output: { 31 | path: __dirname + '/build/', 32 | filename: '[name].js', 33 | publicPath: 'http://localhost:8000/build' 34 | }, 35 | plugins: [ 36 | new webpack.DefinePlugin({ 37 | 'process.env': { 38 | 'NODE_ENV': '"development"' 39 | } 40 | }), 41 | new webpack.NoErrorsPlugin(), 42 | new webpack.HotModuleReplacementPlugin() 43 | ], 44 | devServer: { 45 | colors: true, 46 | contentBase: __dirname, 47 | historyApiFallback: true, 48 | hot: true, 49 | inline: true, 50 | port: 8000, 51 | progress: true, 52 | stats: { 53 | cached: false 54 | } 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /lib/HeatmapLayer.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | exports.__esModule = true; 4 | 5 | var _class, _temp; 6 | 7 | var _react = require('react'); 8 | 9 | var _react2 = _interopRequireDefault(_react); 10 | 11 | var _lodash = require('lodash.map'); 12 | 13 | var _lodash2 = _interopRequireDefault(_lodash); 14 | 15 | var _lodash3 = require('lodash.reduce'); 16 | 17 | var _lodash4 = _interopRequireDefault(_lodash3); 18 | 19 | var _lodash5 = require('lodash.filter'); 20 | 21 | var _lodash6 = _interopRequireDefault(_lodash5); 22 | 23 | var _lodash7 = require('lodash.min'); 24 | 25 | var _lodash8 = _interopRequireDefault(_lodash7); 26 | 27 | var _lodash9 = require('lodash.max'); 28 | 29 | var _lodash10 = _interopRequireDefault(_lodash9); 30 | 31 | var _lodash11 = require('lodash.isnumber'); 32 | 33 | var _lodash12 = _interopRequireDefault(_lodash11); 34 | 35 | var _leaflet = require('leaflet'); 36 | 37 | var _leaflet2 = _interopRequireDefault(_leaflet); 38 | 39 | var _reactLeaflet = require('react-leaflet'); 40 | 41 | var _simpleheat = require('simpleheat'); 42 | 43 | var _simpleheat2 = _interopRequireDefault(_simpleheat); 44 | 45 | var _propTypes = require('prop-types'); 46 | 47 | var _propTypes2 = _interopRequireDefault(_propTypes); 48 | 49 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 50 | 51 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } 52 | 53 | function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } 54 | 55 | function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } 56 | 57 | function isInvalid(num) { 58 | return !(0, _lodash12.default)(num) && !num; 59 | } 60 | 61 | function isValid(num) { 62 | return !isInvalid(num); 63 | } 64 | 65 | function isValidLatLngArray(arr) { 66 | return (0, _lodash6.default)(arr, isValid).length === arr.length; 67 | } 68 | 69 | function isInvalidLatLngArray(arr) { 70 | return !isValidLatLngArray(arr); 71 | } 72 | 73 | function safeRemoveLayer(leafletMap, el) { 74 | var _leafletMap$getPanes = leafletMap.getPanes(), 75 | overlayPane = _leafletMap$getPanes.overlayPane; 76 | 77 | if (overlayPane && overlayPane.contains(el)) { 78 | overlayPane.removeChild(el); 79 | } 80 | } 81 | 82 | function shouldIgnoreLocation(loc) { 83 | return isInvalid(loc.lng) || isInvalid(loc.lat); 84 | } 85 | 86 | exports.default = (0, _reactLeaflet.withLeaflet)((_temp = _class = function (_MapLayer) { 87 | _inherits(HeatmapLayer, _MapLayer); 88 | 89 | function HeatmapLayer() { 90 | _classCallCheck(this, HeatmapLayer); 91 | 92 | return _possibleConstructorReturn(this, _MapLayer.apply(this, arguments)); 93 | } 94 | 95 | HeatmapLayer.prototype.createLeafletElement = function createLeafletElement() { 96 | return null; 97 | }; 98 | 99 | HeatmapLayer.prototype.componentDidMount = function componentDidMount() { 100 | var _this2 = this; 101 | 102 | var canAnimate = this.props.leaflet.map.options.zoomAnimation && _leaflet2.default.Browser.any3d; 103 | var zoomClass = 'leaflet-zoom-' + (canAnimate ? 'animated' : 'hide'); 104 | var mapSize = this.props.leaflet.map.getSize(); 105 | var transformProp = _leaflet2.default.DomUtil.testProp(['transformOrigin', 'WebkitTransformOrigin', 'msTransformOrigin']); 106 | 107 | this._el = _leaflet2.default.DomUtil.create('canvas', zoomClass); 108 | this._el.style[transformProp] = '50% 50%'; 109 | this._el.width = mapSize.x; 110 | this._el.height = mapSize.y; 111 | 112 | var el = this._el; 113 | 114 | var Heatmap = _leaflet2.default.Layer.extend({ 115 | onAdd: function onAdd(leafletMap) { 116 | return leafletMap.getPanes().overlayPane.appendChild(el); 117 | }, 118 | addTo: function addTo(leafletMap) { 119 | leafletMap.addLayer(_this2); 120 | return _this2; 121 | }, 122 | onRemove: function onRemove(leafletMap) { 123 | return safeRemoveLayer(leafletMap, el); 124 | } 125 | }); 126 | 127 | this.leafletElement = new Heatmap(); 128 | _MapLayer.prototype.componentDidMount.call(this); 129 | this._heatmap = (0, _simpleheat2.default)(this._el); 130 | this.reset(); 131 | 132 | if (this.props.fitBoundsOnLoad) { 133 | this.fitBounds(); 134 | } 135 | this.attachEvents(); 136 | this.updateHeatmapProps(this.getHeatmapProps(this.props)); 137 | }; 138 | 139 | HeatmapLayer.prototype.getMax = function getMax(props) { 140 | return props.max || 3.0; 141 | }; 142 | 143 | HeatmapLayer.prototype.getRadius = function getRadius(props) { 144 | return props.radius || 30; 145 | }; 146 | 147 | HeatmapLayer.prototype.getMaxZoom = function getMaxZoom(props) { 148 | return props.maxZoom || 18; 149 | }; 150 | 151 | HeatmapLayer.prototype.getMinOpacity = function getMinOpacity(props) { 152 | return props.minOpacity || 0.01; 153 | }; 154 | 155 | HeatmapLayer.prototype.getBlur = function getBlur(props) { 156 | return props.blur || 15; 157 | }; 158 | 159 | HeatmapLayer.prototype.getHeatmapProps = function getHeatmapProps(props) { 160 | return { 161 | minOpacity: this.getMinOpacity(props), 162 | maxZoom: this.getMaxZoom(props), 163 | radius: this.getRadius(props), 164 | blur: this.getBlur(props), 165 | max: this.getMax(props), 166 | gradient: props.gradient 167 | }; 168 | }; 169 | 170 | HeatmapLayer.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { 171 | var currentProps = this.props; 172 | var nextHeatmapProps = this.getHeatmapProps(nextProps); 173 | 174 | this.updateHeatmapGradient(nextHeatmapProps.gradient); 175 | 176 | var hasRadiusUpdated = nextHeatmapProps.radius !== currentProps.radius; 177 | var hasBlurUpdated = nextHeatmapProps.blur !== currentProps.blur; 178 | 179 | if (hasRadiusUpdated || hasBlurUpdated) { 180 | this.updateHeatmapRadius(nextHeatmapProps.radius, nextHeatmapProps.blur); 181 | } 182 | 183 | if (nextHeatmapProps.max !== currentProps.max) { 184 | this.updateHeatmapMax(nextHeatmapProps.max); 185 | } 186 | }; 187 | 188 | /** 189 | * Update various heatmap properties like radius, gradient, and max 190 | */ 191 | 192 | 193 | HeatmapLayer.prototype.updateHeatmapProps = function updateHeatmapProps(props) { 194 | this.updateHeatmapRadius(props.radius, props.blur); 195 | this.updateHeatmapGradient(props.gradient); 196 | this.updateHeatmapMax(props.max); 197 | }; 198 | 199 | /** 200 | * Update the heatmap's radius and blur (blur is optional) 201 | */ 202 | 203 | 204 | HeatmapLayer.prototype.updateHeatmapRadius = function updateHeatmapRadius(radius, blur) { 205 | if (radius) { 206 | this._heatmap.radius(radius, blur); 207 | } 208 | }; 209 | 210 | /** 211 | * Update the heatmap's gradient 212 | */ 213 | 214 | 215 | HeatmapLayer.prototype.updateHeatmapGradient = function updateHeatmapGradient(gradient) { 216 | if (gradient) { 217 | this._heatmap.gradient(gradient); 218 | } 219 | }; 220 | 221 | /** 222 | * Update the heatmap's maximum 223 | */ 224 | 225 | 226 | HeatmapLayer.prototype.updateHeatmapMax = function updateHeatmapMax(maximum) { 227 | if (maximum) { 228 | this._heatmap.max(maximum); 229 | } 230 | }; 231 | 232 | HeatmapLayer.prototype.componentWillUnmount = function componentWillUnmount() { 233 | safeRemoveLayer(this.props.leaflet.map, this._el); 234 | }; 235 | 236 | HeatmapLayer.prototype.fitBounds = function fitBounds() { 237 | var points = this.props.points; 238 | var lngs = (0, _lodash2.default)(points, this.props.longitudeExtractor); 239 | var lats = (0, _lodash2.default)(points, this.props.latitudeExtractor); 240 | var ne = { lng: (0, _lodash10.default)(lngs), lat: (0, _lodash10.default)(lats) }; 241 | var sw = { lng: (0, _lodash8.default)(lngs), lat: (0, _lodash8.default)(lats) }; 242 | 243 | if (shouldIgnoreLocation(ne) || shouldIgnoreLocation(sw)) { 244 | return; 245 | } 246 | 247 | this.props.leaflet.map.fitBounds(_leaflet2.default.latLngBounds(_leaflet2.default.latLng(sw), _leaflet2.default.latLng(ne))); 248 | }; 249 | 250 | HeatmapLayer.prototype.componentDidUpdate = function componentDidUpdate() { 251 | this.props.leaflet.map.invalidateSize(); 252 | if (this.props.fitBoundsOnUpdate) { 253 | this.fitBounds(); 254 | } 255 | this.reset(); 256 | }; 257 | 258 | HeatmapLayer.prototype.shouldComponentUpdate = function shouldComponentUpdate() { 259 | return true; 260 | }; 261 | 262 | HeatmapLayer.prototype.attachEvents = function attachEvents() { 263 | var _this3 = this; 264 | 265 | var leafletMap = this.props.leaflet.map; 266 | leafletMap.on('viewreset', function () { 267 | return _this3.reset(); 268 | }); 269 | leafletMap.on('moveend', function () { 270 | return _this3.reset(); 271 | }); 272 | if (leafletMap.options.zoomAnimation && _leaflet2.default.Browser.any3d) { 273 | leafletMap.on('zoomanim', this._animateZoom, this); 274 | } 275 | }; 276 | 277 | HeatmapLayer.prototype._animateZoom = function _animateZoom(e) { 278 | var scale = this.props.leaflet.map.getZoomScale(e.zoom); 279 | var offset = this.props.leaflet.map._getCenterOffset(e.center)._multiplyBy(-scale).subtract(this.props.leaflet.map._getMapPanePos()); 280 | 281 | if (_leaflet2.default.DomUtil.setTransform) { 282 | _leaflet2.default.DomUtil.setTransform(this._el, offset, scale); 283 | } else { 284 | this._el.style[_leaflet2.default.DomUtil.TRANSFORM] = _leaflet2.default.DomUtil.getTranslateString(offset) + ' scale(' + scale + ')'; 285 | } 286 | }; 287 | 288 | HeatmapLayer.prototype.reset = function reset() { 289 | var topLeft = this.props.leaflet.map.containerPointToLayerPoint([0, 0]); 290 | _leaflet2.default.DomUtil.setPosition(this._el, topLeft); 291 | 292 | var size = this.props.leaflet.map.getSize(); 293 | 294 | if (this._heatmap._width !== size.x) { 295 | this._el.width = this._heatmap._width = size.x; 296 | } 297 | if (this._heatmap._height !== size.y) { 298 | this._el.height = this._heatmap._height = size.y; 299 | } 300 | 301 | if (this._heatmap && !this._frame && !this.props.leaflet.map._animating) { 302 | this._frame = _leaflet2.default.Util.requestAnimFrame(this.redraw, this); 303 | } 304 | 305 | this.redraw(); 306 | }; 307 | 308 | HeatmapLayer.prototype.redraw = function redraw() { 309 | var r = this._heatmap._r; 310 | var size = this.props.leaflet.map.getSize(); 311 | 312 | var maxIntensity = this.props.max === undefined ? 1 : this.getMax(this.props); 313 | 314 | var maxZoom = this.props.maxZoom === undefined ? this.props.leaflet.map.getMaxZoom() : this.getMaxZoom(this.props); 315 | 316 | var v = 1 / Math.pow(2, Math.max(0, Math.min(maxZoom - this.props.leaflet.map.getZoom(), 12)) / 2); 317 | 318 | var cellSize = r / 2; 319 | var panePos = this.props.leaflet.map._getMapPanePos(); 320 | var offsetX = panePos.x % cellSize; 321 | var offsetY = panePos.y % cellSize; 322 | var getLat = this.props.latitudeExtractor; 323 | var getLng = this.props.longitudeExtractor; 324 | var getIntensity = this.props.intensityExtractor; 325 | 326 | var inBounds = function inBounds(p, bounds) { 327 | return bounds.contains(p); 328 | }; 329 | 330 | var filterUndefined = function filterUndefined(row) { 331 | return (0, _lodash6.default)(row, function (c) { 332 | return c !== undefined; 333 | }); 334 | }; 335 | 336 | var roundResults = function roundResults(results) { 337 | return (0, _lodash4.default)(results, function (result, row) { 338 | return (0, _lodash2.default)(filterUndefined(row), function (cell) { 339 | return [Math.round(cell[0]), Math.round(cell[1]), Math.min(cell[2], maxIntensity), cell[3]]; 340 | }).concat(result); 341 | }, []); 342 | }; 343 | 344 | var accumulateInGrid = function accumulateInGrid(points, leafletMap, bounds) { 345 | return (0, _lodash4.default)(points, function (grid, point) { 346 | var latLng = [getLat(point), getLng(point)]; 347 | if (isInvalidLatLngArray(latLng)) { 348 | //skip invalid points 349 | return grid; 350 | } 351 | 352 | var p = leafletMap.latLngToContainerPoint(latLng); 353 | 354 | if (!inBounds(p, bounds)) { 355 | return grid; 356 | } 357 | 358 | var x = Math.floor((p.x - offsetX) / cellSize) + 2; 359 | var y = Math.floor((p.y - offsetY) / cellSize) + 2; 360 | 361 | grid[y] = grid[y] || []; 362 | var cell = grid[y][x]; 363 | 364 | var alt = getIntensity(point); 365 | var k = alt * v; 366 | 367 | if (!cell) { 368 | grid[y][x] = [p.x, p.y, k, 1]; 369 | } else { 370 | cell[0] = (cell[0] * cell[2] + p.x * k) / (cell[2] + k); // x 371 | cell[1] = (cell[1] * cell[2] + p.y * k) / (cell[2] + k); // y 372 | cell[2] += k; // accumulated intensity value 373 | cell[3] += 1; 374 | } 375 | 376 | return grid; 377 | }, []); 378 | }; 379 | 380 | var getBounds = function getBounds() { 381 | return new _leaflet2.default.Bounds(_leaflet2.default.point([-r, -r]), size.add([r, r])); 382 | }; 383 | 384 | var getDataForHeatmap = function getDataForHeatmap(points, leafletMap) { 385 | return roundResults(accumulateInGrid(points, leafletMap, getBounds(leafletMap))); 386 | }; 387 | 388 | var data = getDataForHeatmap(this.props.points, this.props.leaflet.map); 389 | 390 | this._heatmap.clear(); 391 | this._heatmap.data(data).draw(this.getMinOpacity(this.props)); 392 | 393 | this._frame = null; 394 | 395 | if (this.props.onStatsUpdate && this.props.points && this.props.points.length > 0) { 396 | this.props.onStatsUpdate((0, _lodash4.default)(data, function (stats, point) { 397 | stats.max = point[3] > stats.max ? point[3] : stats.max; 398 | stats.min = point[3] < stats.min ? point[3] : stats.min; 399 | return stats; 400 | }, { min: Infinity, max: -Infinity })); 401 | } 402 | }; 403 | 404 | HeatmapLayer.prototype.render = function render() { 405 | return null; 406 | }; 407 | 408 | return HeatmapLayer; 409 | }(_reactLeaflet.MapLayer), _class.propTypes = { 410 | points: _propTypes2.default.array.isRequired, 411 | longitudeExtractor: _propTypes2.default.func.isRequired, 412 | latitudeExtractor: _propTypes2.default.func.isRequired, 413 | intensityExtractor: _propTypes2.default.func.isRequired, 414 | fitBoundsOnLoad: _propTypes2.default.bool, 415 | fitBoundsOnUpdate: _propTypes2.default.bool, 416 | onStatsUpdate: _propTypes2.default.func, 417 | /* props controlling heatmap generation */ 418 | max: _propTypes2.default.number, 419 | radius: _propTypes2.default.number, 420 | maxZoom: _propTypes2.default.number, 421 | minOpacity: _propTypes2.default.number, 422 | blur: _propTypes2.default.number, 423 | gradient: _propTypes2.default.object 424 | }, _temp)); 425 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-leaflet-heatmap-layer", 3 | "version": "2.0.0", 4 | "description": "A custom layer for heatmaps in react-leaflet", 5 | "main": "lib/HeatmapLayer.js", 6 | "scripts": { 7 | "compile": "npm run clean; npm run transpile", 8 | "transpile": "./node_modules/.bin/babel src/HeatmapLayer.js --out-file lib/HeatmapLayer.js", 9 | "clean": "rm -rf ./lib/*", 10 | "example": "webpack-dev-server --config ./example/webpack.config.js", 11 | "lint": "eslint ./src ./example/index.js" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "git+https://github.com/OpenGov/react-leaflet-heatmap-layer.git" 16 | }, 17 | "keywords": [ 18 | "react", 19 | "leaflet", 20 | "layer", 21 | "map", 22 | "maps", 23 | "gis", 24 | "geo", 25 | "geojson", 26 | "heatmap", 27 | "heat" 28 | ], 29 | "author": "Jeremiah Hall ", 30 | "license": "MIT", 31 | "peerDependencies": { 32 | "leaflet": "^1.0.0", 33 | "react-leaflet": "^2.0.0", 34 | "react": "^15.4.1 || ^16.0.0" 35 | }, 36 | "devDependencies": { 37 | "babel-cli": "^6.6.5", 38 | "babel-core": "^6.7.4", 39 | "babel-eslint": "^7.1.1", 40 | "babel-loader": "^6.2.4", 41 | "babel-plugin-object-assign": "^1.2.1", 42 | "babel-plugin-react-transform": "^2.0.0", 43 | "babel-plugin-transform-proto-to-assign": "^6.4.0", 44 | "babel-polyfill": "^6.7.4", 45 | "babel-preset-es2015": "^6.3.13", 46 | "babel-preset-react": "^6.3.13", 47 | "babel-preset-stage-0": "^6.3.13", 48 | "eslint": "^3.15.0", 49 | "eslint-config-airbnb": "^6.2.0", 50 | "eslint-plugin-arrow-function": "^2.0.0", 51 | "eslint-plugin-lean-imports": "^0.3.3", 52 | "eslint-plugin-react": "^4.2.3", 53 | "leaflet": "^1.0.0", 54 | "prop-types": "^15.5.10", 55 | "react": "^16.0.0", 56 | "react-addons-test-utils": "^0.14.7", 57 | "react-dom": "^16.0.0", 58 | "react-leaflet": "^2.0.0", 59 | "react-transform-hmr": "^1.0.4", 60 | "webpack": "^1.12.14", 61 | "webpack-dev-server": "^1.14.1" 62 | }, 63 | "dependencies": { 64 | "lodash.filter": "^4.3.0", 65 | "lodash.foreach": "^4.2.0", 66 | "lodash.isnumber": "^3.0.3", 67 | "lodash.map": "^4.3.0", 68 | "lodash.max": "^4.0.0", 69 | "lodash.min": "^4.0.0", 70 | "lodash.pluck": "^3.1.2", 71 | "lodash.reduce": "^4.3.0", 72 | "simpleheat": "^0.4.0" 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /screenshot.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenGov/react-leaflet-heatmap-layer/d918e91fa73153c63f00239c845c76487143bb48/screenshot.jpg -------------------------------------------------------------------------------- /src/HeatmapLayer.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import map from 'lodash.map'; 3 | import reduce from 'lodash.reduce'; 4 | import filter from 'lodash.filter'; 5 | import min from 'lodash.min'; 6 | import max from 'lodash.max'; 7 | import isNumber from 'lodash.isnumber'; 8 | import L from 'leaflet'; 9 | import { MapLayer, withLeaflet } from 'react-leaflet'; 10 | import simpleheat from 'simpleheat'; 11 | import PropTypes from 'prop-types'; 12 | 13 | export type LngLat = { 14 | lng: number; 15 | lat: number; 16 | } 17 | 18 | export type Point = { 19 | x: number; 20 | y: number; 21 | } 22 | 23 | export type Bounds = { 24 | contains: (latLng: LngLat) => boolean; 25 | } 26 | 27 | export type Pane = { 28 | appendChild: (element: Object) => void; 29 | } 30 | 31 | export type Panes = { 32 | overlayPane: Pane; 33 | } 34 | 35 | export type Map = { 36 | layerPointToLatLng: (lngLat: Point) => LngLat; 37 | latLngToLayerPoint: (lngLat: LngLat) => Point; 38 | on: (event: string, handler: () => void) => void; 39 | getBounds: () => Bounds; 40 | getPanes: () => Panes; 41 | invalidateSize: () => void; 42 | options: Object; 43 | } 44 | 45 | export type LeafletZoomEvent = { 46 | zoom: number; 47 | center: Object; 48 | } 49 | 50 | function isInvalid(num: number): boolean { 51 | return !isNumber(num) && !num; 52 | } 53 | 54 | function isValid(num: number): boolean { 55 | return !isInvalid(num); 56 | } 57 | 58 | function isValidLatLngArray(arr: Array): boolean { 59 | return filter(arr, isValid).length === arr.length; 60 | } 61 | 62 | function isInvalidLatLngArray(arr: Array): boolean { 63 | return !isValidLatLngArray(arr); 64 | } 65 | 66 | function safeRemoveLayer(leafletMap: Map, el): void { 67 | const { overlayPane } = leafletMap.getPanes(); 68 | if (overlayPane && overlayPane.contains(el)) { 69 | overlayPane.removeChild(el); 70 | } 71 | } 72 | 73 | function shouldIgnoreLocation(loc: LngLat): boolean { 74 | return isInvalid(loc.lng) || isInvalid(loc.lat); 75 | } 76 | 77 | export default withLeaflet(class HeatmapLayer extends MapLayer { 78 | static propTypes = { 79 | points: PropTypes.array.isRequired, 80 | longitudeExtractor: PropTypes.func.isRequired, 81 | latitudeExtractor: PropTypes.func.isRequired, 82 | intensityExtractor: PropTypes.func.isRequired, 83 | fitBoundsOnLoad: PropTypes.bool, 84 | fitBoundsOnUpdate: PropTypes.bool, 85 | onStatsUpdate: PropTypes.func, 86 | /* props controlling heatmap generation */ 87 | max: PropTypes.number, 88 | radius: PropTypes.number, 89 | maxZoom: PropTypes.number, 90 | minOpacity: PropTypes.number, 91 | blur: PropTypes.number, 92 | gradient: PropTypes.object 93 | }; 94 | 95 | createLeafletElement() { 96 | return null; 97 | } 98 | 99 | componentDidMount(): void { 100 | const canAnimate = this.props.leaflet.map.options.zoomAnimation && L.Browser.any3d; 101 | const zoomClass = `leaflet-zoom-${canAnimate ? 'animated' : 'hide'}`; 102 | const mapSize = this.props.leaflet.map.getSize(); 103 | const transformProp = L.DomUtil.testProp( 104 | ['transformOrigin', 'WebkitTransformOrigin', 'msTransformOrigin'] 105 | ); 106 | 107 | this._el = L.DomUtil.create('canvas', zoomClass); 108 | this._el.style[transformProp] = '50% 50%'; 109 | this._el.width = mapSize.x; 110 | this._el.height = mapSize.y; 111 | 112 | const el = this._el; 113 | 114 | const Heatmap = L.Layer.extend({ 115 | onAdd: (leafletMap) => leafletMap.getPanes().overlayPane.appendChild(el), 116 | addTo: (leafletMap) => { 117 | leafletMap.addLayer(this); 118 | return this; 119 | }, 120 | onRemove: (leafletMap) => safeRemoveLayer(leafletMap, el) 121 | }); 122 | 123 | this.leafletElement = new Heatmap(); 124 | super.componentDidMount(); 125 | this._heatmap = simpleheat(this._el); 126 | this.reset(); 127 | 128 | if (this.props.fitBoundsOnLoad) { 129 | this.fitBounds(); 130 | } 131 | this.attachEvents(); 132 | this.updateHeatmapProps(this.getHeatmapProps(this.props)); 133 | } 134 | 135 | getMax(props) { 136 | return props.max || 3.0; 137 | } 138 | 139 | getRadius(props) { 140 | return props.radius || 30; 141 | } 142 | 143 | getMaxZoom(props) { 144 | return props.maxZoom || 18; 145 | } 146 | 147 | getMinOpacity(props) { 148 | return props.minOpacity || 0.01; 149 | } 150 | 151 | getBlur(props) { 152 | return props.blur || 15; 153 | } 154 | 155 | getHeatmapProps(props) { 156 | return { 157 | minOpacity: this.getMinOpacity(props), 158 | maxZoom: this.getMaxZoom(props), 159 | radius: this.getRadius(props), 160 | blur: this.getBlur(props), 161 | max: this.getMax(props), 162 | gradient: props.gradient 163 | }; 164 | } 165 | 166 | componentWillReceiveProps(nextProps: Object): void { 167 | const currentProps = this.props; 168 | const nextHeatmapProps = this.getHeatmapProps(nextProps); 169 | 170 | this.updateHeatmapGradient(nextHeatmapProps.gradient); 171 | 172 | const hasRadiusUpdated = nextHeatmapProps.radius !== currentProps.radius; 173 | const hasBlurUpdated = nextHeatmapProps.blur !== currentProps.blur; 174 | 175 | if (hasRadiusUpdated || hasBlurUpdated) { 176 | this.updateHeatmapRadius(nextHeatmapProps.radius, nextHeatmapProps.blur); 177 | } 178 | 179 | if (nextHeatmapProps.max !== currentProps.max) { 180 | this.updateHeatmapMax(nextHeatmapProps.max); 181 | } 182 | 183 | } 184 | 185 | /** 186 | * Update various heatmap properties like radius, gradient, and max 187 | */ 188 | updateHeatmapProps(props: Object) { 189 | this.updateHeatmapRadius(props.radius, props.blur); 190 | this.updateHeatmapGradient(props.gradient); 191 | this.updateHeatmapMax(props.max); 192 | } 193 | 194 | /** 195 | * Update the heatmap's radius and blur (blur is optional) 196 | */ 197 | updateHeatmapRadius(radius: number, blur: ?number): void { 198 | if (radius) { 199 | this._heatmap.radius(radius, blur); 200 | } 201 | } 202 | 203 | /** 204 | * Update the heatmap's gradient 205 | */ 206 | updateHeatmapGradient(gradient: Object): void { 207 | if (gradient) { 208 | this._heatmap.gradient(gradient); 209 | } 210 | } 211 | 212 | /** 213 | * Update the heatmap's maximum 214 | */ 215 | updateHeatmapMax(maximum: number): void { 216 | if (maximum) { 217 | this._heatmap.max(maximum); 218 | } 219 | } 220 | 221 | componentWillUnmount(): void { 222 | safeRemoveLayer(this.props.leaflet.map, this._el); 223 | } 224 | 225 | fitBounds(): void { 226 | const points = this.props.points; 227 | const lngs = map(points, this.props.longitudeExtractor); 228 | const lats = map(points, this.props.latitudeExtractor); 229 | const ne = { lng: max(lngs), lat: max(lats) }; 230 | const sw = { lng: min(lngs), lat: min(lats) }; 231 | 232 | if (shouldIgnoreLocation(ne) || shouldIgnoreLocation(sw)) { 233 | return; 234 | } 235 | 236 | this.props.leaflet.map.fitBounds(L.latLngBounds(L.latLng(sw), L.latLng(ne))); 237 | } 238 | 239 | componentDidUpdate(): void { 240 | this.props.leaflet.map.invalidateSize(); 241 | if (this.props.fitBoundsOnUpdate) { 242 | this.fitBounds(); 243 | } 244 | this.reset(); 245 | } 246 | 247 | shouldComponentUpdate(): boolean { 248 | return true; 249 | } 250 | 251 | attachEvents(): void { 252 | const leafletMap: Map = this.props.leaflet.map; 253 | leafletMap.on('viewreset', () => this.reset()); 254 | leafletMap.on('moveend', () => this.reset()); 255 | if (leafletMap.options.zoomAnimation && L.Browser.any3d) { 256 | leafletMap.on('zoomanim', this._animateZoom, this); 257 | } 258 | } 259 | 260 | 261 | _animateZoom(e: LeafletZoomEvent): void { 262 | const scale = this.props.leaflet.map.getZoomScale(e.zoom); 263 | const offset = this.props.leaflet.map 264 | ._getCenterOffset(e.center) 265 | ._multiplyBy(-scale) 266 | .subtract(this.props.leaflet.map._getMapPanePos()); 267 | 268 | if (L.DomUtil.setTransform) { 269 | L.DomUtil.setTransform(this._el, offset, scale); 270 | } else { 271 | this._el.style[L.DomUtil.TRANSFORM] = 272 | `${L.DomUtil.getTranslateString(offset)} scale(${scale})`; 273 | } 274 | } 275 | 276 | reset(): void { 277 | const topLeft = this.props.leaflet.map.containerPointToLayerPoint([0, 0]); 278 | L.DomUtil.setPosition(this._el, topLeft); 279 | 280 | const size = this.props.leaflet.map.getSize(); 281 | 282 | if (this._heatmap._width !== size.x) { 283 | this._el.width = this._heatmap._width = size.x; 284 | } 285 | if (this._heatmap._height !== size.y) { 286 | this._el.height = this._heatmap._height = size.y; 287 | } 288 | 289 | if (this._heatmap && !this._frame && !this.props.leaflet.map._animating) { 290 | this._frame = L.Util.requestAnimFrame(this.redraw, this); 291 | } 292 | 293 | this.redraw(); 294 | } 295 | 296 | redraw(): void { 297 | const r = this._heatmap._r; 298 | const size = this.props.leaflet.map.getSize(); 299 | 300 | const maxIntensity = this.props.max === undefined 301 | ? 1 302 | : this.getMax(this.props); 303 | 304 | const maxZoom = this.props.maxZoom === undefined 305 | ? this.props.leaflet.map.getMaxZoom() 306 | : this.getMaxZoom(this.props); 307 | 308 | const v = 1 / Math.pow( 309 | 2, 310 | Math.max(0, Math.min(maxZoom - this.props.leaflet.map.getZoom(), 12)) / 2 311 | ); 312 | 313 | const cellSize = r / 2; 314 | const panePos = this.props.leaflet.map._getMapPanePos(); 315 | const offsetX = panePos.x % cellSize; 316 | const offsetY = panePos.y % cellSize; 317 | const getLat = this.props.latitudeExtractor; 318 | const getLng = this.props.longitudeExtractor; 319 | const getIntensity = this.props.intensityExtractor; 320 | 321 | const inBounds = (p, bounds) => bounds.contains(p); 322 | 323 | const filterUndefined = (row) => filter(row, c => c !== undefined); 324 | 325 | const roundResults = (results) => reduce(results, (result, row) => 326 | map(filterUndefined(row), (cell) => [ 327 | Math.round(cell[0]), 328 | Math.round(cell[1]), 329 | Math.min(cell[2], maxIntensity), 330 | cell[3] 331 | ]).concat(result), 332 | [] 333 | ); 334 | 335 | const accumulateInGrid = (points, leafletMap, bounds) => reduce(points, (grid, point) => { 336 | const latLng = [getLat(point), getLng(point)]; 337 | if (isInvalidLatLngArray(latLng)) { //skip invalid points 338 | return grid; 339 | } 340 | 341 | const p = leafletMap.latLngToContainerPoint(latLng); 342 | 343 | if (!inBounds(p, bounds)) { 344 | return grid; 345 | } 346 | 347 | const x = Math.floor((p.x - offsetX) / cellSize) + 2; 348 | const y = Math.floor((p.y - offsetY) / cellSize) + 2; 349 | 350 | grid[y] = grid[y] || []; 351 | const cell = grid[y][x]; 352 | 353 | const alt = getIntensity(point); 354 | const k = alt * v; 355 | 356 | if (!cell) { 357 | grid[y][x] = [p.x, p.y, k, 1]; 358 | } else { 359 | cell[0] = (cell[0] * cell[2] + p.x * k) / (cell[2] + k); // x 360 | cell[1] = (cell[1] * cell[2] + p.y * k) / (cell[2] + k); // y 361 | cell[2] += k; // accumulated intensity value 362 | cell[3] += 1; 363 | } 364 | 365 | return grid; 366 | }, []); 367 | 368 | const getBounds = () => new L.Bounds(L.point([-r, -r]), size.add([r, r])); 369 | 370 | const getDataForHeatmap = (points, leafletMap) => roundResults( 371 | accumulateInGrid( 372 | points, 373 | leafletMap, 374 | getBounds(leafletMap) 375 | ) 376 | ); 377 | 378 | const data = getDataForHeatmap(this.props.points, this.props.leaflet.map); 379 | 380 | this._heatmap.clear(); 381 | this._heatmap.data(data).draw(this.getMinOpacity(this.props)); 382 | 383 | this._frame = null; 384 | 385 | if (this.props.onStatsUpdate && this.props.points && this.props.points.length > 0) { 386 | this.props.onStatsUpdate( 387 | reduce(data, (stats, point) => { 388 | stats.max = point[3] > stats.max ? point[3] : stats.max; 389 | stats.min = point[3] < stats.min ? point[3] : stats.min; 390 | return stats; 391 | }, { min: Infinity, max: -Infinity }) 392 | ); 393 | } 394 | } 395 | 396 | 397 | render(): React.Element { 398 | return null; 399 | } 400 | 401 | }); 402 | --------------------------------------------------------------------------------