2017-07-21 162 views
0

正如您在下面看到的,我有兩個具有邊的多邊形。基本上2個三角形與他們各自的座標。請參閱:使用Google Maps API合併多邊形

function initialize() { 
 
    // Define the LatLng coordinates for the polygon's path. 
 
    var bounds = new google.maps.LatLngBounds(); 
 
    var i; 
 

 
    var polygonCoords = [ 
 
    new google.maps.LatLng(25.774252, -80.190262), 
 
    new google.maps.LatLng(18.466465, -66.118292), 
 
    new google.maps.LatLng(32.321384, -64.757370) 
 
    ]; 
 
    
 

 
    for (i = 0; i < polygonCoords.length; i++) { 
 
    bounds.extend(polygonCoords[i]); 
 
    } 
 

 
    var map = new google.maps.Map(document.getElementById("map_canvas2"), { 
 
    zoom: 4, 
 
    center: bounds.getCenter(), 
 
    mapTypeId: "roadmap" 
 
    }); 
 

 

 
    var triangle1 = new google.maps.Polygon({ 
 
    paths: polygonCoords, 
 
    strokeColor: '#0000ff', 
 
    strokeOpacity: 0.8, 
 
    strokeWeight: 2, 
 
    fillColor: '#0000ff', 
 
    fillOpacity: 0.35 
 
    }); 
 
    triangle1.setMap(map); 
 
    
 
    var polygonCoords2 = [ 
 
    new google.maps.LatLng(25.774252, -80.190262), 
 
    new google.maps.LatLng(18.466465, -66.118292), 
 
    new google.maps.LatLng(14.979063, -83.500871) 
 
    ]; 
 

 
    var triangule2 = new google.maps.Polygon({ 
 
    paths: polygonCoords2, 
 
    strokeColor: '#0000ff', 
 
    strokeOpacity: 0.8, 
 
    strokeWeight: 2, 
 
    fillColor: '#0000ff', 
 
    fillOpacity: 0.35 
 
    }); 
 
    triangule2.setMap(map); 
 
    
 
}
#map { 
 
    height: 100%; 
 
} 
 

 

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

 
html, 
 
body { 
 
    height: 100%; 
 
    margin: 0; 
 
    padding: 0; 
 
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script> 
 

 
<body onload="initialize()"> 
 
    <div id="map_canvas2" style="height: 100vh; width:100vw"></div> 
 
</body>

我想,這樣的風險不會出現在兩者之間的中間,從而使多邊形與4個邊或4個座標合併兩個三角形。什麼是最好的方法來做到這一點?

+0

更換paths: polygonCoords,是它預計是到座標被合併爲一個(即在波多黎各和佛羅里達州的點)總是相同的座標只是不同折線的一部分?希望這是有道理的 –

回答

0

也許你可以合併數組並刪除重複?喜歡的東西:

var newPolygon = polygonCoords.concat(polygonCoords2); 

,然後刪除重複的座標(我從this後的代碼):

var sorted_arr = newPolygon.slice().sort(); // You can define the comparing function here. 
            // JS by default uses a crappy string compare. 
            // (we use slice to clone the array so the 
            // original array won't be modified) 
var results = []; 
for (var i = 0; i < newPolygon.length - 1; i++) { 
    if (sorted_arr[i + 1] == sorted_arr[i]) { 
     results.push(sorted_arr[i]); 
    } 
} 

然後用paths: results,

相關問題