0

I need to be able to store the coordinates of all the polygons I have drawn in an array, and that when the shape of an already generated one changes, the updated coordinates are stored in the array. Does anyone know how to do it?

For now I managed to save the coordinates of the last drawing I make, but not all the drawings, much less the changes.

var drawingManager;
var all_overlays = [];
var selectedShape;
var colors = ['#1E90FF', '#FF1493', '#32CD32', '#FF8C00', '#4B0082'];
var selectedColor;
var colorButtons = {};

function clearSelection() {
  if (selectedShape) {
    selectedShape.setEditable(false);
    selectedShape = null;
  }
}

function setSelection(shape) {
  clearSelection();
  selectedShape = shape;
  shape.setEditable(true);
  selectColor(shape.get('fillColor') || shape.get('strokeColor'));
}

function deleteSelectedShape() {
  if (selectedShape) {
    selectedShape.setMap(null);
  }
}

function deleteAllShape() {
  for (var i = 0; i < all_overlays.length; i++) {
    all_overlays[i].overlay.setMap(null);
  }
  all_overlays = [];
}

function selectColor(color) {
  selectedColor = color;
  for (var i = 0; i < colors.length; ++i) {
    var currColor = colors[i];
    colorButtons[currColor].style.border = currColor == color ? '2px solid #789' : '2px solid #fff';
  }

  // Retrieves the current options from the drawing manager and replaces the
  // stroke or fill color as appropriate.
  var polygonOptions = drawingManager.get('polygonOptions');
  polygonOptions.fillColor = color;
  drawingManager.set('polygonOptions', polygonOptions);
}

function setSelectedShapeColor(color) {
  if (selectedShape) {
    if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
      selectedShape.set('strokeColor', color);
    } else {
      selectedShape.set('fillColor', color);
    }
  }
}

function makeColorButton(color) {
  var button = document.createElement('span');
  button.className = 'color-button';
  button.style.backgroundColor = color;
  google.maps.event.addDomListener(button, 'click', function() {
    selectColor(color);
    setSelectedShapeColor(color);
  });

  return button;
}

function buildColorPalette() {
  var colorPalette = document.getElementById('color-palette');
  for (var i = 0; i < colors.length; ++i) {
    var currColor = colors[i];
    var colorButton = makeColorButton(currColor);
    colorPalette.appendChild(colorButton);
    colorButtons[currColor] = colorButton;
  }
  selectColor(colors[0]);
}

function initialize() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: new google.maps.LatLng(22.344, 114.048),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    disableDefaultUI: true,
    zoomControl: true
  });

  var polyOptions = {
    strokeWeight: 0,
    fillOpacity: 0.45,
    editable: true
  };
  // Creates a drawing manager attached to the map that allows the user to draw
  // markers, lines, and shapes.
  drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.POLYGON,
    polygonOptions: polyOptions,
    map: map
  });

  drawingManager.setOptions ({ drawingControlOptions: {drawingModes: [google.maps.drawing.OverlayType.POLYGON]}});

  google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
    all_overlays.push(e);
    if (e.type != google.maps.drawing.OverlayType.MARKER) {
      // Switch back to non-drawing mode after drawing a shape.
      drawingManager.setDrawingMode(null);

      // Add an event listener that selects the newly-drawn shape when the user
      // mouses down on it.
      var newShape = e.overlay;
      newShape.type = e.type;
      google.maps.event.addListener(newShape, 'click', function() {
        setSelection(newShape);
      });
      setSelection(newShape);
    }
    google.maps.event.addListener(newShape.getPath(), "insert_at", getPolygonCoords(newShape));

  });

  // Clear the current selection when the drawing mode is changed, or when the
  // map is clicked.
  google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
  google.maps.event.addListener(map, 'click', clearSelection);
  google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);
  google.maps.event.addDomListener(document.getElementById('delete-all-button'), 'click', deleteAllShape);

  buildColorPalette();
}
google.maps.event.addDomListener(window, 'load', initialize);

function getPolygonCoords(newShape) {
      var single_coordinates = [];
      var len = newShape.getPath().getLength();
      for (var p = 0; p < len; p++) {
          var latLng = newShape.getPath(p).getAt(p).toUrlValue(5).split(',');
          latLng = '{"lat":'+latLng[0]+',"lng":'+latLng[1]+'}';
          single_coordinates.push(latLng);
      }

    console.log(single_coordinates)
}
#map,
html,
body {
  padding: 0;
  margin: 0;
  height: 100%;
}
#panel {
  width: 200px;
  font-family: Arial, sans-serif;
  font-size: 13px;
  float: right;
  margin: 10px;
}
#color-palette {
  clear: both;
}
.color-button {
  width: 14px;
  height: 14px;
  font-size: 0;
  margin: 2px;
  float: left;
  cursor: pointer;
}
#delete-button {
  margin-top: 5px;
}
<script src="http://maps.google.com/maps/api/js?libraries=drawing&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="panel">
  <div id="color-palette"></div>
  <div>
    <button id="delete-button">Delete Selected Shape</button>
    <button id="delete-all-button">Delete All Shapes</button>
  </div>
</div>
<div id="map"></div>
  • What array do you want to save the coordinates in? What are you planning on doing with them once you have them? – geocodezip Feb 08 '20 at 15:30
  • @geocodezip I want to store them an array that contains each coordinate set of each drawn polygon, in a format of ["lat": numberLat, "lng": numberLng]. This would be stored in my database, and then create all those polygons on a map for users, as a "product shipping areas" –  Feb 08 '20 at 15:35
  • 1
    Possibly related question: [Google Maps: Applying Event Listeners](https://stackoverflow.com/questions/41434197/google-maps-applying-event-listeners) – geocodezip Feb 08 '20 at 16:58
  • 1
    I get a javascript error with the posted code: `Uncaught ReferenceError: single_coordenadas is not defined` – geocodezip Feb 08 '20 at 17:00
  • 1
    Possibly related question: [Get Array of all points of Polygon - Google Maps Drawing Tool API-3](https://stackoverflow.com/questions/30670080/get-array-of-all-points-of-polygon-google-maps-drawing-tool-api-3) – geocodezip Feb 08 '20 at 17:02
  • @geocodezip thanks for your help. The first link you shared helped me solve the problem. I will now post an answer –  Feb 08 '20 at 18:00

1 Answers1

0

After @geocodezip helped me with your comments, I resolved it as follows

var geocoder;
var map;
var polygons = [];

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: -34.397,
      lng: 150.644
    },
    zoom: 8
  });

  var drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.POLYGON,
    drawingControl: true,
    drawingControlOptions: {
      position: google.maps.ControlPosition.TOP_CENTER,
      drawingModes: ['polygon']
    },
  });
  drawingManager.setMap(map);

  var shapeID = 1;

  google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
    drawingManager.setDrawingMode(null);

    polygon.setOptions({
      id: shapeID,
      editable: true,
      draggable: true
    });
    
    polygons.push({"id_polygon": shapeID,
                   "coord": polygon.getPath().getArray().toString()});
    
    google.maps.event.addListener(polygon.getPath(), "insert_at", getPath);
    google.maps.event.addListener(polygon.getPath(), "remove_at", getPath);
    google.maps.event.addListener(polygon.getPath(), "set_at", getPath);

    function getPath() {
      
      for (let i = 0; i < polygons.length; i++) {
         if(polygon.id == polygons[i]['id_polygon']){
           polygons[i]['coord'] = polygon.getPath().getArray().toString();
           break;
         }
      }
      
      console.log(polygons);
      
    }

    shapeID++;
  });
}


google.maps.event.addDomListener(window, "load", initMap);
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<script src="http://maps.google.com/maps/api/js?libraries=drawing"></script>
<div id="map"></div>