React OpenLayers polygon draw style
by mcneela86
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.min.js"></script>
<link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.min.js"></script>
<script src="https://openlayers.org/en/v5.3.0/build/ol.js"></script>
<link rel="stylesheet" href="https://openlayers.org/en/v5.3.0/css/ol.css">
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
CSS
.ol-overlaycontainer-stopevent > .ol-scale-line ~ .ol-scale-line {
bottom: 36px;
}
Babel + JSX
const App = () => <Map><Polygon /></Map>;
class Map extends React.Component {
constructor(props) {
super(props);
// Define base layer
this.baseLayer = new ol.layer.Tile({ source: new ol.source.OSM() });
// Define base view
this.baseView = new ol.View({
center: ol.proj.fromLonLat([37.41, 8.82]),
zoom: 4
});
// Add map, base view and layer
this.map = new ol.Map({
layers: [this.baseLayer],
view: this.baseView
});
}
static childContextTypes = {
map: PropTypes.object
}
getChildContext() {
return {
map: this.map
}
}
componentDidMount() {
// set map target element
this.map.setTarget(this.refs.map);
}
render() {
return <div ref="map">
{this.props.children}
</div>;
}
}
class Polygon extends React.Component {
static contextTypes = {
map: PropTypes.object
}
componentDidMount() {
const source = new ol.source.Vector({wrapX: false});
this.polygonBase = new ol.layer.Vector({ source });
this.context.map.addLayer(this.polygonBase);
// Define the polygon draw interaction
this.draw = new ol.interaction.Draw({
source: source,
type: 'Polygon',
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'rgba(0, 0, 0, 0.5)',
lineDash: [10, 10],
width: 3
}),
image: new ol.style.Circle({
fill: new ol.style.Fill({ color: [0, 0, 0, 0.2] }),
stroke: new ol.style.Stroke({
color: [0, 0, 0, 0.5],
width: 1
}),
radius: 4
})
})
});
// Add the draw interaction
this.context.map.addInteraction(this.draw);
this.draw.on('drawstart', event => {
this.polygonFirstCoordinate = event.feature.getGeometry().getFirstCoordinate();
});
}
componentWillUnmount () {
this.context.map.removeInteraction(this.draw);
}
render() { return <p>Drawing polygon</p>;...