Openlayers: Vector Features instead of Markers

max picture max · May 17, 2011 · Viewed 18.2k times · Source

I want to place a symbol o a Map. E.g.

Map Example

So far I have used OpenLayers with OpenLayers.Layer.Markers. The code looks like this:

    map = new OpenLayers.Map('map');
    layer = new OpenLayers.Layer.OSM( "Simple OSM Map");
    map.addLayer(layer);
    map.setCenter(
        new OpenLayers.LonLat({{ location.lon }}, {{ location.lat }}).transform(
            new OpenLayers.Projection("EPSG:4326"),
            map.getProjectionObject()
        ), 15);

   var lonLat = new OpenLayers.LonLat({{ location.lon }}, {{ location.lat }})
             .transform(
               new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
               map.getProjectionObject() // to Spherical Mercator Projection
             );
   var markers = new OpenLayers.Layer.Markers( "Markers" );
   map.addLayer(markers);
   markers.addMarker(new OpenLayers.Marker(lonLat));

This works as excepted and shows the map above. But I can't get it to work with Vectors replacing the last 3 lines with:

     vectors = new OpenLayers.Layer.Vector("Vector Layer");
     vectors.addFeatures([new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonLat))]);
     map.addLayer(vectors);

Is there any special magic needed to use OpenLayers.Feature.Vector?

Answer

aviaron picture aviaron · May 17, 2011

OpenLayers.Geometry.Point receives two coordinates in its constructor and not an OpenLayers.LonLat.

vectors = new OpenLayers.Layer.Vector("Vector Layer");
point = new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat);
vectors.addFeatures([new OpenLayers.Feature.Vector(point)]);
map.addLayer(vectors);