react google map polygon drag and update coordinates

Viewed 310

Here i want to drag and edit polygon. I got the editable part right which is adding/editing the node, but got stuck at updating coordinates (cords) while dragging. Here if i drag and then try to edit the existing node it will fail but works when its not dragged. So i need to update the cords while dragging the polygon to a new location.

import React from 'react';
import { compose, withProps } from 'recompose';
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Polygon,
} from 'react-google-maps';

const MAP_API_KEY = process.env.MAP_API_KEY;

export class Map extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      coords: [
        { lat: 25.774, lng: -60.19 },
        { lat: 18.466, lng: -46.118 },
        { lat: 32.321, lng: -44.757 },
      ],
    };
  }

  render() {
    const { coords } = this.state;
    return (
      <GoogleMap
        defaultZoom={3}
        defaultCenter={new google.maps.LatLng(24.886, -70.268)}
      >
        <Polygon
          editable={true}
          draggable={true}
          path={coords}
          key={1}
          options={{
            fillColor: '#000',
            fillOpacity: 0.4,
            strokeColor: '#000',
            strokeOpacity: 1,
            strokeWeight: 1,
          }}
          onMouseUp={e => {
            if (e.edge !== undefined) {
              const nextPath = [...coords];
              nextPath.splice(e.edge + 1, 0, {
                lat: e.latLng.lat(),
                lng: e.latLng.lng(),
              });
              console.log('next path :', nextPath);
              this.setState({ coords: nextPath });
            } else if (e.vertex !== undefined) {
              const nextPath = coords.map((coord, index) => {
                if (index === e.vertex) {
                  return { lat: e.latLng.lat(), lng: e.latLng.lng() };
                } else {
                  return coord;
                }
              });
              console.log('edit path', nextPath);
              this.setState({ coords: nextPath });
            }
          }}
          onDragEnd={e => console.log('Stuck')}
        />
      </GoogleMap>
    );
  }
}

export default compose(
  withProps({
    googleMapURL: `https://maps.googleapis.com/maps/api/js?key=${MAP_API_KEY}&libraries=geometry,drawing,places`,
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `400px` }} />,
    mapElement: <div style={{ height: `100%` }} />,
  }),
  withScriptjs,
  withGoogleMap,
)(Map);
0 Answers
Related