2

I have a map that contains one single layer with multiple feature. Those feature contains polygon and point.
I do not filter them because I did load every layout in the same object like the following

geoJsonObject = MyGeoJsonFile

const vectorSource: VectorSource = new VectorSource({
  features: new GeoJSON().readFeatures(geojson),
})

this.vectorLayer = new VectorLayer({
  map: this._map, // Already generated map
  source: vectorSource,
})

Now I try to find the nearest point and move to it while the user is moving
_geolocationService.onUserPositionChanged$ give me the user coordinates {lng: string, lat: string}

moveToCoordinate(coordinates: any[], zoom: number = 16) {
  this.view.animate({ center: olProj.fromLonLat(coordinates), zoom: zoom })
}

this._geolocationService.onUserPositionChanged$
  .pipe(takeUntil(this._unsubscribeAll))
  .subscribe((coordinates) => {
    if (coordinates) {
      const formattedCoordinates = [coordinates.lng, coordinates.lat]
      const fromLonLatCoordinates = olProj.fromLonLat(formattedCoordinates)

      this.positionFeature.setGeometry(coordinates ? new Point(fromLonLatCoordinates) : null)

      const nearestPoint: Feature = this.vectorLayer
        ?.getSource()
        .getClosestFeatureToCoordinate(fromLonLatCoordinates)

      if (nearestPoint) {
        this.moveToCoordinate(nearestPoint.getGeometry().getCoordinates(), 18)
      }
    }
  })

But nearestPoint will give me back the coordinate of the polyline instead of the point.
I know that getClosestFeatureToCoordinate() does accept a filter but I cannot figure out how to make it work.

2 Answers 2

4

In your filter function you can check feature geometry type and return true if geometry is Point:

function featureFilter(feature) {
  return(feature.getGeometry().getType() == 'Point');
}
0
0

In case someone want to copy my code for centering to a specific location, I'll also had to change the projection like this. and I did write a shorter form of the method.

const nearestPoint: Feature = this.vectorLayer
  ?.getSource()
  .getClosestFeatureToCoordinate(fromLonLatCoordinates, (feature) => {
    return feature.getGeometry().getType() == 'Point'
  })
  
if (nearestPoint) {
  this.moveToCoordinate(
    olProj.transform(
      nearestPoint.getGeometry().getCoordinates(),
      this._map.getView().getProjection(),
      'EPSG:4326',
    ),
    18,
  )
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.