2016-08-02 893 views
3

我是OpenLayers的新手,很抱歉有一個明顯的(也許是愚蠢的)問題,爲此我找到了解決方案的不同方法,但都沒有成功。嘗試了這一點,並有十幾種不同的建議(here,here,here,here,here)但徒勞無功。如何獲取OpenLayers中繪製框的座標?

基本上,我想將繪製的矩形的座標傳遞給另一個webservice。所以,繪製矩形之後,它應該將我吐出邊框的四個角。

我至今是繪製矩形的基本OL層例如:

var source = new ol.source.Vector({wrapX: false}); 


    vector = new ol.layer.Vector({ 
     source: source, 
     style: new ol.style.Style({ 
      fill: new ol.style.Fill({ 
       color: 'rgba(0, 255, 0, 0.5)' 
      }), 
      stroke: new ol.style.Stroke({ 
       color: '#ffcc33', 
       width: 2 
      }), 
      image: new ol.style.Circle({ 
       radius: 7, 
       fill: new ol.style.Fill({ 
       color: '#ffcc33' 
       }) 
      }) 
     })  
    }); 



    var map = new ol.Map({ 
     target: 'map', 
     layers: [ 
      new ol.layer.Tile({ 
       source: new ol.source.OSM() 
      }), 
      vector 
     ], 
     view: new ol.View({ 
      center: ol.proj.fromLonLat([37.41, 8.82]), 
      zoom: 4 
     }) 
    }); 



    var draw; // global so we can remove it later 
    function addInteraction() 
    { 
     var value = 'Box'; 

     if (value !== 'None') 
     { 
      var geometryFunction, maxPoints; 
      if (value === 'Square') 
      { 
       value = 'Circle'; 
       geometryFunction = ol.interaction.Draw.createRegularPolygon(4); 
      } 
      else if (value === 'Box') 
      { 
       value = 'LineString'; 
       maxPoints = 2; 
       geometryFunction = function(coordinates, geometry) 
       { 
        if (!geometry) 
        { 
         geometry = new ol.geom.Polygon(null); 
        } 
        var start = coordinates[0]; 
        var end = coordinates[1]; 
        geometry.setCoordinates([ 
        [start, [start[0], end[1]], end, [end[0], start[1]], start] 
        ]); 
        return geometry; 
       }; 
      } 

      draw = new ol.interaction.Draw({ 
       source: source, 
       type: /** @type {ol.geom.GeometryType} */ (value), 
       geometryFunction: geometryFunction, 
       maxPoints: maxPoints    
      }); 

      map.addInteraction(draw);    
     } 
    } 


    addInteraction();   

現在,下一步怎麼走?提取邊界框的好方法是什麼?

感謝您的任何提示!

回答

5

您需要爲偵聽交互設置偵聽器。像這樣:

draw.on('drawend',function(e){ 
alert(e.feature.getGeometry().getExtent()); 
}); 

這裏是一個fiddle

+0

偉大啊!非常感謝。然而,有趣的是,小提琴在Safari瀏覽器中工作,但沒有在我的身邊執行 - 另一方面在火狐瀏覽器和Chrome(所有Mac)上都可以工作... – luftikus143

+0

這是一個官方的ol3示例(http:// openlayers。 org/en/latest/examples/draw-features.html),我剛剛添加了監聽器。它真的很奇怪,它不適用於safari。我沒有safari,所以我無法測試它。樂意效勞 – pavlos