maputnik/src/map.jsx

72 lines
2 KiB
React
Raw Normal View History

import React from 'react'
2016-09-10 00:43:41 +02:00
import MapboxGl from 'mapbox-gl';
2016-09-10 16:05:04 +02:00
import { fullHeight } from './theme.js'
import style from './style.js'
2016-09-10 14:47:06 +02:00
import Immutable from 'immutable'
2016-09-19 15:06:34 +02:00
import validateColor from 'mapbox-gl-style-spec/lib/validate/validate_color'
2016-09-08 19:47:29 +02:00
export class Map extends React.Component {
2016-09-09 15:49:23 +02:00
static propTypes = {
2016-09-10 15:15:17 +02:00
mapStyle: React.PropTypes.instanceOf(Immutable.Map).isRequired,
2016-09-10 16:26:39 +02:00
accessToken: React.PropTypes.string,
2016-09-10 15:15:17 +02:00
}
2016-09-09 15:49:23 +02:00
2016-09-10 00:43:41 +02:00
componentWillReceiveProps(nextProps) {
2016-09-10 16:26:39 +02:00
const tokenChanged = nextProps.accessToken !== MapboxGl.accessToken
2016-09-10 14:47:06 +02:00
// If the id has changed a new style has been uplaoded and
// it is safer to do a full new render
// TODO: might already be handled in diff algorithm?
2016-09-10 14:47:06 +02:00
const mapIdChanged = this.props.mapStyle.get('id') !== nextProps.mapStyle.get('id')
2016-09-10 16:26:39 +02:00
if(mapIdChanged || tokenChanged) {
this.state.map.setStyle(style.toJSON(nextProps.mapStyle))
2016-09-10 14:47:06 +02:00
return
}
// TODO: If there is no map yet we need to apply the changes later?
if(this.state.map) {
style.diffStyles(this.props.mapStyle, nextProps.mapStyle).forEach(change => {
2016-09-19 15:06:34 +02:00
//TODO: Invalid outline color can cause map to freeze?
if(change.command === "setPaintProperty" && change.args[1] === "fill-outline-color" ) {
const value = change.args[2]
if(validateColor({value}).length > 0) {
return
}
}
2016-09-15 18:51:49 +02:00
console.log(change.command, ...change.args)
2016-09-10 14:47:06 +02:00
this.state.map[change.command].apply(this.state.map, change.args);
2016-09-10 00:43:41 +02:00
});
}
}
2016-09-10 15:15:17 +02:00
shouldComponentUpdate(nextProps, nextState) {
//TODO: If we enable this React mixin for immutable comparison we can remove this?
2016-09-10 15:15:17 +02:00
return nextProps.mapStyle !== this.props.mapStyle
}
2016-09-10 00:43:41 +02:00
componentDidMount() {
2016-09-10 16:26:39 +02:00
MapboxGl.accessToken = this.props.accessToken
2016-09-10 14:47:06 +02:00
2016-09-10 00:43:41 +02:00
const map = new MapboxGl.Map({
container: this.container,
style: style.toJSON(this.props.mapStyle),
2016-09-10 00:43:41 +02:00
});
2016-09-10 15:15:17 +02:00
map.on("style.load", (...args) => {
this.setState({ map });
});
2016-09-10 00:43:41 +02:00
}
2016-09-08 19:47:29 +02:00
render() {
2016-09-10 16:11:43 +02:00
return <div
ref={x => this.container = x}
style={{
...fullHeight,
width: "100%",
}}></div>
2016-09-08 19:47:29 +02:00
}
}