2015-09-21 82 views
2

ol.interaction.Draw具有Point,LineString,Polygon,MultiPoint,MultiLineString,MultiPolygon和Circle作爲類型選項。我無法弄清楚的是如何真正繪製例如一個包含幾個單個多邊形的MultiPolygon。 Here's a demo控制檯記錄一個有效的GeoJSON字符串,但只包含一個單一的多邊形。如何在OpenLayers 3中繪製多部分幾何圖形?

相關代碼:

// create draw interaction and add it to the map: 
drawInteraction = new ol.interaction.Draw({ source:vectorSource, type:"MultiPolygon" }); 
map.addInteraction(drawInteraction); 

// define GeoJSON format: 
var formatGeoJSON = new ol.format.GeoJSON(); 

// set listener on "drawend": 
drawInteraction.on("drawend", function(e) { 
    // get feature: 
    var feature = e.feature; 
    // clone feature: 
    var featureClone = feature.clone(); 
    // transform cloned feature to WGS84: 
    featureClone.getGeometry().transform('EPSG:3857', 'EPSG:4326'); 
    // get GeoJSON of feature: 
    var geojson = formatGeoJSON.writeFeature(featureClone); 
    // log: 
    console.log(geojson); 
}); 
+0

您將要覆蓋'VAR geojson'而不是推一個新的多邊形。 –

+0

好的,我明白了!我嘗試過'features.push(featureClone)'和'var geojson = formatGeoJSON.writeFeatures(features);'This,hovever,創建一個FeatureCollection。 – Mark

+0

我想你應該使用http://openlayers.org/en/v3.9.0/apidoc/ol.geom.MultiPolygon.html#appendPolygon –

回答

1

我建議你做這樣的事情:

var drawInteraction = new ol.interaction.Draw({ 
    source: vectorSource, 
    type: "Polygon" 
}); 
map.addInteraction(drawInteraction); 

var multiPolygon = new ol.geom.MultiPolygon([]); 
drawInteraction.on('drawend', function(e) { 
    var 
     feature = e.feature, 
     poly = feature.getGeometry() 
    ; 
    multiPolygon.appendPolygon(poly); 
    updateGeojson(); 
}); 
function updateGeojson(){ 
    var 
     formatGeoJSON = new ol.format.GeoJSON(), 
     cloned = multiPolygon.clone() 
    ; 
    cloned.transform('EPSG:3857', 'EPSG:4326'); 
    var geojson = formatGeoJSON.writeGeometry(cloned); 
    console.info(geojson); 
} 

https://jsfiddle.net/jonataswalker/epyuLy7x/

+0

謝謝Jonatas!我仍然想知道「ol.interaction.Draw」是如何用於「MultiPolygon」類型的。但這是一個很好的工作解決方案! – Mark