Skip to content

Commit

Permalink
geo within polygon
Browse files Browse the repository at this point in the history
  • Loading branch information
sokil committed Dec 21, 2014
1 parent 8bfe478 commit 51b183a
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 1 deletion.
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -761,6 +761,23 @@ $point = $this->collection
->findOne();
```

Search documents with points (stored as legacy coordinates) within polygon:
```php
<?php
$point = $this->collection
->find()
->withinPolygon(
'point',
array(
array(0, 0),
array(0, 10),
array(10, 10),
array(10, 0),
)
)
->findOne();
```

Pagination
----------

Expand Down
25 changes: 24 additions & 1 deletion src/Expression.php
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,7 @@ public function withinCircleSpherical($field, $longitude, $latitude, $radiusInRa
* Based on grid coordinates and does not query for GeoJSON shapes.
*
* Use planar geometry, so 2d index may be used but not required
*
*
* @param string $field
* @param array $bottomLeftCoordinate Bottom left coordinate of box
* @param array $upperRightCoordinate Upper right coordinate of box
Expand All @@ -559,6 +559,29 @@ public function withinBox($field, array $bottomLeftCoordinate, array $upperRight
return $this;
}

/**
* Return documents that are within the polygon, according
* to their point-based location data.
*
* Based on grid coordinates and does not query for GeoJSON shapes.
*
* Use planar geometry, so 2d index may be used but not required
*
* @param string $field
* @param array $points array of coordinates
* @return \Sokil\Mongo\Expression
*/
public function withinPolygon($field, array $points)
{
$this->where($field, array(
'$geoWithin' => array(
'$polygon' => $points,
),
));

return $this;
}

public function toArray()
{
return $this->_expression;
Expand Down
33 changes: 33 additions & 0 deletions tests/DocumentGeoTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -699,4 +699,37 @@ public function testExpressionWithinBox()
$this->assertNotEmpty($point);
$this->assertEquals($point1Id, $point->getId());
}

public function testExpressionWithinPolygon()
{
$this->collection->ensure2dIndex('point');

$point1Id = $this->collection
->createDocument()
->setLegacyPoint('point', 5, 4)
->save()
->getId();

$point2Id = $this->collection
->createDocument()
->setLegacyPoint('point', 50, 40)
->save()
->getId();

$point = $this->collection
->find()
->withinPolygon(
'point',
array(
array(0, 0),
array(0, 10),
array(10, 10),
array(10, 0),
)
)
->findOne();

$this->assertNotEmpty($point);
$this->assertEquals($point1Id, $point->getId());
}
}

0 comments on commit 51b183a

Please sign in to comment.