Skip to content

Instantly share code, notes, and snippets.

@lloc
Created May 15, 2019 14:51
Show Gist options
  • Select an option

  • Save lloc/8d164dd8174da25553c08362b320caff to your computer and use it in GitHub Desktop.

Select an option

Save lloc/8d164dd8174da25553c08362b320caff to your computer and use it in GitHub Desktop.

Revisions

  1. lloc created this gist May 15, 2019.
    88 changes: 88 additions & 0 deletions BoundingBox.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,88 @@
    <?php

    /**
    * Class BoundingBox
    */
    class BoundingBox {

    /**
    * @var float $lat
    * @var float $lon
    * @var int $radius
    */
    protected $lat, $lon, $radius;

    const EARTH_RADIUS = 6371;

    /**
    * BoundingBox constructor.
    *
    * @param float $lat
    * @param float $lon
    * @param int $radius
    */
    public function __construct( float $lat, float $lon, int $radius ) {
    $this->lat = $lat;
    $this->lon = $lon;
    $this->radius = $radius;
    }

    /**
    * @return array
    */
    public function getCenter() {
    return [ 'lat' => $this->lat, 'lon' => $this->lon ];
    }

    /**
    * @return array
    */
    public function getLatitudes() {
    $latDeg = rad2deg($this->radius / self::EARTH_RADIUS );

    return [
    'min' => $this->lat - $latDeg,
    'max' => $this->lat + $latDeg,
    ];
    }

    /**
    * @return array
    */
    public function getLongitudes() {
    $lonDeg = rad2deg($this->radius / self::EARTH_RADIUS / cos( deg2rad( $this->lat ) ) );

    return [
    'min' => $this->lon - $lonDeg,
    'max' => $this->lon + $lonDeg,
    ];
    }

    /**
    * Returns true if the value is between the min and max of the coordinates
    *
    * @param float $value
    * @param array $coords
    *
    * @return bool
    */
    protected function filter( float $value, array $coords ) {
    return $value >= $coords['min'] && $value <= $coords['max'];
    }

    /**
    * Checks if the $coordinate is in the boundary box
    *
    * @param float $lat
    * @param float $lon
    *
    * @return bool
    */
    public function check( float $lat, float $lon ): bool {
    $isLat = $this->filter( $lat, $this->getLatitudes() );
    $islon = $this->filter( $lon, $this->getLongitudes() );

    return $isLat && $islon;
    }

    }