RandomPointsBuilder.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import Location from '../../geom/Location'
  2. import Geometry from '../../geom/Geometry'
  3. import hasInterface from '../../../../../hasInterface'
  4. import GeometryFactory from '../../geom/GeometryFactory'
  5. import Coordinate from '../../geom/Coordinate'
  6. import IllegalArgumentException from '../../../../../java/lang/IllegalArgumentException'
  7. import Polygonal from '../../geom/Polygonal'
  8. import IndexedPointInAreaLocator from '../../algorithm/locate/IndexedPointInAreaLocator'
  9. import GeometricShapeBuilder from '../GeometricShapeBuilder'
  10. export default class RandomPointsBuilder extends GeometricShapeBuilder {
  11. constructor() {
  12. super()
  13. RandomPointsBuilder.constructor_.apply(this, arguments)
  14. }
  15. static constructor_() {
  16. this._maskPoly = null
  17. this._extentLocator = null
  18. if (arguments.length === 0) {
  19. GeometricShapeBuilder.constructor_.call(this, new GeometryFactory())
  20. } else if (arguments.length === 1) {
  21. const geomFact = arguments[0]
  22. GeometricShapeBuilder.constructor_.call(this, geomFact)
  23. }
  24. }
  25. getGeometry() {
  26. const pts = new Array(this._numPts).fill(null)
  27. let i = 0
  28. while (i < this._numPts) {
  29. const p = this.createRandomCoord(this.getExtent())
  30. if (this._extentLocator !== null && !this.isInExtent(p)) continue
  31. pts[i++] = p
  32. }
  33. return this._geomFactory.createMultiPointFromCoords(pts)
  34. }
  35. createRandomCoord(env) {
  36. const x = env.getMinX() + env.getWidth() * Math.random()
  37. const y = env.getMinY() + env.getHeight() * Math.random()
  38. return this.createCoord(x, y)
  39. }
  40. isInExtent(p) {
  41. if (this._extentLocator !== null) return this._extentLocator.locate(p) !== Location.EXTERIOR
  42. return this.getExtent().contains(p)
  43. }
  44. setExtent() {
  45. if (arguments.length === 1 && arguments[0] instanceof Geometry) {
  46. const mask = arguments[0]
  47. if (!hasInterface(mask, Polygonal)) throw new IllegalArgumentException('Only polygonal extents are supported')
  48. this._maskPoly = mask
  49. this.setExtent(mask.getEnvelopeInternal())
  50. this._extentLocator = new IndexedPointInAreaLocator(mask)
  51. } else {
  52. return super.setExtent.apply(this, arguments)
  53. }
  54. }
  55. createCoord(x, y) {
  56. const pt = new Coordinate(x, y)
  57. this._geomFactory.getPrecisionModel().makePrecise(pt)
  58. return pt
  59. }
  60. }