在Google Maps API中为所有内容添加新多边形

时间:2015-10-19 22:28:00

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

我有一个Google.Map对象,其上显示了一组多边形和折线已经

我想添加一个 google.maps.Polygon对象,该对象应显示在下面所有元素(或多或少像"背景"多边形)。

我尝试使用荒谬的低zIndex值(-999999)添加它,但它仍然显示高于所有其他元素。

这是我到目前为止所做的:

            whiteBackground = new google.maps.Polygon({
                path: [ {lat:40.1, lng:-97.1},
                        {lat:40.1, lng:-89.8},
                        {lat:44.5, lng:-89.8},
                        {lat:44.5, lng:-97.1} ],
                strokeColor: "#FF0000",
                fillColor: "#FFFFFF",
                strokeOpacity: 1.0,
                strokeWeight: 1.5,
                fillOpacity: 1.0, 
                zIndex: -999999
            });

            // add to map and to list
            whiteBackground.setMap(my_map);

有没有办法强制新的多边形 whiteBackground 在Google.Map中添加最小 zIndex值?

或者有一种方法可以迭代 Google.Map对象中的所有当前元素?

1 个答案:

答案 0 :(得分:0)

如果您设置所有多边形的zIndex属性,则此方法有效。

proof of concept fiddle (moves smaller polygon above/below larger polygon on click of the button)

代码段



// This example creates a simple polygon representing the Bermuda Triangle and a small polygon that starts above it, toggles above/below by clicking the button (large polygon has zIndex=0; small polygon is +/-1.

var map;
var infoWindow;
var poly2;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 5,
    center: {
      lat: 24.886,
      lng: -70.268
    },
    mapTypeId: google.maps.MapTypeId.TERRAIN
  });
  // Define the LatLng coordinates for the polygon.
  var triangleCoords = [{
    lat: 25.774,
    lng: -80.190
  }, {
    lat: 18.466,
    lng: -66.118
  }, {
    lat: 32.321,
    lng: -64.757
  }];

  // Construct the polygon.
  var bermudaTriangle = new google.maps.Polygon({
    paths: triangleCoords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 3,
    fillColor: '#FF0000',
    fillOpacity: 0.35,
    zIndex: 0
  });
  bermudaTriangle.setMap(map);

  var poly2Coords = [{
    lat: 26.78484736105119,
    lng: -72.24609375
  }, {
    lat: 27.059125784374068,
    lng: -68.8623046875
  }, {
    lat: 23.926013339487024,
    lng: -71.806640625
  }];

  poly2 = new google.maps.Polygon({
    paths: poly2Coords,
    strokeColor: '#0000FF',
    strokeOpacity: 0.8,
    strokeWeight: 3,
    fillColor: '#FF0000',
    fillOpacity: 0.35,
    zIndex: 1
  });
  poly2.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initMap);

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
}

<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="info"></div>
<input id="btn" type="button" value="click" onclick="if (poly2.get('zIndex') > 0) poly2.setOptions({zIndex:-1}); else poly2.setOptions({zIndex:1});" />
<div id="map"></div>
&#13;
&#13;
&#13;