如何更新地图状态

时间:2019-05-27 17:16:35

标签: javascript arrays google-maps google-maps-api-3 google-maps-markers

我试图在单击地图时创建一个多边形,每次将新的LatLng对象添加到数组时,都将其分配给Polygon对象,但是我意识到该多边形也保存了较旧的值,并且不会仅得到新创建的数组的值。分配新更新的数组后,如何重新渲染多边形。

        function add_point(map, location) {
           upcoming_point = {lat: location.lat(), lng:location.lng() }
           poligon_array.push(upcoming_point)

           if(polygon_array.length>5){
             polygon_array.shift();
           }
           create_Polygon(polygon_array);
         }

         function create_Polygon(polygon_array) {
             var Polygon = new google.maps.Polygon({
                 paths: polygon_array,
                 strokeColor: '#FF0000',
                 strokeOpacity: 0.8,
                 strokeWeight: 2,
                 fillColor: '#FF0000',
                 fillOpacity: 0.35
               });
              Polygon.setMap(map);

          }

1 个答案:

答案 0 :(得分:0)

Polygon.setPath(newArrayOfPoints)将更新多边形。

var polygon;

function add_point(map, location) {
  upcoming_point = {lat: location.lat(), lng:location.lng() }
  poligon_array.push(upcoming_point)

  if(polygon_array.length > 5){
    polygon_array.shift();
  }
  if (polygon) {
    polygon.setPath(polygon_array);
  } else {
    polygon = create_Polygon(polygon_array);
  }
}

function create_Polygon(polygon_array) {
  var Polygon = new google.maps.Polygon({
    paths: polygon_array,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });
  Polygon.setMap(map);
  return Polygon;
}