2015-08-19 45 views
2

我需要添加一個標記在我的地圖,當我調用該方法addMarker(長,LAT)。 我發現的唯一的例子是this一箇中的OpenLayers示例列表,但它在一個特定的地方僅增加一個標記。如何添加上的OpenLayers標記3捐贈座標

我需要隨時調用我的方法,我需要並傳遞座標(一般的想法是有一個簡單的菜單,用戶可以鍵入長和經度,然後單擊提交按鈕並在上面繪製標記地圖)。

在這個例子中,如果我這樣做是正確,他們創造了一個功能及其風格,然後創建一個層繪製圖標,並初始化使用層地圖。

var iconFeature = new ol.Feature({ 
    geometry: new ol.geom.Point(ol.proj.transform([-72.0704, 46.678], 'EPSG:4326', 'EPSG:3857')), 
    name: 'Null Island', 
    population: 4000, 
    rainfall: 500 
}); 

var iconStyle = new ol.style.Style({ 
    image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({ 
    anchor: [0.5, 46], 
    anchorXUnits: 'fraction', 
    anchorYUnits: 'pixels', 
    opacity: 0.75, 
    src: 'data/icon.png' 
    })) 
}); 

iconFeature.setStyle(iconStyle); 

var vectorSource = new ol.source.Vector({ 
    features: [iconFeature] 
}); 

var vectorLayer = new ol.layer.Vector({ 
    source: vectorSource 
}); 

var map = new ol.Map({ 
    layers: [new ol.layer.Tile({ source: new ol.source.OSM() }), vectorLayer], 
    target: document.getElementById('map'), 
    view: new ol.View2D({ 
    center: [0, 0], 
    zoom: 3 
    }) 
}); 

我相信我能創造一系列的功能,類似的東西(一個例子,我看到here):

var iconFeatures=[]; 

var iconFeature = new ol.Feature({ 
    geometry: new ol.geom.Point(ol.proj.transform([-72.0704, 46.678], 'EPSG:4326',  
    'EPSG:3857')), 
    name: 'Null Island', 
    population: 4000, 
    rainfall: 500 
}); 

var iconFeature1 = new ol.Feature({ 
    geometry: new ol.geom.Point(ol.proj.transform([-73.1234, 45.678], 'EPSG:4326',  
    'EPSG:3857')), 
    name: 'Null Island Two', 
    population: 4001, 
    rainfall: 501 
}); 

iconFeatures.push(iconFeature); 
iconFeatures.push(iconFeature1); 

這裏是我的方法至今:

class map{ 
    private markerFeatures = []; 

    //receive an array of coordinates 
    public addMarkers(markers: Array<Marker>): void { 
     for (var i in markers) { 
      var markFeature = new ol.Feature({ 
       geometry: new ol.geom.Point(ol.proj.transform([markers[i].long, markers[i].lat], 'EPSG:4326',  
       'EPSG:3857')), 
       name: 'Null Island', 
       population: 4000, 
       rainfall: 500 
      }); 

      this.markerFeatures.push(markFeature); 
     }    
    } 
} 

但當我這樣做時沒有發生任何事。

觀測值:我創建的地圖,層和調用的方法。 我使用OL V3.7

+0

代碼的最後這部分.. 。類的一部分...是這個javascript嗎? :-) –

+0

這是打字稿,Jonatas =) –

+0

看看... http://jsfiddle.net/jonataswalker/ckfd9d1L/ –

回答

3

假設你有一個包含矢量源層,你只需要一個步驟添加到您的addMarkers功能:

myVectorSource.addFeatures(markerFeatures); 
+0

這應該被接受! –