Skip to content

Instantly share code, notes, and snippets.

@qrobin qrobin/poly.js
Created Jun 20, 2017

Embed
What would you like to do?
import React, { Component } from 'react';
import { withGoogleMap, GoogleMap } from 'react-google-maps';
import DrawingManager from 'react-google-maps/lib/drawing/DrawingManager';
// import { createContainer } from 'meteor/react-meteor-data';
import _ from 'underscore';
const DrawingGoogleMap = withGoogleMap(props => (
<GoogleMap
defaultZoom={13}
defaultCenter={new google.maps.LatLng(50.45, 30.52)}>
<DrawingManager
onPolygonComplete={poly => props.onPolygonComplete(poly)}
defaultDrawingMode={google.maps.drawing.OverlayType.POLYGON}
defaultOptions={{
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.POLYGON
]
},
polygonOptions: {
fillColor: '#ffff00',
fillOpacity: 0.5,
strokeWeight: 2,
clickable: true,
editable: true,
/* draggable: true,*/
zIndex: 1
}
}}
/>
</GoogleMap>
));
export default class extends Component {
constructor(props) {
super(props);
this.state = {
polygons: []
};
}
_computeCoordinates(array) {
const result = [];
array.forEach((el) => {
result.push(el.toJSON());
});
return result;
}
_computePolygonArea() {
return google.maps.geometry.spherical.computeArea(array);
}
_handlePolygonComplete = (poly) => {
const coordinates = this._computeCoordinates(poly.getPath().getArray());
const area = google.maps.geometry.spherical.computeArea(poly.getPath().getArray());
let polygons = this.state.polygons.slice();
polygons.push({
coordinates,
event_id: 115, // COMPUTE ME PLZ
area: area
});
this.setState({ polygons }, () => {
const _this = this;
const _addPolygonListener = (type) => {
google.maps.event.addListener(poly.getPath(), type, function(index, obj) {
polygons = _this.state.polygons;
const newPolyCoordinates = _this._computeCoordinates(this.getArray());
let indexToChange;
_.each(polygons, (_polyInState, _polyInStateIndex) => {
let l = newPolyCoordinates.length;
let comparedLength = (type === 'remove_at') ? (l + 1) : (type === 'insert_at') ? (l - 1) : l;
if (_polyInState.coordinates.length === comparedLength) {
_.each(newPolyCoordinates, (it) => {
if (_.find(_polyInState.coordinates, it)) {
indexToChange = _polyInStateIndex;
return;
}
});
}
});
polygons[indexToChange].coordinates = newPolyCoordinates;
_this.setState({ polygons });
});
};
// Change point position listener
_addPolygonListener('set_at');
// Add new point listener
_addPolygonListener('insert_at');
// Remove point listener
_addPolygonListener('remove_at');
});
}
render() {
return (
<DrawingGoogleMap
onPolygonComplete={(poly) => this._handlePolygonComplete(poly)}
containerElement={( <div style={{ height: '100%' }} /> )}
mapElement={( <div style={{ height: '100%' }} /> )} />
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.