2

I was trying different ways to display one country using countries.geojson file, but I unable to display.
I tried like this, but map is not displaying....

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

var vector = new ol.layer.Vector({
    source: new ol.source.Vector({
        format: new ol.format.GeoJSON(),
        url: 'https://raw.githubusercontent.com/openlayers/ol3/6838fdd4c94fe80f1a3c98ca92f84cf1454e232a/examples/data/geojson/countries.geojson'
    }),
    style: function(feature, res){
        if(feature.get("name") == "Germany"){
            return new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: 'red',
                    width: 2
                })
            });
        }
    }
});
1
  • Define yor var vector =... before adding it to the map!
    – Lars
    Commented Jan 13, 2017 at 10:38

1 Answer 1

2

Use a ol.StyleFunction() and get the name (or any other - depending on the source) attribute of the feature. E.g.:

// vector layer
var vector = new ol.layer.Vector({
    source: new ol.source.Vector({
        format: new ol.format.GeoJSON(),
        url: 'https://raw.githubusercontent.com/openlayers/ol3/6838fdd4c94fe80f1a3c98ca92f84cf1454e232a/examples/data/geojson/countries.geojson'
    }),
    style: function(feature, res){
        // replace "Germany" with any country name you would like to display...
        if(feature.get("name") == "Germany"){
            return new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: 'red',
                    width: 2
                })
            });
        }
    }
});

See Demo on JSFiddle

3
  • I was tried but map is not displaying Commented Jan 13, 2017 at 8:41
  • The code is working. Your error should be somewhere else. I added a fiddle.
    – Lars
    Commented Jan 13, 2017 at 10:25
  • Its working..... thank you :) but, I want to display only selected country remaining should be blur or hide from map, do you have any idea about this.... Commented Jan 13, 2017 at 10:40

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.