如何获取已编辑多边形的 ID

how to get id of the edited polygon

<script type="text/javascript">
    var map;
    var sampArr = [];


    function initMap() {
        let coordinates = [];
        let getCoordinates = localStorage.getItem("polygons");
        if (typeof getCoordinates == 'string') {
            coordinates = JSON.parse(getCoordinates);
        }
        let polygonPoints = coordinates.map((item) => item.coord)

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(success, error);
        } else {
            alert('location not supported');
        }

        function error(msg) {
            alert('error in geolocation');
        }

        function success(position) {
            var lats = position.coords.latitude;
            var lngs = position.coords.longitude;
            map = new google.maps.Map(document.getElementById("map"), {
                center: {
                    lat: lats,
                    lng: lngs
                },
                zoom: 12,
            });
            marker = new google.maps.Marker({
                position: {
                    lat: lats,
                    lng: lngs
                },
                map,
                title: "my location",
            });
            // To initialize existing poygon on map.

            for (var items of coordinates) {

                var newShape = new google.maps.Polygon({
                    id: items.id_polygon,
                    paths: items.coord,
                    strokeColor: "#FF0000",
                    strokeOpacity: 0.8,
                    strokeWeight: 3,
                    fillColor: "#FF0000",
                    fillOpacity: 0.35,
                    editable: true,
                });
                sampArr.push(newShape);
                sampArr[sampArr.length - 1].setMap(map);

                //Listen to changes made in existing  polygon  and update them localy.

                sampArr[sampArr.length - 1].getPaths().forEach(function(path, index) {
                    google.maps.event.addListener(path, 'insert_at', function() {
                        console.log('insert_at event', sampArr[sampArr.length - 1].id);
                    });
                    google.maps.event.addListener(path, 'remove_at', function() {
                        console.log('remove_at event',sampArr[sampArr.length - 1].id);

                    });
                    google.maps.event.addListener(path, 'set_at', function() {
                        console.log('set_at event',sampArr[sampArr.length - 1].id);

                    });
                });

            }

        }
    }
    google.maps.event.addDomListener(window, "load", initMap);
</script> 

我试图在编辑后识别多边形的 ID。我安慰了 addListener 中的值,但始终获取所有多边形的最后一个 ID。例如:如果地图上有 5 个多边形,编辑后所有多边形的多边形 ID 将为 5 google map developer site>

如果我没记错的话,您需要自己分配 ID 属性。

用记号笔就可以了

         let marker = new google.maps.Marker({
                _id : 12345,
                position: {
                    lat: lats,
                    lng: lngs
                },
                map,
                title: "my location",
            });

正如您对多边形所做的那样,您可能需要对自定义属性使用 _,因为它们可能会被覆盖。

              var shape = new google.maps.Polygon({
                    _id: items.id_polygon,
                    paths: items.coord,
                    strokeColor: "#FF0000",
                    strokeOpacity: 0.8,
                    strokeWeight: 3,
                    fillColor: "#FF0000",
                    fillOpacity: 0.35,
                    editable: true,
                });

您正在使用 sampArr[sampArr.length - 1].id 作为 ID。这将(在添加所有多边形之后)始终是最后一个多边形。最简单的“现代”方法是在 forEach 函数的范围内定义一个变量来保存多边形 ID(使用 let):

sampArr[sampArr.length - 1].getPaths().forEach(function(path, index) {
  let polyId = sampArr[sampArr.length - 1].id;
  google.maps.event.addListener(path, 'insert_at', function() {
    console.log('insert_at event', polyId);
  });
  google.maps.event.addListener(path, 'remove_at', function() {
    console.log('remove_at event', polyId);
  });
  google.maps.event.addListener(path, 'set_at', function() {
    console.log('set_at event', polyId);
  });
});

proof of concept fiddle

代码片段:

var map;
var sampArr = [];
var defaultPosition = {
  coords: {
    latitude: 40.7127753,
    longitude: -74.0059728
  }
}

function initMap() {
  let coordinates = [];
  // let getCoordinates = localStorage.getItem("polygons");
  // if (typeof getCoordinates == 'string') {
  //  coordinates = JSON.parse(getCoordinates);
  // }
  let polygonPoints = coordinates.map((item) => item.coord)

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(success, error);
  } else {
    console.log('location not supported');
    success(defaultPosition);
  }

  function error(msg) {
    console.log('error in geolocation:' + msg.code + " " + msg.message);
    success(defaultPosition);
  }

  function success(position) {
    var lats = position.coords.latitude;
    var lngs = position.coords.longitude;
    map = new google.maps.Map(document.getElementById("map"), {
      center: {
        lat: lats,
        lng: lngs
      },
      zoom: 10,
    });
    marker = new google.maps.Marker({
      position: {
        lat: lats,
        lng: lngs
      },
      map,
      title: "my location",
    });
    // To initialize existing poygon on map.
    var coordinates = [{
        id_polygon: 1,
        coord: [{
          lat: 40.626321,
          lng: -74.184501
        }, {
          lat: 40.637785,
          lng: -74.08837
        }, {
          lat: 40.600259,
          lng: -74.071891
        }, {
          lat: 40.519923,
          lng: -74.214713
        }, {
          lat: 40.626321,
          lng: -74.184501
        }]
      },
      {
        id_polygon: 2,
        coord: [{
          lat: 40.627364,
          lng: -74.022652
        }, {
          lat: 40.768619,
          lng: -73.904549
        }, {
          lat: 40.671823,
          lng: -73.837257
        }, {
          lat: 40.592616,
          lng: -73.962227
        }]
      }
    ]
    for (var items of coordinates) {

      var newShape = new google.maps.Polygon({
        id: items.id_polygon,
        paths: items.coord,
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 3,
        fillColor: "#FF0000",
        fillOpacity: 0.35,
        editable: true,
        map: map
      });
      sampArr.push(newShape);
      sampArr[sampArr.length - 1].setMap(map);

      //Listen to changes made in existing  polygon  and update them localy.

      sampArr[sampArr.length - 1].getPaths().forEach(function(path, index) {
        let polyId = sampArr[sampArr.length - 1].id;
        google.maps.event.addListener(path, 'insert_at', function() {
          console.log('insert_at event', polyId);
        });
        google.maps.event.addListener(path, 'remove_at', function() {
          console.log('remove_at event', polyId);
        });
        google.maps.event.addListener(path, 'set_at', function() {
          console.log('set_at event', polyId);
        });
      });

    }

  }
}
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;
}
<!DOCTYPE html>
<html>

<head>
  <title>Drawing Polygons</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=drawing"></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <div id="map"></div>
</body>

</html>