Skip to content

Instantly share code, notes, and snippets.

@christospappas
Last active February 2, 2017 07:53
Show Gist options
  • Save christospappas/fff23fc39635bb14fc73e594f112b433 to your computer and use it in GitHub Desktop.
Save christospappas/fff23fc39635bb14fc73e594f112b433 to your computer and use it in GitHub Desktop.
/*
Here's an example of using diffStyles with React to manage Mapbox.
Use this along with Redux to manage state changes. Nice and simple!
*/
import React, { Component } from 'react';
import config from 'config';
import mapboxgl from 'mapbox-gl';
import diffStyles from 'mapbox-gl-style-spec/lib/diff';
import 'mapbox-gl-css';
class Mapbox extends Component {
constructor(props) {
super(props);
mapboxgl.accessToken = config.MAPBOX_API_ACCESS_TOKEN;
}
componentDidMount() {
const { styles, onMouseMove, onMouseOut, onMove } = this.props;
const mapOptions = Object.assign({ container: this.refs.map }, styles);
this._map = new mapboxgl.Map(mapOptions);
if (onMouseMove) this._map.on('mousemove', onMouseMove);
if (onMouseOut) this._map.on('mouseout', onMouseOut);
if (onMove) this._map.on('move', onMove);
this._map.addControl(new mapboxgl.NavigationControl());
}
componentWillUnmount() {
const { onMouseMove, onMouseOut, onMove } = this.props;
if (onMouseMove) this._map.off('mousemove', onMouseMove);
if (onMouseOut) this._map.off('mouseout', onMouseOut);
if (onMove) this._map.off('move', onMove);
}
componentWillReceiveProps(nextProps) {
// TODO: handle event handler changes
const { styles } = this.props;
const changes = diffStyles(styles, Object.assign({}, styles, nextProps.styles));
this.applyChanges(changes);
}
render() {
const mapStyle = {position: 'absolute', width: '100%', height: '100%'};
return (
<div style={mapStyle} ref='map'></div>
);
}
applyChanges(changes) {
changes.forEach((change) => {
this._map[change.command].apply(this._map, change.args);
});
}
}
Mapbox.propTypes = {
styles: React.PropTypes.object.isRequired,
onMouseMove: React.PropTypes.func,
onMouseOut: React.PropTypes.func,
onMove: React.PropTypes.func,
};
export default Mapbox;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment