Skip to content

Instantly share code, notes, and snippets.

@ivesdebruycker
Created January 24, 2018 09:47
Show Gist options
  • Save ivesdebruycker/814578d65cea8e6db40d3b54005395cb to your computer and use it in GitHub Desktop.
Save ivesdebruycker/814578d65cea8e6db40d3b54005395cb to your computer and use it in GitHub Desktop.
React component for OpenLayers
import React, { Component } from 'react';
import PropTypes from 'prop-types'
import ol from 'openlayers';
class PoiMapContainer extends Component {
constructor(props) {
super(props);
this.state = {
map: null,
}
}
componentDidMount() {
let poi = this.props.poi;
let location = ol.proj.fromLonLat([poi.location.coordinates[1], poi.location.coordinates[0]]);
let poiFeature = new ol.Feature({
geometry: new ol.geom.Point(location)
});
poiFeature.setStyle(new ol.style.Style({
image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
color: this.props.color,
crossOrigin: 'anonymous',
src: 'https://openlayers.org/en/v4.4.2/examples/data/dot.png'
}))
}));
const vectorSource = new ol.source.Vector({
features: [poiFeature]
});
const vectorLayer = new ol.layer.Vector({
source: vectorSource
});
const rasterLayer = new ol.layer.Tile({
title: 'OMS Imagery',
source: new ol.source.OSM({}),
});
const map = new ol.Map({
layers: [rasterLayer, vectorLayer],
target: document.getElementById('map'),
view: new ol.View({
center: location,
zoom: 14
})
});
if (this.props.modify) {
let modify = new ol.interaction.Modify({source: vectorSource, pixelTolerance: 20});
map.addInteraction(modify);
modify.on('modifyend', e => {
const coordinates = e.features.getArray()[0].getGeometry().getCoordinates();
if (this.props.onModifyEnd) {
const lonLat = ol.proj.toLonLat(coordinates)
this.props.onModifyEnd([lonLat[1], lonLat[0]])
}
});
}
}
render() {
return (
<div>
<div className="openlayers-map" id="map">
{this.props.children}
</div>
</div>
)
}
}
const coordinatesPropType = function(props, propName, componentName) {
if (!Array.isArray(props[propName]) || props[propName].length != 2 || !props[propName].every(n => !isNaN(parseFloat(n)) && isFinite(n))) {
return new Error(`${propName} needs to be an array of two numbers`);
}
return null
}
PoiMapContainer.propTypes = {
poi: PropTypes.shape({
location: PropTypes.shape({
coordinates: coordinatesPropType,
}).isRequired,
}).isRequired,
color: PropTypes.string.isRequired,
modify: PropTypes.bool,
onModifyEnd: PropTypes.func,
};
export default PoiMapContainer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment