Search code examples
javascriptopenlayers

What is wrong with my OpenLayers Vector layer?


I want to create an OpenLayers map with 2 layers:

  1. The actual map.
  2. A red dot, which marks the center of the city.

I wrote following code:

function createView() {
    return new ol.View({
        center: ol.proj.transform([132.183333, 43.35], 'EPSG:4326', 'EPSG:3857'),
        zoom: 13
    });
}
function createMapLayer() {
    return new ol.layer.Tile({
        source: new ol.source.MapQuest({layer: 'osm'}),
        visibility: true
    });
}

function createCenterOfCityLayer() {
    var coordinates = [132.183333, 43.35];
    var features = new Array(1);

    features[0] = new ol.Feature(new ol.geom.Point(coordinates));

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

    var style = [new ol.style.Circle({
        radius: 100,
        stroke: new ol.style.Stroke({
            color: 'red'
        }),
        fill: new ol.style.Fill({
            color: 'red'
        })
    })];

    var layer = new ol.layer.Vector({
        source: source,
        style: style
    });

    return layer;
}

function createMap() {
    return new ol.Map({
        target: 'map',
        layers: [
            createMapLayer(),
            createCenterOfCityLayer()
        ],
        view: createView()
    });
}
(function(){
    var app = angular.module('city-editor', [  ]);

    app.controller('CityEditorController', function(){
        this.map = createMap();
    });
})();

The first layer (actual map) is created inside the createMapLayer function, the red dot layer - in createCenterOfCityLayer. But when I open the web page, no red dot is displayed at the center of the view.

You can find the entire source code here.

What is wrong with my code (how can I change it so that the red dot is displayed at point [132.183333, 43.35]) ?


Solution

  • The vector data must be in the same projection of your view, so you must translate your vector coordinates too from EPSG:4326 to EPSG:3857.

    Another options, instead make the transform by hand is to use the projection property within the vector source.

    Cheers.