将事件点击添加到标记openlayers

时间:2017-12-05 21:25:18

标签: javascript openlayers

美好的一天,我试图在地图上为动态编程的标记添加事件。标记显示在屏幕上,但是当您单击以显示div时,而不是仅显示与书签相关的div,请激活事件,单击屏幕上的所有div。

创建标记的位置是调用函数crearMarcadores并发送坐标和变量cc以用于div的id。

@user.picture.path

div如果你正确创建它们,据我所知它必须是每个标记的div。

我几乎可以肯定的是我的错误在于:

var centro = ol.extent.getCenter(boundingBox);
crearMarcadores(centro, cc);

由于它执行foreach,并且只应返回标记功能。但我不知道如何只在当前标记中运行它。虽然我发现的所有例子都与foreach有关。

非常感谢你的宝贵帮助。



  var feature = map.forEachFeatureAtPixel(evt.pixel,
        function(feature, layer) {
            return feature;
  });

    var iconFeature = new ol.Feature({
   	    geometry: new ol.geom.Point([-90.204114, 13.866291]),
   	    name: 'nombre',
   	    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: 'http://openlayers.org/en/v3.9.0/examples/data/icon.png'
   	    }))
    });
    iconFeature.setStyle(iconStyle);

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

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

    var layer = new ol.layer.Vector({ /*layer con los poligonos*/
   	    source: new ol.source.Vector()
    })

    function crearMarcadores(centroPoligono, CentroCosto) {

   	    var iconFeature = new ol.Feature({
   		    geometry: new ol.geom.Point(centroPoligono),
   		    name: CentroCosto,
   		    population: 4000,
   		    rainfall: 500
   	    });
   	    vectorSource.addFeature(iconFeature);
   	    iconFeature.setStyle(iconStyle);

   	    //------------start creation popup
   	    var div = document.createElement('div');
   	    div.setAttribute("id", CentroCosto);
   	    div.setAttribute("style", "width: 580px; height: 400px; float: left");
   	    document.body.appendChild(div);

   	    var element = document.getElementById(CentroCosto);

   	    var popup = new ol.Overlay({
   		    element: element,
   		    positioning: 'bottom-center',
   		    stopEvent: false
   	    });
   	    map.addOverlay(popup);
   	    //------------end creation popup

   	    // --------------display popup on click
   	    map.on('click', function(evt) {
   		
   		var feature = map.forEachFeatureAtPixel(evt.pixel,
   			function(feature, layer) {
   				return feature;
   			});
   		if (feature) {
   			var geometry = feature.getGeometry();
   			var coord = geometry.getCoordinates();
   			popup.setPosition(coord);
   			$(element).popover({
   				'placement': 'top',
   				'html': true,
   				'content': feature.get('name')
   			});
   			$(element).popover('show');
   		} else {
   			$(element).popover('destroy');
   		}
   	    });
   	//---------------end display popup on click

   	
    } //termina funcion crearMarcadores

    function generarMapas() {

   	var FechaInicial = '';
   	var FechaFinal = '';
   	var Finca = '';
   	$.ajax({
   		type: "POST",
   		url: "FrmMapaAvanceRiego.aspx\/FillMapas",
   		data: '{FechaInicial: "' + FechaInicial + '", FechaFinal: "' + FechaFinal + '", Finca: "' + Finca + '"}',
   		contentType: "application/json; charset=utf-8",
   		dataType: "json",
   		success: function(msg) {
   			var data = JSON.parse(msg.d);
   			coordenadas = [];
   			cc = [];
   			$.each(data, function(i, item) {
   				coordenadas[i] = item.Coordenadas;
   				cc[i] = item.CentroDeCostoLote;
   				crearPoligonos(coordenadas[i], cc[i]);

   			});
   		},
   		error: errores
   	});
    }

    function errores(msg) {
   	 alert('Error: ' + msg.responseText);
    }

    function crearPoligonos(coordenada, cc) {
   	//console.log(coordenada);
   	console.log(cc);
   	var coordenadas = coordenada.split(' ') // Separamos por espacio
   		.map(function(data) {
   			var info = data.split(','), // Separamos por coma
   				coord = { // Creamos el obj de coordenada
   					lat: parseFloat(info[1]),
   					lng: parseFloat(info[0])
   				};

   			return coord;
   		});

   	var parserJSTS = new jsts.io.OL3Parser();

   	var poly = new ol.Feature({
   		geometry: new ol.geom.Polygon([coordenadas.map(function(_ref) {
   			var lng = _ref.lng,
   				lat = _ref.lat;
   			return [lng, lat];
   		})])
   	});

   	var boundingBox = poly.getGeometry().getExtent()
   	var polybbox = new ol.Feature({
   		geometry: ol.geom.Polygon.fromExtent(boundingBox)
   	})

   	var [xmin, ymin, xmax, ymax] = boundingBox

   	var porcentaje = 0.50
   	var newXmax = xmin + ((xmax - xmin) * porcentaje)

   	var newBoundingBox = [xmin, ymin, newXmax, ymax]

   	var polybbox50 = new ol.Feature({
   		geometry: ol.geom.Polygon.fromExtent(newBoundingBox)
   	})

   	var polybbox50jsts = parserJSTS.read(polybbox50.getGeometry())

   	var polyjsts = parserJSTS.read(poly.getGeometry())

   	var intersectionJSTSGeometry = polyjsts.intersection(polybbox50jsts)

   	var intersectionGeometry = parserJSTS.write(intersectionJSTSGeometry)

   	var newPoly = new ol.Feature({
   		geometry: intersectionGeometry
   	})
   	//console.log(boundingBox)

   	newPoly.setStyle(new ol.style.Style({
   		fill: new ol.style.Fill({
   			color: '#02ABFF'
   		})
   	}))

   	// Descomentar para ver los bounding boxes
   	//      layer.getSource().addFeature(polybbox)
   	//      layer.getSource().addFeature(polybbox50)
   	layer.getSource().addFeature(poly)
   	layer.getSource().addFeature(newPoly)


   	var centro = ol.extent.getCenter(boundingBox);
   	//console.log(centro);

   	crearMarcadores(centro, cc);
    }

    //------------start creation map
    var map = new ol.Map({
   	layers: [
   		new ol.layer.Tile({
   			source: new ol.source.BingMaps({
   				key: 
    'AudCyoI6al0eAZmQhwmI1IG9AOdGH8DHHk6PsiGta1faEACulxawFU9KV-XAvZ8f',
   				imagerySet: 'AerialWithLabels'
   			})
   		}),
   		layer, vectorLayer
   	],
   	target: 'map',
   	controls: ol.control.defaults({
   		attributionOptions: ({
   			collapsible: false
   		})
   	}),
   	view: new ol.View({
   		center: [-90.365730, 13.954185],
   		zoom: 9,
   		projection: 'EPSG:4326'
   	})
    });
    // --------------end creation map




1 个答案:

答案 0 :(得分:2)

forEachFeatureAtPixelapi doc)会浏览该位置的每个的所有功能。因此,您可能会从其他图层中获得意外结果。

但是该功能还允许您定义一个layerFilter,它决定是否要包含图层。

示例:

map.addLayer(new ol.layer.Vector({
  source: vectorSource1,
  myKey: 'magic' // arbitrary property to distinguish between the layers
});

map.addLayer(new ol.layer.Vector({
  source: vectorSource2,
  myKey: 'someotherlayer'
});

// this only gives back the first feature at this position
// on the layer with the property `myKey` equal to `'magic'`
const feature = map.forEachFeatureAtPixel(
  pixel,
  function(someFeature){ return someFeature; }, // stop at the very first feature
  {
    layerFilter: function(layer) { return layer.get('myKey') === 'magic'; }
  }
);