developer tip

OpenLayers 3으로 마커를 추가하는 방법

optionbox 2020. 11. 28. 09:08
반응형

OpenLayers 3으로 마커를 추가하는 방법


OpenLayers 3지도 에 제작자를 추가하려고합니다 .

내가 찾은 유일한 예는 하나의 OpenLayers예를 들어 목록 .

그러나 예를 들어, 사용은 ol.Style.Icon 대신 같은 뭔가 OpenLayers.Marker 에서 OpenLayers 2.

첫 번째 질문

유일한 차이점은 이미지 URL을 설정해야하지만 마커를 추가하는 유일한 방법입니까?

또한 OpenLayers 3마커 이미지와 함께 제공되지 않는 것 같으므로 다른 방법이 없다면 의미가 있습니다.ol.Style.Icon

두 번째 질문

지도가로드 된 후 마커 나 아이콘을 추가하는 기능의 예를 누군가 제게 줄 수 있다면 정말 좋을 것입니다.

예제에서 이해 한 바에 따르면 아이콘에 대한 레이어를 만듭니다.

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 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'
  }))
});

iconFeature.setStyle(iconStyle);

var vectorSource = new ol.source.Vector({
  features: [iconFeature]
});

var vectorLayer = new ol.layer.Vector({
  source: vectorSource
});

그런 다음지도를 초기화 할 때 아이콘 레이어를 설정합니다.

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

마커를 여러 개 추가하려면 각 마커에 대해 레이어를 하나씩 만들어야합니까?

레이어에 여러 마커를 추가하려면 어떻게해야합니까? 이 부분이 어떻게 생겼는지 모르겠어요

var vectorSource = new ol.source.Vector({
  features: [iconFeature]
});

var vectorLayer = new ol.layer.Vector({
  source: vectorSource
});

감사합니다


Q1. 마커는 OpenLayers 2에서 더 이상 사용되지 않는 것으로 간주되지만 문서에서는 명확하지 않습니다. 대신, 스타일의 일부 이미지 소스로 설정된 externalGraphic이있는 OpenLayers.Feature.Vector를 사용해야합니다. 이 개념은 OpenLayers 3에 적용되었으므로 마커 클래스가 없으며 인용 한 예제와 같이 수행됩니다.

Q2. ol.source.Vector는 기능의 배열을 취합니다. 행, 기능 : [iconFeature]에 유의하십시오. 따라서 아이콘 기능의 배열을 만들고 여기에 기능을 추가합니다. 예 :

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
});

분명히, 이것은 모든 ol.Feature 생성을 일부 데이터 소스를 기반으로 한 루프 안에 넣으면 더 우아하게 처리 될 수 있지만 이것이 접근 방식을 보여주기를 바랍니다. 또한 ol.layer.Vector에 스타일을 적용하여 레이어에 추가되는 모든 기능에 적용 할 수 있습니다. 따라서 개별 기능에 스타일을 설정하지 않아도됩니다. 분명히 동일합니다.

편집 : 그 대답은 작동하지 않는 것 같습니다. 다음은 vectorSource.addFeature를 사용하여 루프의 빈 벡터 소스에 기능 (아이콘)을 추가 한 다음 나중에 레이어 벡터에 전체 로트를 추가하는 방식으로 작동 하는 업데이트 된 바이올린 입니다. 원래 답변을 업데이트하기 전에 이것이 작동하는지 기다릴 것입니다.


http://openlayersbook.github.io에 좋은 튜토리얼이 있습니다.

테스트되지 않았지만 도움이 될 수 있음

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);

var exampleLoc = ol.proj.transform(
    [131.044922, -25.363882], 'EPSG:4326', 'EPSG:3857');

var map = new ol.Map({
  target: 'map',
  renderer: 'canvas',
  view: new ol.View2D({
    projection: 'EPSG:3857',
    zoom: 3,
    center: exampleLoc
  }),
  layers: [
    new ol.layer.Tile({source: new ol.source.MapQuest({layer: 'osm'})})
  ]
});

map.addOverlay(new ol.Overlay({
  position: exampleLoc,
  element: $('<img src="resources/img/marker-blue.png">')
      .css({marginTop: '-200%', marginLeft: '-50%', cursor: 'pointer'})
      .tooltip({title: 'Hello, world!', trigger: 'click'})
}));

map.on('postcompose', function(evt) {
  evt.vectorContext.setFillStrokeStyle(
      new ol.style.Fill({color: 'rgba(255, 0, 0, .1)'}),
      new ol.style.Stroke({color: 'rgba(255, 0, 0, .8)', width: 3}));
  evt.vectorContext.drawCircleGeometry(
      new ol.geom.Circle(exampleLoc, 400000));
});

var exampleKml = new ol.layer.Vector({
  source: new ol.source.KML({
    projection: 'EPSG:3857',
    url: 'data/example.kml'
  })
});
map.addLayer(exampleKml);

참고 URL : https://stackoverflow.com/questions/24315801/how-to-add-markers-with-openlayers-3

반응형