Saltar al contenido

cómo agregar marcadores con OpenLayers 3

Este team de expertos pasados muchos días de investigación y recopilación de de información, obtuvimos la respuesta, queremos que todo este artículo sea de utilidad en tu proyecto.

Solución:

Q1. Los marcadores se consideran obsoletos en OpenLayers 2, aunque esto no es muy obvio en la documentación. En su lugar, debe usar un OpenLayers.Feature.Vector con un externalGraphic establecido en alguna fuente de imagen en su estilo. Esta noción se ha trasladado a OpenLayers 3, por lo que no hay una clase de marcador y se hace como en el ejemplo que citó.

Q2. El ol.source.Vector toma un array de características, tenga en cuenta la línea, características: [iconFeature]por lo que crearía un array de funciones de iconos y agregar funciones a eso, por ejemplo:

var iconFeatures=[];

var iconFeature = new ol.Feature(
  geometry: new ol.geom.Point(ol.proj.transform([-72.0704, 46.678], 'EPSG:4326',     
  'EPSG:3857')),
  name: 'Null Island',
  population: 4000,
  rainfall: 500
);

var iconFeature1 = new ol.Feature(
  geometry: new ol.geom.Point(ol.proj.transform([-73.1234, 45.678], 'EPSG:4326',     
  'EPSG:3857')),
  name: 'Null Island Two',
  population: 4001,
  rainfall: 501
);

iconFeatures.push(iconFeature);
iconFeatures.push(iconFeature1);

var vectorSource = new ol.source.Vector(
  features: iconFeatures //add an array of features
);

var iconStyle = new ol.style.Style(
  image: new ol.style.Icon(/** @type olx.style.IconOptions */ (
    anchor: [0.5, 46],
    anchorXUnits: 'fraction',
    anchorYUnits: 'pixels',
    opacity: 0.75,
    src: 'data/icon.png'
  ))
);


var vectorLayer = new ol.layer.Vector(
  source: vectorSource,
  style: iconStyle
);

Obviamente, esto podría manejarse de manera más elegante colocando toda la creación de ol.Feature dentro de un bucle basado en alguna fuente de datos, pero espero que esto demuestre el enfoque. Tenga en cuenta, también, que puede aplicar un estilo a ol.layer.Vector para que se aplique a todas las funciones que se agregan a la capa, en lugar de tener que establecer el estilo en funciones individuales, asumiendo que desea que sean las igual, obviamente.

EDITAR: Esa respuesta no parece funcionar. Aquí hay un violín actualizado que funciona agregando las características (iconos) a la fuente de vector vacía en un bucle, usando vectorSource.addFeature y luego agrega todo al vector de capa después. Esperaré y veré si esto funciona para usted, antes de actualizar mi respuesta original.

hay un buen tutorial en: http://openlayersbook.github.io

no probado pero puede ser útil

var features = [];

//iterate through array...
for( var i = 0 ; i < data.length ; i++)
    var item = data[i];                                     //get item
    var type = item.type;                                   //get type
    var longitude = item.longitude;                         //coordinates
    var latitude = item.latitude;
    /*....
    * now get your specific icon...('..../ic_customMarker.png')
    * by e.g. switch case...
    */
    var iconPath = getIconPath(type);

    //create Feature... with coordinates
    var iconFeature = new ol.Feature(
        geometry: new ol.geom.Point(ol.proj.transform([longitude, latitude], 'EPSG:4326',     
        'EPSG:3857'))
    );

    //create style for your feature...
    var iconStyle = new ol.style.Style(
        image: new ol.style.Icon(/** @type olx.style.IconOptions */ (
        anchor: [0.5, 46],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        opacity: 0.75,
        src: iconPath
        ))
    );

    iconFeature.setStyle(iconStyle);
    features.push(iconFeature);
    //next item...


/*
* create vector source
* you could set the style for all features in your vectoreSource as well
*/
var vectorSource = new ol.source.Vector(
    features: features      //add an array of features
    //,style: iconStyle     //to set the style for all your features...
);

var vectorLayer = new ol.layer.Vector(
    source: vectorSource
);
map.addLayer(vectorLayer);

Reseñas y calificaciones

Nos puedes favorecer nuestro análisis ejecutando un comentario y dejando una puntuación te estamos eternamente agradecidos.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *