maputnik/src/components/map/MapboxGlMap.jsx

96 lines
2.2 KiB
React
Raw Normal View History

import React from 'react'
2016-12-24 15:24:22 +01:00
import ReactDOM from 'react-dom'
2016-12-19 12:51:23 +01:00
import MapboxGl from 'mapbox-gl'
2016-12-24 15:24:22 +01:00
import FeatureLayerTable from './FeatureLayerTable'
import validateColor from 'mapbox-gl-style-spec/lib/validate/validate_color'
2016-12-20 11:44:22 +01:00
import style from '../../libs/style.js'
2016-12-24 15:14:31 +01:00
import 'mapbox-gl/dist/mapbox-gl.css'
2016-12-20 11:44:22 +01:00
2016-12-24 15:24:22 +01:00
function renderTable(feature) {
var mountNode = document.createElement('div');
ReactDOM.render(<FeatureLayerTable feature={feature} />, mountNode);
return mountNode.innerHTML;
}
2016-12-24 14:42:57 +01:00
export default class MapboxGlMap extends React.Component {
2016-12-19 21:21:10 +01:00
static propTypes = {
2016-12-24 14:42:57 +01:00
onDataChange: React.PropTypes.func,
mapStyle: React.PropTypes.object.isRequired,
accessToken: React.PropTypes.string,
2016-12-24 15:14:31 +01:00
style: React.PropTypes.object,
2016-12-19 21:21:10 +01:00
}
static defaultProps = {
2016-12-24 14:42:57 +01:00
onMapLoaded: () => {},
onDataChange: () => {},
2016-12-19 21:21:10 +01:00
}
2016-12-19 14:52:04 +01:00
constructor(props) {
super(props)
this.state = { map: null }
}
2016-12-24 14:42:57 +01:00
componentWillReceiveProps(nextProps) {
2016-12-20 13:28:50 +01:00
if(!this.state.map) return
2016-12-20 13:28:50 +01:00
//Mapbox GL now does diffing natively so we don't need to calculate
//the necessary operations ourselves!
2016-12-20 16:08:49 +01:00
this.state.map.setStyle(nextProps.mapStyle, { diff: true})
}
componentDidMount() {
MapboxGl.accessToken = this.props.accessToken
const map = new MapboxGl.Map({
container: this.container,
2016-12-20 16:08:49 +01:00
style: this.props.mapStyle,
2016-12-24 15:17:15 +01:00
hash: true,
2016-12-24 14:42:57 +01:00
})
2016-12-24 15:14:31 +01:00
const nav = new MapboxGl.NavigationControl();
map.addControl(nav, 'top-right');
2016-12-24 14:42:57 +01:00
map.on("style.load", () => {
this.setState({ map });
2016-12-24 14:42:57 +01:00
})
map.on("data", e => {
if(e.dataType !== 'tile') return
this.props.onDataChange({
map: this.state.map
})
})
2016-12-24 15:24:22 +01:00
map.on('click', this.displayPopup.bind(this));
}
displayPopup(e) {
const features = this.state.map.queryRenderedFeatures(e.point, {
layers: this.layers
});
if (!features.length) {
return
}
const feature = features[0]
console.log('Click on feature', feature)
const popup = new MapboxGl.Popup()
.setLngLat(e.lngLat)
.setHTML(renderTable(feature))
.addTo(this.state.map)
2016-12-24 14:42:57 +01:00
}
render() {
return <div
ref={x => this.container = x}
style={{
position: "fixed",
top: 0,
bottom: 0,
height: "100%",
width: "100%",
2016-12-24 15:14:31 +01:00
...this.props.style,
2016-12-24 14:42:57 +01:00
}}></div>
}
}