如何分离多边形?

时间:2015-09-05 20:51:27

标签: javascript html google-maps polygons

这是我的代码(javascript + HTML),

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Simple Polygon</title>
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
    </style>
  </head>
  <body>
<p id="demo"></p>
    <div id="map"></div>
    <script>



function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
     zoom: 12,
    center: {lat: 33.53625, lng: -111.92674},
    mapTypeId: google.maps.MapTypeId.TERRAIN
  });
var str = "33.53625,-111.92674,33.51049,-111.96279,33.50141,-111.90374;33.53424,-111.82674,33.50944,-111.86279,33.50174,-111.80374";
    var mainstr = str.split(";");
    var mainlen = mainstr.length; 
    var newdata;
    var newsplit;
    var newstrlen;
    var halflen;
    var bermudaTriangle=[];
    var triangleCoords = [];


for (i = 0; i < 2; i++) 
{
newdata=mainstr[i];
newsplit=newdata.split(",");
newstrlen=newsplit.length;
halflen=newstrlen/2;

for (x = 0; x < halflen; x++) {
    n = 2 * x; 
    h = 2 * x + 1;
  triangleCoords.push({ lat: parseFloat(newsplit[n],10), lng: parseFloat(newsplit[h],10) });

}

 bermudaTriangle = new google.maps.Polygon({
    paths: triangleCoords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35

  });
  bermudaTriangle.setMap(map);


}


}

    </script>
    <script async defer
        src="https://maps.googleapis.com/maps/api/js?signed_in=true&callback=initMap"></script>
  </body>
</html>

var str 中有两组三角形坐标,它们由“;”分开,我能够分开这两组绳索,但我无法单独绘制两个三角形。当我在没有循环的情况下单独运行代码时,我能够得到这个,http://postimg.org/image/hjnyu5uxf/

但是当我跑到程序之上时,我得到了这个,http://postimg.org/image/djlf1vdmv/

该程序认为它是一个单一的多边形,我哪里做错了?

1 个答案:

答案 0 :(得分:0)

var triangleCoords = []; 放在第一个for循环中。

for (i = 0; i < 2; i++) 
{
var triangleCoords = [];
newdata=mainstr[i];
newsplit=newdata.split(",");
newstrlen=newsplit.length;
halflen=newstrlen/2;
for (x = 0; x < halflen; x++) {
    n = 2 * x; 
    h = 2 * x + 1;
  triangleCoords.push({ lat: parseFloat(newsplit[n],10), lng: parseFloat(newsplit[h],10) });

}

 bermudaTriangle = new google.maps.Polygon({
    paths: triangleCoords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35

  });
  bermudaTriangle.setMap(map);


}