Skip to content

Instantly share code, notes, and snippets.

@zuckercode
Created October 23, 2012 23:14
Show Gist options
  • Save zuckercode/3942401 to your computer and use it in GitHub Desktop.
Save zuckercode/3942401 to your computer and use it in GitHub Desktop.
Phalcon ZipCoordinates Model
<?php
namespace Application\Backend\Models;
/**
*
*/
class ZipCoordinates extends \Phalcon\Mvc\Model
{
/**
* @const
*/
const EARTH_RADIUS = 6380;
/**
* @return string
*/
public function getSource ()
{
return 'zip_coordinates';
}
/**
* @param $lon
* @param $lat
* @param $zip
* @param $radius
*
* @return mixed
*/
public function getZipsInRadiusFromZip ( $lon, $lat, $zip, $radius )
{
$namespace = 'Application\Backend\Models\ZipCoordinates';
$phql = "SELECT
zc_zip,
zc_location_name,
ACOS(
SIN(RADIANS(zc_lat)) * SIN(RADIANS(" . $lat . "))
+ COS(RADIANS(zc_lat)) * COS(RADIANS(" . $lat . ")) * COS(RADIANS(zc_lon)
- RADIANS(" . $lon . "))
) * " . self::EARTH_RADIUS . " AS distance
FROM " . $namespace . "
WHERE ACOS(
SIN(RADIANS(zc_lat)) * SIN(RADIANS(" . $lat . "))
+ COS(RADIANS(zc_lat)) * COS(RADIANS(" . $lat . ")) * COS(RADIANS(zc_lon)
- RADIANS(" . $lon . "))
) * " . self::EARTH_RADIUS . " < " . $radius . "
AND zc_id <> " . $zip . "
ORDER BY distance,zc_zip";
$mm = $this->getDI()->getShared( 'modelsManager' );
$result = $mm->executeQuery( $phql );
return $result;
}
/**
* @param $zip
*/
public function getGeoCoordinates ( $zip )
{
$conditions = 'zc_zip = :zip:';
$bind = [ 'zip' => $zip ];
return self::find( [ $conditions, 'bind' => $bind ] );
}
}
// in controller or somewhere
$model = new \Application\Backend\Models\ZipCoordinates();
$rows = $model->getGeoCoordinates( $zip );
foreach ( $rows as $row ) {
$zipSearch = $row;
}
$rows = $model->getZipsInRadiusFromZip( $zipSearch->zc_lon, $zipSearch->zc_lat, $zipSearch->zc_zip, 10 );
foreach ( $rows as $row ) {
var_dump( $row->zc_zip );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment