how to get which lineString is get clicked on click on any parallel line generated from Style geometry in Openlayer

99封情书 提交于 2021-01-28 18:57:48

问题


I have generated parallel lineString on map by using Style geometry options for Single Feature Object in openlayer v5.2 with different-different width stroke after modified the found reference link on http://jsfiddle.net/CPRam/egn1kmc8/.

While using geometry with call function in style function I'm not getting the geometry on single click event for the Style. So for that, I removed call function and given fixed resolution with distance for parallel.

So now on 'singleclick' event, I'm able to get the feature with all style and its geometry. But here inside map.on('singleclick',function(event){})....How to differentiate on which line or geometry get clicked.

I tried click event point intersect with line or not but not got sucess then I understood here the problem is I am clicking on Stroke not on Line because of that on click event pixel point also cannot compare with intersecting to the line or not

Image of single feature with multi geometry style:

image-of-single-Feature-with-multi-geometry-Style

Even I tried turf.js pointToLineDistance() but due to the dynamic width and line coordinate difference not getting right linestring in mine logic.

I google but didn't get any solution to get which style geometry(line) is get clicked on the map. Please for the code see above jsFiddler reference link

Any help to get which lineString is get clicked is through any event.


回答1:


A click is unlikely to exactly intersect any of the linestrings but you can use the getClosestPoint() method on each geometry to find which was closest:

map.on('singleclick',function(event){
  var coordinate = event.coordinate;
  console.log('singleclick');
  var feature = map.forEachFeatureAtPixel(event.pixel, function(feature){return feature});
  if (feature) {
    var closestGeom;
    var closestDistSq = Infinity;
    var resolution = map.getView().getResolution();
    var styles = styleFunction(feature, resolution);
    styles.forEach(function(style){
      var geomFn = style.getGeometryFunction();
      if (geomFn) {
        var geom = geomFn(feature);
      } else {
        var geom = feature.getGeometry();
      }
      var closestPoint = geom.getClosestPoint(coordinate);
      var distSq = Math.pow(closestPoint[0]-coordinate[0],2)+Math.pow(closestPoint[1]-coordinate[1],2);
      if (closestDistSq > distSq) {
        closestDistSq = distSq;
        closestGeom = geom;
      }
    });
    console.log(closestGeom.getCoordinates());
  }
});


来源:https://stackoverflow.com/questions/52237629/how-to-get-which-linestring-is-get-clicked-on-click-on-any-parallel-line-generat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!