/** * Converts decimal degrees into a given format * * @param float $degrees The decimal degrees * @param string $format The format: DMS, HMS, MOD360, NONE, RADIANS, default = NONE * @param bool $mod360 True to convert degrees to a value between 0 and 360 degrees before formating, * false otherwise, default = false * @return float|array The degrees expressed in the given format * @returns int 0 The degrees or the hours * @returns int 1 The minutes * @returns float 2 The seconds * @returns bool 3 True if positive, false if negative */ function aa_degrees_to_format($degrees, $format = null, $mod360 = false) { if ($mod360) { $degrees = aa_degrees_to_mod360($degrees); } switch ($format) { case 'DMS': case 'dms': $degrees = aa_degrees_to_dms($degrees); break; case 'HMS': case 'hms': $degrees = aa_degrees_to_hms($degrees); break; case 'MOD360': case 'mod360': $degrees = aa_degrees_to_mod360($degrees); break; case 'NONE': case null: // passthru, no formatting break; case 'RADIANS': case 'radians': $degrees = deg2rad($degrees); break; default: aa_set_error('Invalid format.'); return false; } return $degrees; }
/** * Adjust axes for block spacing, setting the depth unit */ protected function AdjustAxes(&$x_len, &$y_len) { // make sure project_angle is in range if ($this->project_angle < 1) { $this->project_angle = 1; } elseif ($this->project_angle > 90) { $this->project_angle = 90; } $ends = $this->GetAxisEnds(); $bars = $ends['k_max'][0] - $ends['k_min'][0] + 1; $a = deg2rad($this->project_angle); $depth = $this->depth; $u = $x_len / ($bars + $depth * cos($a)); $d = $u * $depth * sin($a); if ($d > $y_len) { // doesn't fit - use 1/2 y length $d = $y_len / 2; $u = $d / $depth * sin($a); } $c = $u * $depth * cos($a); $x_len -= $c; $y_len -= $d; $this->depth_unit = $u; return array($c, $d); }
/** * @param float $longitude * * @return float */ protected function deg2radLongitude($longitude) { if ($longitude > 0) { return deg2rad($longitude); } return deg2rad($longitude + 360); }
public function renderGraph() { $this->i['top_heading_height'] = max(self::$c['size']['headers'] + 22 + self::$c['size']['key'], 48); $this->i['top_start'] = $this->i['top_heading_height'] + 50; $this->update_graph_dimensions($this->i['graph_width'], $this->i['graph_height'] + $this->i['top_start'], true); // Do the actual work $this->render_graph_init(); $this->graph_key_height(); $this->render_graph_key(); $this->render_graph_heading(); $data = array(1, 2, 3, 6, 7, 8, 9, 10); $center_block_x = round($this->i['graph_width'] / 2); $center_block_y = round($this->i['graph_height'] / 2); for ($ring = 0, $blocks_per_ring = count($data) <= 5 ? 5 : 4, $ring_size = ceil(count($data) / $blocks_per_ring); $ring < $ring_size; $ring++) { $depth = ($ring + 1) * (min($center_block_x, $center_block_y) / ($ring_size + 0.25)); for ($i = $ring * $blocks_per_ring, $i_size = $i + $blocks_per_ring; $i < $i_size; $i++) { $this_degree = 360 / $blocks_per_ring * ($i % $blocks_per_ring + $ring / $ring_size); $this_block_x = round($center_block_x + cos(deg2rad($this_degree)) * $depth); $this_block_y = round($center_block_y - sin(deg2rad($this_degree)) * $depth); $this->svg_dom->draw_svg_line($center_block_x, $center_block_y, $this_block_x, $this_block_y, self::$c['color']['notches'], 2); $this->svg_dom->add_element('rect', array('x' => $this_block_x - 20, 'y' => $this_block_y - 20, 'width' => 40, 'height' => 40, 'fill' => self::$c['color']['alert'])); } } $this->svg_dom->add_element('rect', array('x' => $center_block_x - 50, 'y' => $center_block_y - 50, 'width' => 100, 'height' => 100, 'fill' => self::$c['color']['alert'])); }
/** * get distance between to geocoords using great circle distance formula * @param Point $point1 * @param Point $point2 * @param string $unit M=miles, K=kilometers, N=nautical miles, I=inches, F=feet */ function distanceBetweenPoints($point1, $point2, $unit = 'K') { $lat1 = $point1->lat; $lng1 = $point1->lng; $lat2 = $point2->lat; $lng2 = $point2->lng; // calculate miles $M = 69.09 * rad2deg(acos(sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($lng1 - $lng2)))); switch (strtoupper($unit)) { case 'K': // kilometers return $M * 1.609344; break; case 'N': // nautical miles return $M * 0.868976242; break; case 'F': // feet return $M * 5280; break; case 'I': // inches return $M * 63360; break; case 'M': // miles return $M; break; default: // miles return $M; break; } }
/** * Calculates position of pie */ protected function Calc() { $bound_x_left = $this->pad_left; $bound_y_top = $this->pad_top; $bound_x_right = $this->width - $this->pad_right; $bound_y_bottom = $this->height - $this->pad_bottom; $w = $bound_x_right - $bound_x_left; $h = $bound_y_bottom - $bound_y_top; if ($this->aspect_ratio == 'auto') { $this->aspect_ratio = $h / $w; } elseif ($this->aspect_ratio <= 0) { $this->aspect_ratio = 1.0; } $this->x_centre = ($bound_x_right - $bound_x_left) / 2 + $bound_x_left; $this->y_centre = ($bound_y_bottom - $bound_y_top) / 2 + $bound_y_top; $this->start_angle %= 360; if ($this->start_angle < 0) { $this->start_angle = 360 + $this->start_angle; } $this->s_angle = deg2rad($this->start_angle); if ($h / $w > $this->aspect_ratio) { $this->radius_x = $w / 2.0; $this->radius_y = $this->radius_x * $this->aspect_ratio; } else { $this->radius_y = $h / 2.0; $this->radius_x = $this->radius_y / $this->aspect_ratio; } $this->calc_done = true; $this->sub_total = 0; $this->ColourSetup($this->values->ItemsCount()); }
/** * Calculate an (approximate) OpenXML column width, based on font size and text contained * * @param int $fontSize Font size (in pixels or points) * @param bool $fontSizeInPixels Is the font size specified in pixels (true) or in points (false) ? * @param string $columnText Text to calculate width * @param int $rotation Rotation angle * @return int Column width */ public static function calculateColumnWidth($fontSize = 9, $fontSizeInPixels = false, $columnText = '', $rotation = 0) { if (!$fontSizeInPixels) { // Translate points size to pixel size $fontSize = PHPExcel_Shared_Font::fontSizeToPixels($fontSize); } // If it is rich text, use rich text... if ($columnText instanceof PHPExcel_RichText) { $columnText = $columnText->getPlainText(); } // Only measure the part before the first newline character if (strpos($columnText, "\r") !== false) { $columnText = substr($columnText, 0, strpos($columnText, "\r")); } if (strpos($columnText, "\n") !== false) { $columnText = substr($columnText, 0, strpos($columnText, "\n")); } // Calculate column width $columnWidth = (strlen($columnText) * $fontSize + 5) / $fontSize * 256 / 256; // Calculate approximate rotated column width if ($rotation !== 0) { if ($rotation == -165) { // stacked text $columnWidth = 4; // approximation } else { // rotated text $columnWidth = $columnWidth * cos(deg2rad($rotation)) + $fontSize * abs(sin(deg2rad($rotation))) / 5; // approximation } } // Return return round($columnWidth, 6); }
/** * Get bearing from position to another * * Code from http://www.corecoding.com/getfile.php?file=25 */ function get_bearing($from, $to) { if (round($from['longitude'], 1) == round($to['longitude'], 1)) { if ($from['latitude'] < $to['latitude']) { $bearing = 0; } else { $bearing = 180; } } else { $dist = org_routamc_positioning_utils::get_distance($from, $to, 'N'); $arad = acos((sin(deg2rad($to['latitude'])) - sin(deg2rad($from['latitude'])) * cos(deg2rad($dist / 60))) / (sin(deg2rad($dist / 60)) * cos(deg2rad($from['latitude'])))); $bearing = $arad * 180 / pi(); if (sin(deg2rad($to['longitude'] - $from['longitude'])) < 0) { $bearing = 360 - $bearing; } } $dirs = array("N", "E", "S", "W"); $rounded = round($bearing / 22.5) % 16; if ($rounded % 4 == 0) { $dir = $dirs[$rounded / 4]; } else { $dir = $dirs[2 * floor((floor($rounded / 4) + 1) % 4 / 2)]; $dir .= $dirs[1 + 2 * floor($rounded / 8)]; } return $dir; }
/** * @param $from - string|array * string: GeoJson representation of POINT * array: location in the form [ <lng>, <lat> ] (two floats) * @param $attribute - attribute name of POINT * @param $radius number - search radius in kilometers * @return $this - query that returns models that are near to $from * * Example usages: * $here = [4.9, 52.3]; // longitude and latitude of my place * $nearestModel = <model>::find()->nearest($here, <attributeName>, 100)->one(); // search radius is 100 km * $fiveNearestModels = <model>::find()->nearest($here, <attributeName>, 100)->limit(5)->all(); * $dataProvider = new ActiveDataProvider([ 'query' => <model>::find()->nearest($here, <attributeName>, 100) ]); * * * @link http://www.plumislandmedia.net/mysql/haversine-mysql-nearest-loc/ * @link https://en.wikipedia.org/wiki/Haversine_formula */ public function nearest($from, $attribute, $radius = 100) { $lenPerDegree = 111.045; // km per degree latitude; for miles, use 69.0 if (is_string($from)) { $feat = SpatialHelper::jsonToGeom($from); if ($feat && $feat['type'] == 'Point') { $from = $feat['coordinates']; } } if (!is_array($from)) { return $this; } $lng = $from[0]; $lat = $from[1]; $dLat = $radius / $lenPerDegree; $dLng = $dLat / cos(deg2rad($lat)); /** @var \yii\db\ActiveRecord $modelCls */ $modelCls = $this->modelClass; $subQuery = $this->create($this)->from($modelCls::tableName())->select(['*', '_lng' => "X({$attribute})", '_lat' => "Y({$attribute})"])->having(['between', '_lng', $lng - $dLng, $lng + $dLng])->andHaving(['between', '_lat', $lat - $dLat, $lat + $dLat]); $this->from([$subQuery])->select(['*', '_d' => "{$lenPerDegree}*DEGREES(ACOS(COS(RADIANS(:lt))*COS(RADIANS(_lat))*COS(RADIANS(:lg)-RADIANS(_lng))+SIN(RADIANS(:lt))*SIN(RADIANS(_lat))))"])->params([':lg' => $lng, ':lt' => $lat])->having(['<', '_d', $radius])->orderBy(['_d' => SORT_ASC]); $this->where = null; $this->limit = null; $this->offset = null; $this->distinct = null; $this->groupBy = null; $this->join = null; $this->union = null; return $this; }
/** * @dataProvider coordValidProvider */ public function testGetCoordinate($coord) { $radians = deg2rad($coord); $Coordinate = new N\Coordinate(); $Coordinate->set($coord); $this->assertEquals($radians, $Coordinate->get(), '', 2.0E-14); }
public function init() { parent::init(); $this->maxDistKm = $this->maxDistance / 1000; $this->newLat = deg2rad($this->lat); $this->newLng = deg2rad($this->lng); }
/** * Call this function to find zipcodes near a certain location * @param {double} $latitude The latitude of the coordinates to search around * @param {double} $longitude The longitude of the coordinates to search around * @param {double} $miles The radius, in miles, around the central point of the zipcode * @param {double} $limit Limit on how many to return. Defaults to 100. * @return {array} Returns an array of Places_Zipcode objects, if any are found. */ public static function nearby($latitude, $longitude, $miles, $limit = 100) { // First, get a bounding box that's big enough to avoid false negatives $latGrid = $miles / 69.1703234283616; $longGrid = abs($latGrid / cos(deg2rad($latitude))); // Now, select zipcodes in a bounding box using one of the indexes $q = Places_Zipcode::select('*')->where(array('latitude >' => $latitude - $latGrid, 'latitude <' => $latitude + $latGrid)); $longitudes = array('longitude >' => max($longitude - $longGrid, -180), 'longitude <' => min($longitude + $longGrid, 180)); if ($latitude + $longGrid > 180) { $q->andWhere($longitudes, array('longitude >' => -180, 'longitude <' => $longitude + $longGrid - 180 * 2)); } else { if ($latitude - $longGrid < -180) { $q->andWhere($longitudes, array('longitude <=' => 180, 'longitude >' => $longitude - $longGrid + 180 * 2)); } else { $q->andWhere($longitudes); } } $latitude = substr($latitude, 0, 10); $longitude = substr($longitude, 0, 10); $q = $q->orderBy("POW(latitude - ({$latitude}), 2) + POW(longitude - ({$longitude}), 2)"); if ($limit) { $q = $q->limit($limit); } return $q->fetchDbRows(); }
function imagepolarline($image, $x1, $y1, $length, $angle, $color) { $x2 = $x1 + sin(deg2rad($angle)) * $length; $y2 = $y1 + cos(deg2rad($angle + 180)) * $length; imageline($image, $x1, $y1, $x2, $y2, $color); return array($x2, $y2); }
function convert($lat, $long) { $airy1830 = new RefEll(6377563.396, 6356256.909); $OSGB_F0 = 0.9996012717; $N0 = -100000.0; $E0 = 400000.0; $phi0 = deg2rad(49.0); $lambda0 = deg2rad(-2.0); $a = $airy1830->maj; $b = $airy1830->min; $eSquared = $airy1830->ecc; $phi = deg2rad($lat); $lambda = deg2rad($long); $E = 0.0; $N = 0.0; $n = ($a - $b) / ($a + $b); $v = $a * $OSGB_F0 * pow(1.0 - $eSquared * $this->sinSquared($phi), -0.5); $rho = $a * $OSGB_F0 * (1.0 - $eSquared) * pow(1.0 - $eSquared * $this->sinSquared($phi), -1.5); $etaSquared = $v / $rho - 1.0; $M = $b * $OSGB_F0 * ((1 + $n + 5.0 / 4.0 * $n * $n + 5.0 / 4.0 * $n * $n * $n) * ($phi - $phi0) - (3 * $n + 3 * $n * $n + 21.0 / 8.0 * $n * $n * $n) * sin($phi - $phi0) * cos($phi + $phi0) + (15.0 / 8.0 * $n * $n + 15.0 / 8.0 * $n * $n * $n) * sin(2.0 * ($phi - $phi0)) * cos(2.0 * ($phi + $phi0)) - 35.0 / 24.0 * $n * $n * $n * sin(3.0 * ($phi - $phi0)) * cos(3.0 * ($phi + $phi0))); $I = $M + $N0; $II = $v / 2.0 * sin($phi) * cos($phi); $III = $v / 24.0 * sin($phi) * pow(cos($phi), 3.0) * (5.0 - $this->tanSquared($phi) + 9.0 * $etaSquared); $IIIA = $v / 720.0 * sin($phi) * pow(cos($phi), 5.0) * (61.0 - 58.0 * $this->tanSquared($phi) + pow(tan($phi), 4.0)); $IV = $v * cos($phi); $V = $v / 6.0 * pow(cos($phi), 3.0) * ($v / $rho - $this->tanSquared($phi)); $VI = $v / 120.0 * pow(cos($phi), 5.0) * (5.0 - 18.0 * $this->tanSquared($phi) + pow(tan($phi), 4.0) + 14 * $etaSquared - 58 * $this->tanSquared($phi) * $etaSquared); $N = $I + $II * pow($lambda - $lambda0, 2.0) + $III * pow($lambda - $lambda0, 4.0) + $IIIA * pow($lambda - $lambda0, 6.0); $E = $E0 + $IV * ($lambda - $lambda0) + $V * pow($lambda - $lambda0, 3.0) + $VI * pow($lambda - $lambda0, 5.0); return array($E, $N); }
function CircleDraw($lat_one, $long_one, $radius, $datasrc, $time) { //convert from degrees to radians $lat1 = deg2rad($lat_one); $long1 = deg2rad($long_one); $d = $radius; $d_rad = $d / 6378137; $hex = 0xc249255; $color = $datasrc * $hex; $out = "<name>Data Visualization</name>\n"; $out .= "<visibility>1</visibility>\n"; $out .= "<Placemark>\n"; $out .= "<name>Dilution for node " . $datasrc . " at " . $time . "</name>\n"; $out .= "<visibility>1</visibility>\n"; $out .= "<Style>\n"; $out .= "<geomColor>" . dechex($color) . "</geomColor>\n"; $out .= "<geomScale>1</geomScale></Style>\n"; $out .= "<LineString>\n"; $out .= "<coordinates>\n"; // loop through the array and write path linestrings for ($i = 0; $i <= 360; $i++) { $radial = deg2rad($i); $lat_rad = asin(sin($lat1) * cos($d_rad) + cos($lat1) * sin($d_rad) * cos($radial)); $dlon_rad = atan2(sin($radial) * sin($d_rad) * cos($lat1), cos($d_rad) - sin($lat1) * sin($lat_rad)); $lon_rad = fmod($long1 + $dlon_rad + M_PI, 2 * M_PI) - M_PI; $out .= rad2deg($lon_rad) . "," . rad2deg($lat_rad) . ",0 "; } $out .= "</coordinates>\n"; $out .= "</LineString>\n"; $out .= "</Placemark>\n"; return $out; }
/** * @return InclinedStringDrawer **/ public function draw($string) { $textWidth = $this->getTextWidth($string); $textHeight = $this->getMaxCharacterHeight(); if ($textWidth < $this->getTuringImage()->getHeight()) { $maxAngle = 45; } else { $maxAngle = rad2deg(asin(($this->getTuringImage()->getHeight() - $textHeight) / $textWidth)); } $angle = mt_rand(-$maxAngle / 2, $maxAngle / 2); if ($angle > self::MAX_ANGLE) { $angle = self::MAX_ANGLE; } if ($angle < -self::MAX_ANGLE) { $angle = -self::MAX_ANGLE; } if ($this->getTuringImage()->getWidth() > $textWidth) { $x = round(($this->getTuringImage()->getWidth() - $textWidth) * cos(deg2rad($angle)) / 2); $y = round(($this->getTuringImage()->getHeight() + $textWidth) * sin(deg2rad($angle)) / 2 + $textHeight / 2); for ($i = 0, $length = strlen($string); $i < $length; ++$i) { $character = $string[$i]; $this->drawCraracter($angle, $x, $y, $character); $charWidth = $this->getStringWidth($character) + $this->getSpace(); $y -= $charWidth * sin(deg2rad($angle)); $x += $charWidth * cos(deg2rad($angle)); } } else { return $this->showError(); } return $this; }
function bearing($lat1, $lon1, $lat2, $lon2) { if (round($lon1, 1) == round($lon2, 1)) { if ($lat1 < $lat2) { $bearing = 0; } else { $bearing = 180; } } else { $dist = distance($lat1, $lon1, $lat2, $lon2, 'N'); $arad = acos((sin(deg2rad($lat2)) - sin(deg2rad($lat1)) * cos(deg2rad($dist / 60))) / (sin(deg2rad($dist / 60)) * cos(deg2rad($lat1)))); $bearing = $arad * 180 / pi(); if (sin(deg2rad($lon2 - $lon1)) < 0) { $bearing = 360 - $bearing; } } $dirs = array("N", "E", "S", "W"); $rounded = round($bearing / 22.5) % 16; if ($rounded % 4 == 0) { $dir = $dirs[$rounded / 4]; } else { $dir = $dirs[2 * floor((floor($rounded / 4) + 1) % 4 / 2)]; $dir .= $dirs[1 + 2 * floor($rounded / 8)]; #if ($rounded % 2 == 1) # $dir = $dirs[round_to_int($rounded/4) % 4] . "-" . $dir; } $var_dist = ""; #return $dir; if (isset($dist)) { $var_dist = $dist . " miles"; } return round($bearing, 0) . "º " . $dir . " " . $var_dist; }
function beforeFind(&$model, $query) { $default = array('lon' => null, 'lat' => null, 'dist' => '1km'); $query = Set::merge($default, $query); $lon = (double) $query['lon']; $lat = (double) $query['lat']; $dist = $query['dist']; if ($lon && $lat) { if (strpos($dist, 'km') === false && strpos($dist, 'm')) { $dist = floatval($dist) / 1000; } else { $dist = floatval($dist); } $lon1 = $lon - $dist / abs(cos(deg2rad($lat)) * 69.09 * 1.609344); $lon2 = $lon + $dist / abs(cos(deg2rad($lat)) * 69.09 * 1.609344); $lat1 = $lat - $dist / (69.09 * 1.609344); $lat2 = $lat + $dist / (69.09 * 1.609344); $conditions = array("{$model->alias}.lon BETWEEN ? AND ?" => array($lon1, $lon2), "{$model->alias}.lat BETWEEN ? AND ?" => array($lat1, $lat2)); $query = Set::merge($query, array('conditions' => $conditions)); } unset($query['lon']); unset($query['lat']); unset($query['dist']); if ($model->findQueryType !== 'count') { $fields = array("{$model->alias}.*", "3956*2*ASIN(\n\t\t\t\t\tSQRT(\n\t\t\t\t\t\tPOWER(\n\t\t\t\t\t\t\tSIN(({$lat}-`{$model->alias}`.`lat`)\n\t\t\t\t\t\t\t*pi()/180/2),2\n\t\t\t\t\t\t)\n\t\t\t\t\t\t+COS({$lat}*pi()/180)\n\t\t\t\t\t\t*COS(`{$model->alias}`.`lat`*pi()/180)\n\t\t\t\t\t\t*POWER(\n\t\t\t\t\t\t\tSIN(({$lon}-`{$model->alias}`.`lon`)\n\t\t\t\t\t\t\t*pi()/180/2),2\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t)*1.609344*1000 AS `distance`"); $order = array('distance ASC'); $query = Set::merge($query, array('fields' => $fields), array('order' => $order)); } return $query; }
function ogdbDistance($origin, $destination) { ini_set('precision', 49); // http://de2.php.net/manual/de/function.pi.php $fileData = explode("\n", ogdbGetData()); foreach ($fileData as $fileRow) { $fileRow = explode("\t", $fileRow); $dataStructure = ogdbDataStructure($fileRow); if ($dataStructure) { if (isset($fileRow[$dataStructure['zip_pos']]) && isset($fileRow[$dataStructure['lon_pos']]) && isset($fileRow[$dataStructure['lat_pos']])) { if (substr_count($fileRow[$dataStructure['zip_pos']], $origin) == 1) { $origin_lon = deg2rad($fileRow[$dataStructure['lon_pos']]); $origin_lat = deg2rad($fileRow[$dataStructure['lat_pos']]); } if (substr_count($fileRow[$dataStructure['zip_pos']], $destination) == 1) { $destination_lon = deg2rad($fileRow[$dataStructure['lon_pos']]); $destination_lat = deg2rad($fileRow[$dataStructure['lat_pos']]); } } } unset($dataStructure, $fileRow); } $distance = FALSE; if (isset($origin_lon) && isset($origin_lat) && isset($destination_lon) && isset($destination_lat)) { $distance = acos(sin($destination_lat) * sin($origin_lat) + cos($destination_lat) * cos($origin_lat) * cos($destination_lon - $origin_lon)) * OGDB_EARTH_RADIUS; } return $distance; }
public function toCartesian() { $radiansTheta = deg2rad($this->theta); $x = round($this->r * cos($radiansTheta)); $y = round($this->r * sin($radiansTheta)); return new Cartesian($x, $y); }
function calc_distance($r1, $a1, $r2, $a2) { assert($r1 >= 0); assert($a1 >= 0 && $a1 <= 360000); assert($r2 >= 0); assert($a2 >= 0 && $a2 <= 360000); // First, calculate X1,Y1 and X2,Y2, the coordinates inside the // (virtual) galaxy grid $Y1 = $r1 * cos(deg2rad($a1 / 1000)); // RADS! Which in fact, doesn't mind // since all points are virtual $X1 = $r1 * sin(deg2rad($a1 / 1000)); $Y2 = $r2 * cos(deg2rad($a2 / 1000)); $X2 = $r2 * sin(deg2rad($a2 / 1000)); // Get the (absolute) delta of the 2 points $DX = abs($X1 - $X2); $DY = abs($Y1 - $Y2); // Pythagoras says: c^2 = a^2 + b^2. At least, he used to say, he's dead now... $c = sqrt($DX * $DX + $DY * $DY); // round ($c, 4); // PHP >= 4.0.4?? $c = $c * 1000; // Keep 3 digits after the comma $c = round($c); // Round it $c = $c / 1000; // And back with those digits... return $c; // Return schuine zijde }
/** * Get distance from another position * * @param PositionAbstract $position Position to get distance from. * * @param string $units Units to return. Default (m) is miles. * n = nautical miles, k = kilometers, * f = feet, i = inches. * * @param float $adjustment Adjust the distance to take turns into account. * 1.125 seems to be the most accurate. * * @return float Distance in the specified units */ public function getDistanceFrom(PositionAbstract $position, $units = 'm', $adjustment = 1.125) { $miles = $adjustment * 3959 * acos(cos(deg2rad($this->getLat())) * cos(deg2rad($position->getLat())) * cos(deg2rad($this->getLng()) - deg2rad($position->getLng())) + sin(deg2rad($this->getLat())) * sin(deg2rad($position->getLat()))); switch (strtolower($units)) { case 'k': // kilometers return $miles * 1.609344; break; case 'n': // nautical mile return $miles * 0.868976242; break; case 'f': // feet return $miles * 5280; break; case 'i': // inches return $miles * 63360; break; case 'm': default: return $miles; break; } }
public function createFromWidthAndAlpha(array $coords) { $width = $coords[0]; $alpha = $coords[1]; $height = tan(deg2rad($alpha)) * $width; return $this->createFromCoordinates(array(0, 0, $width, $height)); }
public static function getDistance($lat1, $long1, $lat2, $long2, $scale = 'km') { switch (strtolower($scale)) { case 'miles': $earth = 3960; break; case 'km': default: $earth = 6371; break; } //Point 1 cords $lat1 = deg2rad($lat1); $long1 = deg2rad($long1); //Point 2 cords $lat2 = deg2rad($lat2); $long2 = deg2rad($long2); //Haversine Formula $dlong = $long2 - $long1; $dlat = $lat2 - $lat1; $sinlat = sin($dlat / 2); $sinlong = sin($dlong / 2); $a = $sinlat * $sinlat + cos($lat1) * cos($lat2) * ($sinlong * $sinlong); $b = 2 * asin(min(1, sqrt($a))); return $earth * $b; }
protected static function getRadDeg($x) { if (self::$DEGREES == true) { return deg2rad($x); } return $x; }
private function distance($lat1, $lon1, $lat2, $lon2, $unit) { global $source; $theta = $lon1 - $lon2; $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); $dist = acos($dist); $dist = rad2deg($dist); $miles = $dist * 60 * 1.1515; $unit = strtoupper($unit); $distDesc = ""; if ($unit == "K") { $meters = intval($miles * 1.609344 * 1000); if ($meters > 1000) { $distDesc1 = intval($meters / 1000) . '公里'; $distDesc2 = intval($meters % 1000) . '公尺'; $distDesc = $distDesc1 . $distDesc2; } else { $distDesc = $meters . '公尺'; } } else { if ($unit == "N") { $distDesc = $miles * 0.8683999999999999 + ''; } else { $distDesc = $miles + ''; } } return array("dist" => $meters, "distDesc" => $distDesc); }
public function scopeNearLatLong($query, $lat, $lng, $radius = 10, $unit = 69.0) { if (!is_numeric($lat) || -90 >= $lat || $lat >= 90) { throw new RangeException("Latitude must be between -90 and 90 degrees."); } if (!is_numeric($lng) || -180 >= $lng || $lng >= 180) { throw new RangeException("Longitude must be between -180 and 180 degrees."); } $subQuery = clone $query; $latDistance = $radius / $unit; $latNorth = $lat - $latDistance; $latSouth = $lat + $latDistance; $lngDistance = $radius / ($unit * cos(deg2rad($lat))); $lngEast = $lng - $lngDistance; $lngWest = $lng + $lngDistance; $subQuery->selectRaw(DB::raw('*, (? * DEGREES( ACOS( COS(RADIANS(?)) * COS(RADIANS(latitude)) * COS(RADIANS(? - longitude)) + SIN(RADIANS(?)) * SIN(RADIANS(latitude)) ) )) AS distance'))->addBinding([$unit, $lat, $lng, $lat], 'select'); $subQuery->whereBetween('latitude', [$latNorth, $latSouth]); $subQuery->whereBetween('longitude', [$lngEast, $lngWest]); $query->from(DB::raw('(' . $subQuery->toSql() . ') as d')); $query->mergeBindings($subQuery->getQuery()); $query->where('distance', '<=', $radius); // // To use: // $latitude = 29.443778; // $longitude = -98.478903; // // Default radius is 10; default unit is miles. // Model::nearLatLong($latitude, $longitude)->get(); }
/** * Compare two position and return is in area * @param double $areaLat * @param double $areaLng * @param double $radius * @param double $targetLat * @param double $targetLng * @return boolean */ public function isInArea($lat1, $lon1, $radius, $lat2, $lon2) { $theta = $lon1 - $lon2; $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); $dist = acos($dist); $dist = rad2deg($dist); $miles = $dist * 60 * 1.1515; $meter = $miles * 1609.344; if ($meter <= $radius) { return true; } else { return false; } // if ($unit == "K") { // return ($miles * 1.609344); // } else if ($unit == "N") { // return ($miles * 0.8684); // } else { // return $miles; // } // } // echo distance(32.9697, -96.80322, 29.46786, -98.53506, "M") . " Miles<br>"; // echo distance(32.9697, -96.80322, 29.46786, -98.53506, "K") . " Kilometers<br>"; // echo distance(32.9697, -96.80322, 29.46786, -98.53506, "N") . " Nautical Miles<br>"; }
public static function getRange($params) { if (empty($params['range'])) { $params['range'] = 1000; } if (!isset($params['latitude']) || !isset($params['longitude']) || !isset($params['range'])) { return false; } $latitude = $params['range'] / 111319.55; $result['min_latitude'] = number_format($params['latitude'] - $latitude, 6); $result['max_latitude'] = number_format($params['latitude'] + $latitude, 6); // $longitude = $params['range']/(111319.55*cos($params['latitude']))*0.817;//0.86修正数 $longitude = rad2deg(asin(sin($params['range'] / self::R) / cos(deg2rad($params['latitude'])))); $result['min_longitude'] = number_format($params['longitude'] - $longitude, 6); $result['max_longitude'] = number_format($params['longitude'] + $longitude, 6); if ($result['min_latitude'] < -90) { $result['min_latitude'] = -90.0; } if ($result['max_latitude'] > 90) { $result['max_latitude'] = 90.0; } if ($result['min_longitude'] < -180) { $result['min_longitude'] = -180.0; } if ($result['max_longitude'] > 180) { $result['max_longitude'] = 180.0; } return $result; }
/** * Calculates the distance (in miles) between two points using the Haversine formula. * * @param array $point1 Array with indices [lat,lng] * @param array $point2 Array with indices [lat,lng] * @return float Distance in miles */ public static function _getLatLngDistance($point1, $point2) { $lat1 = $point1["lat"]; $lng1 = $point1["lng"]; $lat2 = $point2["lat"]; $lng2 = $point2["lng"]; //$earth = 6371; //km change accordingly $earth = 3960; //miles //Point 1 cords $lat1 = deg2rad($lat1); $long1 = deg2rad($lng1); //Point 2 cords $lat2 = deg2rad($lat2); $long2 = deg2rad($lng2); //Haversine Formula $dlong = $long2 - $long1; $dlat = $lat2 - $lat1; $sinlat = sin($dlat / 2); $sinlong = sin($dlong / 2); $a = $sinlat * $sinlat + cos($lat1) * cos($lat2) * ($sinlong * $sinlong); $c = 2 * asin(min(1, sqrt($a))); $d = $earth * $c; return $d; }