OL3 - geojson

by shriek

HTML

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/ol3/3.9.0/ol.min.css">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/ol3/3.9.0/ol.min.js"></script>
<div id="map"></div>

CSS

html,body,#map { width:100%; height:100%; margin:0; }

JavaScript

var geojsonObject = {
    'type': 'FeatureCollection',
    'crs': {
        'type': 'name',
        'properties': {
            'name': 'EPSG:4326'
        }
    },
    'features': [
        {
            'type': 'Feature',
            'properties': {
            	'any-property': 'feature1'
            },
            'geometry': {
                'type': 'Point',
                'coordinates': [21.54967, 38.70250]
            }
        },
        {
            'type': 'Feature',
            'properties': {
            	'any-property': 'feature2'
            },
            'geometry': {
                'type': 'LineString',
                'coordinates': [
                    [21.54967, 38.70250], [22.54967, 39.70250]
                ]
            }
        }
    ]
};
var styles = {
    'Point': [new ol.style.Style({
        image: new ol.style.Circle({
            fill: new ol.style.Fill({ color: [255,255,255,1] }),
            stroke: new ol.style.Stroke({ color: [0,0,0,1] }),
            radius: 5
        })
    })],
    'LineString': [new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: 'green',
            width: 5
        })
    })]
};
var features = new ol.format.GeoJSON().readFeatures(geojsonObject, {
    featureProjection: 'EPSG:3857'
});
var vectorSource = new ol.source.Vector({
  features: features
});
var vectorLayer = new ol.layer.Vector({
    source: vectorSource,
    style: function(feature, resolution){
        return styles[feature.getGeometry().getType()];
    }
});

var map = new ol.Map({
    target: 'map',
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM({layer: 'sat'})
        }),
        vectorLayer
    ],
    view: new ol.View({
        center: ol.proj.fromLonLat([21.54967, 38.70250]),
        zoom: 5
    })
});
map.on('click', function(evt){
    var feature = map.forEachFeatureAtPixel(
        evt.pixel, function(ft, l) { return ft; }
    );

    if (feature) {
        //you can see...