How do I get a Graphic from the Graphic Layer like the way one can implement in OpenLayers using getFeatureById()?

Presently, I am attaching attributes to graphic and then by getting graphic layer by layerId, I loop through all the graphics in that layer until the loop satisfy the condition and returns me the correct Graphic I am looking for.

So it works in following way,

`//This returns graphics layer from the list of graphics layer
var graphicsLayer = map.getLayer(layerId);
//Not supported by API
//var graphic = graphicsLayer.getGraphic(graphicId);`

`//Current approach
    if(graphisLayer.graphics[i].attribute.fid == myFid){
        //Do something with this graphic

However, I am seeking another approach.

  • You could probably use something like this graphicsLayer.graphics.filter(g=>{g.attributes.fid===myFid}). Not necessarily better, or faster, but at least shorter. BTW, I wonder if speed is really an issue here. If you have, say, 1000 graphics, looping over that array shouldn't take very long. If you have (much) more graphics, you'll probably experience other issues, such as the actual drawing of those graphics.
    – Berend
    Commented Aug 16, 2016 at 12:40
  • @Berend thanks for your solution, will try this one. Also in case of my app there is no formal limit on graphics those will be added on map. So it can be 1k or can be 50k. Hence i was looking for some method directly from API instead of manual looping.
    – Suraj
    Commented Aug 17, 2016 at 5:15
  • Depending on how frequently you add/remove or clear the graphicsLayer, one approach could be to maintain an object (ex. graphicsLayerObj) with the keys as graphic ID's (ex. graphic_id) and the value as the corresponding graphic. Just call it as when needed as graphicsLayerObj[graphic_id]. Commented Sep 12, 2016 at 21:26

1 Answer 1


Use Array's find function : by declaring a function where you'll make your search and create property in your layer refering the last created function :

here is the code

var getGraphics = function (myFid){
    function findGraphic(graphic) {
       if(typeof  graphic.attribute == 'undefined') return "";
       return graphic.attribute.fid == myFid;
    return this.graphics.find(findGraphic);

//assigning new member as function 
graphicsLayer.getGraphic = getGraphics ;

// perform serach
var graphic = graphicsLayer.getGraphic(graphicId);

Hope this help you .


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.