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 dpEncode($points) { global $verySmall; $maxDist = 0; $absMaxDist = 0; $dists = array(); if (count($points) > 2) { $stack[] = array(0, count($points) - 1); while (count($stack) > 0) { $current = array_pop($stack); $maxDist = 0; for ($i = $current[0] + 1; $i < $current[1]; $i++) { $temp = distance($points[$i], $points[$current[0]], $points[$current[1]]); if ($temp > $maxDist) { $maxDist = $temp; $maxLoc = $i; if ($maxDist > $absMaxDist) { $absMaxDist = $maxDist; } } } if ($maxDist > $verySmall) { $dists[$maxLoc] = $maxDist; array_push($stack, array($current[0], $maxLoc)); array_push($stack, array($maxLoc, $current[1])); } } } $encodedPoints = createEncodings($points, $dists); $encodedLevels = encodeLevels($points, $dists, $absMaxDist); $encodedPointsLiteral = str_replace('\\', "\\\\", $encodedPoints); return array($encodedPoints, $encodedLevels, $encodedPointsLiteral); }
public function showlist() { global $G; $catid = intval($_GET['catid']); $pagesize = intval($_GET['pagesize']); $pagesize = $pagesize > 0 ? $pagesize : 20; $orderby = trim($_GET['orderby']); $orderby = in_array($orderby, array('id', 'sold', 'score')) ? $orderby : 'id'; $asc = $_GET['asc'] == 1 ? 'ASC' : 'DESC'; $goodslist = $this->t('goods')->field('*,dsx_distance(' . $this->longitude . ',' . $this->latitude . ',longitude,latitude) as distance')->order("distance ASC,{$orderby} {$asc}")->page($G['page'], $pagesize)->select(); if ($goodslist) { $newlist = array(); foreach ($goodslist as $list) { $list['pic'] = image($list['pic']); $list['distance'] = distance($list['distance']); $list['dateline'] = @date('Y-m-d', $list['dateline']); unset($list['description']); $newlist[] = $list; } $goodslist = $newlist; } else { $goodslist = array(); } $this->showAppData($goodslist); }
function distance($strandA, $strandB) { guardSameStrandLength($strandA, $strandB); if (empty($strandA) && empty($strandB)) { return 0; } return (int) areDifferent(substr($strandA, 0, 1), substr($strandB, 0, 1)) + distance(substr($strandA, 1), substr($strandB, 1)); }
function filter_by_loc($coupon_info) { global $search_bar_coupon_distance; global $user_location_longitude; global $user_location_latitude; if (distance($user_location_latitude, $user_location_longitude, $coupon_info->latitude, $coupon_info->longitude) <= $search_bar_coupon_distance) { return true; } return false; }
function intensity() { $edir = getcwd(); $efile = $edir . "/event.xy"; $contents = file($efile); $string = implode($contents); list($qlon, $qlat, $qdep, $qmag, $ntrig, $etime, $dtime, $qstd, $r_squared, $misfit) = split('[,]', $string); $a = -0.05; // Distance term $b = 1.8385; // Magnitude term $c = -7.8671; // Constant $width = (int) (log10($qmag * $qmag) * 100.0) / 100.0; $dec = 100; $dI = 1.0 / $dec; $dy = (int) (log10($qmag * $qmag) * $dec) / $dec; $lon_fact = cos($qlat * pi() / 180.0); $lon_fact *= $lon_fact; $dx = (int) ($dy / $lon_fact) * $dec / $dec; $x_mn = (int) ($qlon * $dec) / $dec - $dx; $x_mx = (int) ($qlon * $dec) / $dec + $dx; $y_mn = (int) ($qlat * $dec) / $dec - $dy; $y_mx = (int) ($qlat * $dec) / $dec + $dy; $dx2 = 0.1; $nx = (int) ($dx / $dx2 * 2) + 1; $ny = (int) ($dy / $dx2 * 2) + 1; $intensity_file = "intensity_map.xyz"; $fh = fopen($intensity_file, 'w'); for ($ix = 0; $ix < $nx; $ix++) { $x = $x_mn + $dx2 * (double) $ix; for ($iy = 0; $iy < $ny; $iy++) { $y = $y_mn + $dx2 * (double) $iy; $dist_xy = distance($qlon, $qlat, $x, $y); $dist_xyz = sqrt($dist_xy * $dist_xy + $qdep * $qdep); $pga = exp($a * $dist_xyz + $b * $qmag + $c); fwrite($fh, "{$x} , {$y} , {$pga}, {$dist_xyz} \n"); } } $sfile = $edir . "/stations.xyz"; $contents = file($sfile); foreach ($contents as $line_num => $line) { list($slon, $slat, $smag, $hid, $tid, $sfile, $ttime, $rtime, $sig, $dis, $pgah[0], $pgaz[0], $pgah[1], $pgaz[1], $pgah[2], $pgaz[2], $pgah[3], $pgaz[3], $pgah[4], $pgaz[4]) = split('[,]', $line); for ($j = 0; $j <= 4; $j++) { if ($pgah[$j] > $smag) { $smag = $pgah[$j]; } if ($pgaz[$j] > $smag) { $smag = $pgaz[$j]; } } fwrite($fh, "{$slon} , {$slat}, {$smag}\n"); } fclose($fh); }
function distance($word1, $word2) { if (strlen($word1) == 0) { return strlen($word2); } elseif (strlen($word2) == 0) { return strlen($word1); } else { $cost = $word1[0] == $word2[0] ? 0 : 1; return min(distance(substr($word1, 1), $word2) + 1, distance($word1, substr($word2, 1)) + 1, distance(substr($word1, 1), substr($word2, 1)) + $cost); } }
function efficiency($home_lat, $home_lng, $src_lat, $src_lng, $dst_lat, $dst_lng) { $home_lat = (double) $home_lat; $home_lng = (double) $home_lng; $src_lat = (double) $src_lat; $src_lng = (double) $src_lng; $dst_lat = (double) $dst_lat; $dst_lng = (double) $dst_lng; $src2dst = distance($src_lat, $src_lng, $dst_lat, $dst_lng); $home2dst = distance($home_lat, $home_lng, $dst_lat, $dst_lng); $home2src = distance($home_lat, $home_lng, $src_lat, $src_lng); return ceil($src2dst / ($src2dst + $home2dst + $home2src) * 200); }
function filterStoresByDistance($stores, $radius, $lat, $lng, $unit = "K") { //Check if Store is in the radius foreach ($stores as $id => $store) { $distance = distance($lat, $lng, $store['lat'], $store['long'], $unit); $distance = intval($distance); if ($distance <= $radius or $radius == 0) { $stores_radius[$id] = $distance; } } //Sort Radius-Store-List for Distance and rebuild stores-Array asort($stores_radius); foreach ($stores_radius as $id => $store) { $stores[$id][placeholder][distance] = $store; $stores_tmp[] = $stores[$id]; } return $stores_tmp; }
function getAlldetails($id, $lat, $lng) { //! Message Loggin comment_message_log('Start of Function : ' . __FUNCTION__); //! Data base connection $rConnection = dbConnection(); /*! * Check if the database Connection is failed */ if (!$rConnection) { //! Message Loggin comment_message_log('End of Function : ' . __FUNCTION__); return E00010; } //! Query $sQuery = "SELECT * FROM `servicesubcatrelation` a,`ownerservice` b,`servicebranch` c WHERE a.sub_category_id={$id} and a.service_id=b.service_id and b.service_id=c.service_id "; //! Executing the query $res = mysqli_query($rConnection, $sQuery); /*! * Check If the Query executed properly */ if ($res) { $data = array(); //! retrieve the result from the result set while ($aRow = mysqli_fetch_assoc($res)) { if (distance($lat, $aRow['branch_lat'], $lng, $aRow['branch_lng']) < 300) { $data[] = $aRow; } } //! Closing the connections dbConnectionClose($rConnection); //! Message Login comment_message_log('Query Executed Successfully.::: ' . $sQuery); comment_message_log('End of Function : ' . __FUNCTION__); return $data; } else { comment_message_log('Query Execution failed. ::: ' . $sQuery . ' ::: ' . @mysqli_error($rConnection)); comment_message_log('End of Function : ' . __FUNCTION__); //! Closing the connections dbConnectionClose($rConnection); return E00100; } }
public function showlist() { global $G; $pagesize = isset($_GET['pagesize']) ? intval($_GET['pagesize']) : 20; $shoplist = $this->t('shop')->field('*,dsx_distance(' . $this->longitude . ',' . $this->latitude . ',longitude,latitude) as distance')->page($G['page'], $pagesize)->order('distance ASC,shopid ASC')->select(); if ($shoplist) { $newlist = array(); foreach ($shoplist as $list) { $list['pic'] = image($list['pic']); $list['distance'] = distance($list['distance']); $list['description'] = stripHtml($list['description']); $newlist[] = $list; } $shoplist = $newlist; } else { $shoplist = array(); } $this->showAppData($shoplist); }
public function showmytask() { global $G, $lang; $pagesize = isset($_GET['pagesize']) ? intval($_GET['pagesize']) : 20; $tasklist = $this->t('task')->where(array('uid' => $this->uid))->page($G['page'], $pagesize)->order('tid DESC')->select(); if ($tasklist) { $newlist = array(); foreach ($tasklist as $list) { $list['pic'] = image($list['pic']); $list['distance'] = distance($list['distance']); unset($list['content']); $newlist[] = $list; } $tasklist = $newlist; } else { $tasklist = array(); } $this->showAppData($tasklist); }
function distToSegment($firstPointSegment, $secondPointSegment, $point) { /* нахождение длины отрезка */ $sizeSegment = distance($firstPointSegment, $secondPointSegment); /* нахождение проекции точки $point на отрезке по формуле t = [(p-v) . (w-v)] / |w-v|^2 * где t - $projection, p - $point, v - $firstPointSegment, w - $secondPointSegment */ $projection = (($point['X'] - $firstPointSegment['X']) * ($secondPointSegment['X'] - $firstPointSegment['X']) + ($point['Y'] - $firstPointSegment['Y']) * ($secondPointSegment['Y'] - $firstPointSegment['Y'])) / $sizeSegment; if ($projection < 0) { // если проекция на точке $firstPointSegment $pointOnSegment = $firstPointSegment; } elseif ($projection > 1) { // если проекция на точке $secondPointSegment $pointOnSegment = $secondPointSegment; } else { // если проекция не на границах отрезка $pointOnSegment = array('X' => $firstPointSegment['X'] + $projection * ($secondPointSegment['X'] - $firstPointSegment['X']), 'Y' => $firstPointSegment['Y'] + $projection * ($secondPointSegment['Y'] - $firstPointSegment['Y'])); } /* массив с минимальным расстоянием, и расположением точки на отрезке */ return array('DISTANCE' => sqrt(distance($point, $pointOnSegment)), 'POINT' => $pointOnSegment); }
function main($lat, $lon, $offset, $date_search, $distance_tolerance) { $rows_per_page = 10; $cxn = $GLOBALS['cxn']; $sql = "SELECT * FROM user_events\n\t\t\tWHERE end_date >= '{$date_search}'\n\t\t\tORDER BY start_date ASC\n\t\t\tLIMIT {$offset}, {$rows_per_page}"; $res = mysqli_query($cxn, $sql) or die("could not pull events"); //echo $sql; $count = mysqli_num_rows($res); //echo "Count:".$count; if ($count == 0) { //user has no events! $arr = array("status" => 0, "content" => "No events!"); echo json_encode($arr); exit; } // all results will be appended to this var: $search_output = ""; while ($row = mysqli_fetch_assoc($res)) { //event_id user_id event_title event_description end_date start_date date_created public extract($row); //echo "pulling event $event_id <br />"; $query_id = "SELECT * FROM event_address WHERE event_id = '{$event_id}'"; $res2 = mysqli_query($cxn, $query_id) or die("failed to pull address"); $row_addy = mysqli_fetch_assoc($res2); //address_id event_id address_text x_coord y_coord extract($row_addy); $distance = distance($x_coord, $y_coord, $lat, $lon, "m"); /* after everything is extracted: assemble the event and make the html output */ if ($distance <= $distance_tolerance) { $all_vars = array("event_id" => $event_id, "user_id" => $user_id, "event_description" => $event_description, "event_title" => $event_title, "start_date" => $start_date, "end_date" => $end_date, "venue_address" => $address_text, "lat" => $x_coord, "lon" => $y_coord, "distance" => $distance, "search_output" => $search_output, "isContactInfo" => $is_contactable, "contactInfo" => $contact_info, "contactType" => $contact_type); $search_output = search_output_func_users($all_vars); //see search_functions.php } } $content_array = array("status" => 1, "content" => $search_output); return $content_array; }
function lookUp($loc, $mask, $pdo, $SENDER_URL, $APP_INFO) { $user = getUser($mask, $pdo); $list = getMatchList($mask, $pdo); if (getUser($mask, $pdo)["friendMask"] != 'nill') { sendReply("Your friend has left the conversation.", getFMask($mask, $pdo), $SENDER_URL, $APP_INFO); sendReply(exitCoversation($mask, $pdo), $mask, $SENDER_URL, $APP_INFO); } $found = FALSE; foreach ($list as $listUser) { if (distance($listUser["lat"], $listUser["longi"], $user["lat"], $user["longi"], "K") <= 10) { updateFriend($mask, $listUser["mask"], $pdo); updateFriend($listUser["mask"], $mask, $pdo); $user = $listUser["username"]; $found = TRUE; break; } } if ($found) { return "You have been matched up with {$user}.\n Type FSTR M <message> and send it to 77100 to start the conversation."; } else { return "Sorry no match found, please try again later."; } }
$f['number'] = '2'; } foreach ($Service1 as &$f) { $f['number'] = '0'; } foreach ($Service2 as &$f) { $f['number'] = '1'; } //print_r($Service1); foreach ($Service1 as $service => $value) { $dist = distance($lat, $Service1[$service]['branch_lat'], $lon, $Service1[$service]['branch_lng']); $Service1[$service]['dist'] = $dist; $Service1[$service]['rank'] = 0; } foreach ($Service2 as $service => $value) { $dist = distance($lat, $Service2[$service]['lat'], $lon, $Service2[$service]['lng']); $Service2[$service]['dist'] = $dist; $Service2[$service]['rank'] = 0; } usort($Service1, "cmp"); usort($Service2, "cmp"); foreach ($Service1 as &$service) { if ($service['amount_paid'] > 210000) { $service['rank'] = 3 * 10 / 100; } else { if ($service['amount_paid'] > 21000) { $service['rank'] = 2 * 10 / 100; } else { if ($service['listingType'] == 1) { $service['rank'] = 1 * 10 / 100; }
/*:: 'N' is nautical miles :*/ /*:: Worldwide cities and other features databases with latitude longitude :*/ /*:: are available at http://www.geodatasource.com :*/ /*:: :*/ /*:: For enquiries, please contact sales@geodatasource.com :*/ /*:: :*/ /*:: Official Web site: http://www.geodatasource.com :*/ /*:: :*/ /*:: GeoDataSource.com (C) All Rights Reserved 2014 :*/ /*:: :*/ /*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ function distance($lat1, $lon1, $lat2, $lon2, $unit) { $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); if ($unit == "K") { return $miles * 1.609344; } else { if ($unit == "N") { return $miles * 0.8683999999999999; } else { return $miles; } } } echo distance(-10.92832, -37.072868333333, -10.934228333333, -37.075035, "K") . " Miles<br>";
function distance($lat1, $lon1, $lat2, $lon2, $unit) { $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); if ($unit == "K") { return $miles * 1.609344; } else { if ($unit == "N") { return $miles * 0.8683999999999999; } 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>"; ?> ?>
/** * getDirectBusDistance: This function will find the distance of the direct bus **/ function getDirectBusDistance($startStop, $endStop, $startOffsetDistance, $endOffsetDistance, $xml = false) { $strRoute = ''; $strRoute = '<Distances>'; //latitude & longitude for startStop $query = "SELECT Latitude, Longitude FROM Stops WHERE (StopName ='" . $startStop . "')"; $result = mysql_query($query); $row = mysql_fetch_row($result); $lat1 = $row[0]; $lon1 = $row[1]; //latitude & longitude for firstJunction $query = "SELECT Latitude, Longitude FROM Stops WHERE (StopName ='" . $endStop . "')"; $result = mysql_query($query); $row = mysql_fetch_row($result); $lat2 = $row[0]; $lon2 = $row[1]; $dist1 = distance($lat1, $lon1, $lat2, $lon2, "K"); $totalDirectRouteDistance = $startOffsetDistance + $dist1 + $endOffsetDistance; if ($xml == true) { $strRoute = $strRoute . '<Distance>'; $strRoute = $strRoute . '<StartStop>' . $startStop . '</StartStop>'; $strRoute = $strRoute . '<EndStop>' . $endStop . '</EndStop>'; $strRoute = $strRoute . '<StartOffsetDistance>' . $startOffsetDistance . '</StartOffsetDistance>'; $strRoute = $strRoute . '<EndOffsetDistance>' . $endOffsetDistance . '</EndOffsetDistance>'; $strRoute = $strRoute . '<RouteDistance>' . $totalDirectRouteDistance . '</RouteDistance>'; $strRoute = $strRoute . '</Distance>'; $strRoute = $strRoute . '</Distances>'; //return $totalDirectRouteDistance; return $strRoute; } else { return $totalDirectRouteDistance; } //just the number }
function tratarDados($dados) { $con = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689"); if ($con !== false) { mysql_select_db('tracker', $con); $gpsSignalIndicator = 'F'; $latitudeDecimalDegrees = $dados[1]; $longitudeDecimalDegrees = $dados[2]; $latitudeHemisphere = $dados[3]; $longitudeHemisphere = $dados[4]; $speed = $dados[5]; $imei = $dados[6]; $satelliteFixStatus = 'A'; $phone = ''; $infotext = $dados[8]; $dataBem = null; $dataCliente = null; $ligado = count($dados) > 9 ? $dados[9] : 'N'; $ativo = count($dados) > 10 ? $dados[10] : 'N'; $realTime = count($dados) > 11 ? $dados[11] : ''; //D para diferencial $gpsSignalIndicator = $dados[0] == 'S' ? 'F' : 'L'; //Otavio Gomes - 200120152137 // Estava aqui o problema do crx1 so enviar o sinal S. if ($realTime == 'D') { $gpsSignalIndicator = 'D'; } else { $gpsSignalIndicator = 'R'; } $resBem = mysql_query("SELECT id, cliente, envia_sms, name, hodometro, alerta_hodometro, alerta_hodometro_saldo, limite_velocidade FROM bem WHERE imei = '{$imei}'", $con); //echo 'Ligado: '.$ligado; $dataBem = mysql_fetch_assoc($resBem); if ($resBem !== false) { $resCliente = mysql_query("SELECT id, celular, dt_ultm_sms, envia_sms, sms_acada, hour(TIMEDIFF(now(), dt_ultm_sms)) horas, minute(TIMEDIFF(now(), dt_ultm_sms)) minutos, nome, email FROM cliente WHERE id = " . $dataBem['cliente'], $con); if ($resCliente !== false) { $dataCliente = mysql_fetch_assoc($resCliente); $texto_sms_localiza = ""; $texto_sms_alerta_hodometro = ""; $texto_sms_alerta = ""; $result = mysql_query("SELECT * FROM preferencias", $con); if (mysql_num_rows($result) > 0) { while ($dataPref = mysql_fetch_assoc($result)) { if ($dataPref['nome'] == 'texto_sms_localiza') { $texto_sms_localiza = $dataPref['valor']; } if ($dataPref['nome'] == 'texto_sms_alerta_hodometro') { $texto_sms_alerta_hodometro = $dataPref['valor']; } if ($dataPref['nome'] == 'texto_sms_alerta') { $texto_sms_alerta = $dataPref['valor']; } } } $movimento = ''; if ($speed > 0) { $movimento = 'S'; if ($dataBem['limite_velocidade'] != "0" && $dataBem['limite_velocidade'] != null && $speed > $dataBem['limite_velocidade']) { if (!checkAlerta($imei, 'Limite Velocidade')) { mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Limite Velocidade')", $con); $msgEmail = "<p><b>Alerta de Limite de Velocidade: </b></p><br><p>O veículo " . $dataBem['name'] . " está trafegando com velocidade de " . $speed . " Km/h, ultrapassando o limite de velocidade definido (" . $dataBem['limite_velocidade'] . " Km/h) em " . date("d/m/Y") . " às " . date("H:i:s") . ".</p><br><i>Equipe InovarSat</i>"; enviaEmail($dataCliente['email'], "Alerta de Limite de Velocidade", $msgEmail); } } } else { $movimento = 'N'; } // CERCA VIRTUAL if ($imei != "") { $consulta = mysql_query("SELECT * FROM geo_fence WHERE imei = '{$imei}'", $con); while ($data = mysql_fetch_assoc($consulta)) { $idCerca = $data['id']; $imeiCerca = $data['imei']; $nomeCerca = $data['nome']; $coordenadasCerca = $data['coordenadas']; $resultCerca = $data['tipo']; $tipoEnvio = $data['tipoEnvio']; $lat_point = $latitudeDecimalDegrees; $lng_point = $longitudeDecimalDegrees; $exp = explode("|", $coordenadasCerca); if (count($exp) < 5) { $strExp = explode(",", $exp[0]); $strExp1 = explode(",", $exp[2]); } else { $int = count($exp) / 2; $strExp = explode(",", $exp[0]); $strExp1 = explode(",", $exp[$int]); } $lat_vertice_1 = $strExp[0]; $lng_vertice_1 = $strExp[1]; $lat_vertice_2 = $strExp1[0]; $lng_vertice_2 = $strExp1[1]; if ($lat_vertice_1 < $lat_point or $lat_point < $lat_vertice_2 and $lng_point < $lng_vertice_1 or $lng_vertice_2 < $lng_point) { $result = '0'; $situacao = 'fora'; } else { $result = '1'; $situacao = 'dentro'; } if ($result == 0 and $movimento == 'S') { if (!checkAlerta($imei, 'Cerca Violada')) { mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Cerca Violada')", $con); if ($tipoEnvio == 0) { # Convert the GPS coordinates to a human readable address /*$tempstr = "http://maps.google.com/maps/geo?q=$lat_point,$lng_point&oe=utf-8&sensor=true&key=ABQIAAAAFd56B-wCWVpooPPO7LR3ihTz-K-sFZ2BISbybur6B4OYOOGbdRShvXwdlYvbnwC38zgCx2up86CqEg&output=csv"; //output = csv, xml, kml, json $rev_geo_str = file_get_contents($tempstr); $rev_geo_str = preg_replace("/\"/","", $rev_geo_str); $rev_geo = explode(',', $rev_geo_str); $logradouro = $rev_geo[2] .",". $rev_geo[3] ;*/ /*$consulta1 = mysql_query("SELECT a.*, b.* FROM cliente a INNER JOIN bem b ON a.id = b.cliente WHERE b.imei = '$imei'", $con); while($data = mysql_fetch_assoc($consulta1)) { $emailDestino = $data['email']; $nameBem = $data['name']; $msgEmail = "<p><b>Alerta de Violação de Perímetro:</b></p><br><p>O veículo ". $nameBem .", está ". $situacao ." do perímetro ". $nomeCerca .", as ". date("H:i:s") ." do dia ". date("d/m/Y") . ".</p><br><i>Equipe InovarSat</i>"; enviaEmail($emailDestino, "Alerta de Violação de Perímetro", $msgEmail); }*/ $json = json_decode(file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=" . $lat_point . "," . $lng_point . "&sensor=false")); if (isset($json->status) && $json->status == 'OK') { $address = $json->results[0]->formatted_address; $address = utf8_decode($address); } //else echo $json->status; $emailDestino = $dataCliente['email']; $nameBem = $dataBem['name']; $msgEmail = "<p><b>Alerta de Violação de Perímetro: </b></p><br><p>O veículo " . $nameBem . ", está " . $situacao . " do perímetro " . $nomeCerca . ", transitando na " . $address . " às " . date("H:i:s") . " do dia " . date("d/m/Y") . ".</p><br><i>Equipe InovarSat</i>"; enviaEmail($emailDestino, "Alerta de Violação de Perímetro", $msgEmail); } } } } } //FIM CERCA VIRTUAL # Write it to the database... if ($gpsSignalIndicator != 'L' && !empty($latitudeDecimalDegrees)) { $gpsLat = $latitudeDecimalDegrees; //gprsToGps($latitudeDecimalDegrees, $latitudeHemisphere) $gpsLon = $longitudeDecimalDegrees; //gprsToGps($longitudeDecimalDegrees, $longitudeHemisphere) $gpsLatAnt = 0; $gpsLatHemAnt = ''; $gpsLonAnt = 0; $gpsLonHemAnt = ''; $alertaACadaSaldo = 0; $resLocAtual = mysql_query("SELECT id, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere FROM loc_atual WHERE imei = '{$imei}' LIMIT 1", $con); $numRows = mysql_num_rows($resLocAtual); if ($numRows == 0) { mysql_query("INSERT INTO loc_atual (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, converte, ligado) VALUES (now(), '{$imei}', '{$phone}', '{$satelliteFixStatus}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$infotext}', '{$gpsSignalIndicator}', 0, '{$ligado}')", $con); } else { mysql_query("UPDATE loc_atual SET date = now(), phone = '{$phone}', satelliteFixStatus = '{$satelliteFixStatus}', latitudeDecimalDegrees = '{$latitudeDecimalDegrees}', latitudeHemisphere = '{$latitudeHemisphere}', longitudeDecimalDegrees = '{$longitudeDecimalDegrees}', longitudeHemisphere = '{$longitudeHemisphere}', speed = '{$speed}', infotext = '{$infotext}', gpsSignalIndicator = '{$gpsSignalIndicator}', converte = 0, ligado = '{$ligado}' WHERE imei = '{$imei}'", $con); } $distance = 0; try { $bemId = $dataBem['id']; $countGeoDistance = mysql_query("SELECT bem FROM geo_distance WHERE bem = {$bemId}", $con); if ($countGeoDistance === false || mysql_num_rows($countGeoDistance) == 0) { mysql_query("INSERT INTO geo_distance (bem, tipo) VALUES({$bemId}, 'I')", $con); mysql_query("INSERT INTO geo_distance (bem, tipo) VALUES({$bemId}, 'F')", $con); } /*envio de sms*/ if ($dataCliente['envia_sms'] == 'S' && $dataBem['envia_sms'] == 'S' && !empty($dataCliente['celular']) && !empty($dataCliente['sms_acada'])) { if (empty($dataCliente['dt_ultm_sms'])) { mysql_query("UPDATE cliente SET dt_ultm_sms = convert_tz(now(), 'GMT', 'Brazil/East') WHERE id = " . $dataCliente['id'], $con); } else { $horas = $dataCliente['horas']; $minutos = $dataCliente['minutos']; if (!empty($horas)) { $horas = $horas * 60; } $tempoTotal = $horas + $minutos; if ($tempoTotal > $dataCliente['sms_acada']) { $json = json_decode(file_get_contents("http://maps.google.com/maps/api/geocode/json?sensor=false&latlng={$gpsLat},{$gpsLon}&language=es-ES")); if (isset($json->status) && $json->status == 'OK' && isset($json->results[0]->formatted_address)) { $address = $json->results[0]->formatted_address; $address = utf8_decode($address); $aDataCliente = split(' ', $dataCliente['nome']); $msg = $texto_sms_localiza; $msg = str_replace("#CLIENTE", $aDataCliente[0], $msg); $msg = str_replace("#VEICULO", $dataBem['name'], $msg); $msg = str_replace("#LOCALIZACAO", $address, $msg); $msg = str_replace(' ', '+', $msg); sendSMS($dataCliente['celular'], $msg, ''); if ($retorno < 0) { mysql_query("INSERT INTO controle(texto) VALUES('envio de sms retorno: {$retorno}')", $con); } else { mysql_query("UPDATE cliente SET dt_ultm_sms = convert_tz(now(), 'GMT', 'Brazil/East') WHERE id = " . $dataCliente['id'], $con); } } } } } if ($movimento == 'S') { $resGeoDistance = mysql_query("SELECT parou FROM geo_distance WHERE bem = {$bemId} AND tipo = 'I'", $con); if ($resGeoDistance !== false) { $dataGeoDistance = mysql_fetch_assoc($resGeoDistance); if ($dataGeoDistance['parou'] == 'S' || empty($dataGeoDistance['parou'])) { mysql_query("UPDATE geo_distance SET latitudeDecimalDegrees = '{$latitudeDecimalDegrees}', latitudeHemisphere = '{$latitudeHemisphere}', longitudeDecimalDegrees = '{$longitudeDecimalDegrees}', longitudeHemisphere = '{$longitudeHemisphere}', parou = 'N' WHERE bem = {$bemId} AND tipo = 'I'", $con); } } } else { $resGeoDistance = mysql_query("SELECT latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere FROM geo_distance WHERE bem = {$bemId} AND tipo = 'I'", $con); if (mysql_num_rows($resGeoDistance) > 0) { $update = mysql_query("UPDATE geo_distance SET latitudeDecimalDegrees = '{$latitudeDecimalDegrees}', latitudeHemisphere = '{$latitudeHemisphere}', longitudeDecimalDegrees = '{$longitudeDecimalDegrees}', longitudeHemisphere = '{$longitudeHemisphere}', parou = 'S' WHERE bem = {$bemId} AND tipo = 'I'", $con); $dataGeoDistance = mysql_fetch_assoc($resGeoDistance); $gpsLatAnt = !strstr($dataGeoDistance['latitudeDecimalDegrees'], "-") ? gprsToGps($dataGeoDistance['latitudeDecimalDegrees'], $dataGeoDistance['latitudeHemisphere']) : $dataGeoDistance['latitudeDecimalDegrees']; $gpsLonAnt = !strstr($dataGeoDistance['longitudeDecimalDegrees'], "-") ? gprsToGps($dataGeoDistance['longitudeDecimalDegrees'], $dataGeoDistance['longitudeHemisphere']) : $dataGeoDistance['longitudeDecimalDegrees']; // $gpsLatAnt = gprsToGps($dataGeoDistance['latitudeDecimalDegrees'], $dataGeoDistance['latitudeHemisphere']); //$dataGeoDistance['latitudeDecimalDegrees']; // $gpsLonAnt = gprsToGps($dataGeoDistance['longitudeDecimalDegrees'], $dataGeoDistance['longitudeHemisphere']); //$dataGeoDistance['longitudeDecimalDegrees']; if ($gpsLatAnt != $gpsLat) { if ($gpsLatAnt != 0 && $gpsLonAnt != 0) { $geoDistance = distance($gpsLatAnt, $gpsLonAnt, $gpsLat, $gpsLon); //$strDistance = $json->rows[0]->elements[0]->distance->value; $distance = (int) $geoDistance; //(int)($geoDistance*1000) //echo "******************************IMEI: ". $imei ." | Lat/Long Antiga: ". $gpsLatAnt . ", ". $gpsLonAnt ." | Lat/Long Atual: ". $gpsLat .", ". $gpsLon ." | Geodistance : ". $geoDistance ." | Inteiro: ". $distance ."<br>"; $alertaACada = $dataBem['alerta_hodometro']; $alertaACadaSaldo = $dataBem['alerta_hodometro_saldo']; $alertaACadaSaldo = $alertaACadaSaldo - $distance; if ($alertaACadaSaldo <= 0 && $alertaACada > 0) { $msg = $texto_sms_alerta_hodometro; $msg = str_replace("#CLIENTE", $dataCliente['nome'], $msg); $msg = str_replace("#VEICULO", $dataBem['name'], $msg); $msg = str_replace("#HODOMETRO", $alertaACada, $msg); $msg = str_replace(' ', '+', $msg); //sendSMS($dataCliente['celular'], $msg, ''); $msgEmail = "<p><b>Quilometragem atingida: </b></p><br><p>O veículo " . $dataBem['name'] . " atingiu a quilometragem de " . $dataBem['hodometro'] . "Km rodados às " . date("H:i:s") . " do dia " . date("d/m/Y") . ".</p><br><i>Equipe InovarSat</i>"; //echo $msgEmail; // enviaEmail($dataCliente['email'], 'Hodômetro - Quilometragem Atingida', $msgEmail); $alertaACadaSaldo = $alertaACada; } // $alertaACadaSaldo = (int)$alertaACadaSaldo;//(int)$alertaACadaSaldo/1000 } } } } } catch (Exception $e) { mysql_query("INSERT INTO controle (texto) VALUES ({$e->getMessage}())", $con); } if (!empty($latitudeDecimalDegrees)) { mysql_query("INSERT INTO gprmc (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, km_rodado, converte, ligado) VALUES (now(), '{$imei}', '{$phone}', '{$satelliteFixStatus}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$infotext}', '{$gpsSignalIndicator}', {$distance}, 0, '{$ligado}')", $con); } if ($alertaACadaSaldo == 0) { mysql_query("UPDATE bem set date = now(), status_sinal = 'R', movimento = '{$movimento}', hodometro = hodometro+{$distance} WHERE imei = '{$imei}'", $con); } else { mysql_query("UPDATE bem set date = now(), status_sinal = 'R', movimento = '{$movimento}', hodometro = hodometro+{$distance}, alerta_hodometro_saldo = {$alertaACadaSaldo} WHERE imei = '{$imei}'", $con); } /* if($numRows == 0){ mysql_query("INSERT INTO loc_atual (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator) VALUES (now(), '$imei', '$phone', '$satelliteFixStatus', '$latitudeDecimalDegrees', '$latitudeHemisphere', '$longitudeDecimalDegrees', '$longitudeHemisphere', '$speed', '$infotext', '$gpsSignalIndicator')", $cnx); } else { mysql_query("UPDATE loc_atual set date = now(), phone = '$phone', satelliteFixStatus = '$satelliteFixStatus', latitudeDecimalDegrees = '$latitudeDecimalDegrees', latitudeHemisphere = '$latitudeHemisphere', longitudeDecimalDegrees = '$longitudeDecimalDegrees', longitudeHemisphere = '$longitudeHemisphere', speed = '$speed', infotext = '$infotext', gpsSignalIndicator = '$gpsSignalIndicator' where imei = '$imei'", $cnx); } */ } else { $resLocAtual = mysql_query("SELECT id, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere FROM loc_atual WHERE imei = '{$imei}' LIMIT 1", $con); $numRows = mysql_num_rows($resLocAtual); if ($numRows == 0) { mysql_query("INSERT INTO loc_atual (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, converte, ligado) VALUES (now(), '{$imei}', '{$phone}', '{$satelliteFixStatus}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$infotext}', '{$gpsSignalIndicator}', 0, '{$ligado}')", $con); } else { mysql_query("UPDATE loc_atual SET date = now(), phone = '{$phone}', satelliteFixStatus = '{$satelliteFixStatus}', latitudeDecimalDegrees = '{$latitudeDecimalDegrees}', latitudeHemisphere = '{$latitudeHemisphere}', longitudeDecimalDegrees = '{$longitudeDecimalDegrees}', longitudeHemisphere = '{$longitudeHemisphere}', speed = '{$speed}', infotext = '{$infotext}', gpsSignalIndicator = '{$gpsSignalIndicator}', converte = 0, ligado = '{$ligado}' WHERE imei = '{$imei}'", $con); } if (!empty($latitudeDecimalDegrees)) { mysql_query("INSERT INTO gprmc (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, km_rodado, converte, ligado) VALUES (now(), '{$imei}', '{$phone}', '{$satelliteFixStatus}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$infotext}', '{$gpsSignalIndicator}', 0, 0, '{$ligado}')", $con); } mysql_query("UPDATE bem set date = now(), status_sinal = 'S' WHERE imei = '{$imei}'", $con); } if (!empty($ligado)) { mysql_query("UPDATE bem SET ligado = '{$ligado}' where imei = '{$imei}'", $con); } # Now check to see if we need to send any alerts. if ($infotext != "tracker") { $msg = $texto_sms_alerta; $msg = str_replace("#CLIENTE", $dataCliente['nome'], $msg); $msg = str_replace("#VEICULO", $dataBem['name'], $msg); $res = mysql_query("SELECT responsible FROM bem WHERE imei='{$imei}'", $con); while ($data = mysql_fetch_assoc($res)) { switch ($infotext) { case "dt": if (!checkAlerta($imei, 'Rastreador Desat.')) { $body = "Disable Track OK"; $msg = str_replace("#TIPOALERTA", "Rastreador Desabilitado", $msg); mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Rastreador Desat.')", $con); } break; case "et": if (!checkAlerta($imei, 'Alarme Parado')) { $body = "Stop Alarm OK"; $msg = str_replace("#TIPOALERTA", "Alarme parado", $msg); mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Alarme Parado')", $con); } break; case "gt": if (!checkAlerta($imei, 'Alarme Movimento')) { $body = "Move Alarm set OK"; $msg = str_replace("#TIPOALERTA", "Alarme de Movimento ativado", $msg); mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Alarme Movimento')", $con); } break; case "help me": if (!checkAlerta($imei, 'SOS!')) { $body = "Help!"; mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'SOS!')", $con); $msg = str_replace("#TIPOALERTA", "SOS", $msg); } //Envia comando de resposta: alerta recebido //$send_cmd = "**,imei:". $conn_imei .",E"; //socket_send($socket, $send_cmd, strlen($send_cmd), 0); //printLog($fh, "Comando de resposta (help me): " . $send_cmd . " imei: " . $conn_imei); break; case "ht": if (!checkAlerta($imei, 'Alarme Velocidade')) { $body = "Speed alarm set OK"; $msg = str_replace("#TIPOALERTA", "Alarme de velocidade ativado", $msg); mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Alarme Velocidade')", $con); } break; case "it": $body = "Timezone set OK"; break; case "low battery": if (!checkAlerta($imei, 'Bateria Fraca')) { $body = "Low battery!\nYou have about 2 minutes..."; $msg = str_replace("#TIPOALERTA", "Bateria fraca, voce tem 2 minutos", $msg); mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Bateria Fraca')", $con); } //Envia comando de resposta: alerta recebido $send_cmd = "**,imei:" . $conn_imei . ",E"; socket_send($socket, $send_cmd, strlen($send_cmd), 0); //printLog($fh, "Comando de resposta (low battery): " . $send_cmd . " imei: " . $conn_imei); break; case "move": if (!checkAlerta($imei, 'Movimento')) { $body = "Move Alarm!"; $msg = str_replace("#TIPOALERTA", "Seu veiculo esta em movimento", $msg); mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Movimento')", $con); } //Envia comando de resposta: alerta recebido $send_cmd = "**,imei:" . $conn_imei . ",E"; socket_send($socket, $send_cmd, strlen($send_cmd), 0); //printLog($fh, "Comando de resposta (move): " . $send_cmd . " imei: " . $conn_imei); break; case "nt": $body = "Returned to SMS mode OK"; break; case "speed": if (!checkAlerta($imei, 'Velocidade')) { $body = "Speed alarm!"; $msg = str_replace("#TIPOALERTA", "Seu veiculo ultrapassou o limite de velocidade", $msg); mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Velocidade')", $con); } //Envia comando de resposta: alerta recebido $send_cmd = "**,imei:" . $conn_imei . ",E"; socket_send($socket, $send_cmd, strlen($send_cmd), 0); //printLog($fh, "Comando de resposta (speed): " . $send_cmd . " imei: " . $conn_imei); break; case "stockade": if (!checkAlerta($imei, 'Cerca')) { $body = "Geofence Violation!"; $msg = str_replace("#TIPOALERTA", "Seu veiculo saiu da cerca virtual", $msg); mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Cerca')", $con); } //Envia comando de resposta: alerta recebido $send_cmd = "**,imei:" . $conn_imei . ",E"; socket_send($socket, $send_cmd, strlen($send_cmd), 0); //printLog($fh, "Comando de resposta (stockade): " . $send_cmd . " imei: " . $conn_imei); break; case "door alarm": if (!checkAlerta($imei, 'Porta')) { $body = "Open door!"; mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Porta')", $con); } //Envia comando de resposta: alerta recebido $send_cmd = "**,imei:" . $conn_imei . ",E"; socket_send($socket, $send_cmd, strlen($send_cmd), 0); //printLog($fh, "Comando de resposta (door alarm): " . $send_cmd . " imei: " . $conn_imei); break; case "acc alarm": if (!checkAlerta($imei, 'Alarme Disparado')) { $body = "ACC alarm!"; $msg = str_replace("#TIPOALERTA", "Alarme disparado", $msg); mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Alarme Disparado')", $con); } //Envia comando de resposta: alerta recebido $send_cmd = "**,imei:" . $conn_imei . ",E"; socket_send($socket, $send_cmd, strlen($send_cmd), 0); //printLog($fh, "Comando de resposta (acc alarm): " . $send_cmd . " imei: " . $conn_imei); break; case "acc off": $body = "Ignicao Desligada!"; $msg = str_replace("#TIPOALERTA", "Seu veiculo esta com a chave desligada", $msg); //mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Ignição')", $cnx); mysql_query("UPDATE bem SET ligado = 'N' where imei = '{$imei}'", $con); //Envia comando de resposta: alerta recebido $send_cmd = "**,imei:" . $conn_imei . ",E"; socket_send($socket, $send_cmd, strlen($send_cmd), 0); //printLog($fh, "Comando de resposta (acc alarm): " . $send_cmd . " imei: " . $conn_imei); break; case "acc on": $body = "Ignicao Ligada!"; $msg = str_replace("#TIPOALERTA", "Seu veiculo esta com a chave ligada", $msg); //mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Ignição')", $cnx); mysql_query("UPDATE bem SET ligado = 'S' where imei = '{$imei}'", $cnx); //Envia comando de resposta: alerta recebido $send_cmd = "**,imei:" . $conn_imei . ",E"; socket_send($socket, $send_cmd, strlen($send_cmd), 0); //printLog($fh, "Comando de resposta (acc alarm): " . $send_cmd . " imei: " . $conn_imei); break; } //switch $msg = str_replace(' ', '+', $msg); //if($dataCliente['envia_sms'] == 'S' && $dataBem['envia_sms'] == 'S' && $infotext != 'acc on'&& $infotext != 'acc off' && $infotext != 'et') // sendSMS($dataCliente['celular'], $msg, ''); //Enviando e-mail de alerta /*$headers = "From: $email_from" . "\r\n" . "Reply-To: $email_from" . "\r\n"; $responsible = $data['responsible']; $rv = mail($responsible, "Tracker - $imei", $body, $headers);*/ if (isset($body)) { enviaEmail($dataCliente['email'], "Rastreador - {$imei}", $body); } } //while } } else { echo 'Cliente não encontrado. Erro: ' . mysql_error($con); } } else { echo 'Veículo não encontrado. Erro: ' . mysql_error($con); } mysql_close($con); } else { echo 'Não foi possivel conectar ao banco. Erro: ' . mysql_error(); } }
function getDistance($userId, $shopId) { if (!$shopId) { return array(); } static $cache = array(); if (!isset($cache[$userId])) { $cache[$userId] = array(); } if (!isset($cache[$userId][$shopId])) { //$tmp=mysql_fetch_assoc(query($sql="select shop_id from panelie_user_shop_link where id=$shopId")); $shop = getShopPosition($shopId); $home = getHomePosition($userId); $cache[$userId][$shopId] = distance($shop, $home); } return $cache[$userId][$shopId] > 0 ? array('distance' => $cache[$userId][$shopId]) : array(); }
// local integer = lpeg.P('-')^0 * lpeg.R('09')^1 / tonumber // local pair = '(' * integer * ', ' * integer * ')' // local points = pair * ' ' * pair // // local ax, ay, bx, by = points:match(s) // // // Not that different for just breaking up the regex: // // $integer = '([-]?\d+)'; // $point = "\($integer, $integer\)"; // $regex = "#$point $point#"; // // (I'd say better, but still has wrong types) function distance($s) { preg_match('#\\(([-]?\\d+), ([-]?\\d+)\\) \\(([-]?\\d+), ([-]?\\d+)\\)#', $s, $matches); $ax = (int) $matches[1]; $ay = (int) $matches[2]; $bx = (int) $matches[3]; $by = (int) $matches[4]; $dx = max($ax, $bx) - min($ax, $bx); $dy = max($ay, $by) - min($ay, $by); echo sqrt($dx * $dx + $dy * $dy) . PHP_EOL; } $filename = strpos($argv[0], 'Matthew\\Dropbox') !== false ? 'data.txt' : $argv[1]; foreach (file($filename) as $line) { if (trim($line) !== '') { distance($line); } }
function getDistance($c1, $c2) { return distance(getCoordinates($c1), getCoordinates($c2)); }
//$json_array as $json) $lastpoint = $json->features[0]->geometry->coordinates; $thispoint; if (is_array($json->features)) { foreach ($json->features as $feature) { // echo $feature->geometry->coordinates[0]; $latitude = $feature->geometry->coordinates[1]; $latceil = ceil($latitude); $latfloor = floor($latitude); $longitude = $feature->geometry->coordinates[0]; $lngceil = ceil($longitude); $lngfloor = floor($longitude); $mile = 0; // $lastpoint = $feature->geometry->coordinates; $thispoing = $feature->geometry->coordinates; $mile = distance($lastpoint[1], $lastpoint[0], $thispoing[1], $thispoing[0], "K"); // echo $lastpoint[1]."___".$lastpoint[0]."___".$thispoing[1]."___".$thispoing[0]."___"; // echo $mile."___----___"; $lastpoint = $thispoing; $sql = "SELECT *, (((acos(sin(({$latitude}*pi()/180)) * sin((`latitude`*pi()/180))+cos(({$latitude}*pi()/180)) * cos((`latitude`*pi()/180)) * cos((({$longitude} - `longitude`)*pi()/180))))*180/pi())*60*1.1515) AS `distance` \n\tFROM zipcode\n\tWHERE (\n\tlatitude BETWEEN '{$latfloor}' AND '{$latceil}' \n\tAND \n\tlongitude BETWEEN '{$lngceil}' AND '{$lngfloor}'\n\t)\n\tHAVING distance < {$distance} ORDER BY distance ASC LIMIT 1"; //$sql = "SELECT *, (((acos(sin(($latitude*pi()/180)) * sin((`latitude`*pi()/180))+cos(($latitude*pi()/180)) * cos((`latitude`*pi()/180)) * cos((($longitude - `longitude`)*pi()/180))))*180/pi())*60*1.1515) AS `distance` FROM zipcode HAVING distance < $distance ORDER BY distance ASC LIMIT 1"; //$theresult[]=[$latitude,$longitude]; $result = mysqli_query($con, $sql) or die("Error: " . mysqli_error($con)); while ($row = mysqli_fetch_array($result)) { // //echo "lsl"; $city = $row['primary_city']; $zip = $row['zip']; $lat = $row['latitude']; $lon = $row['longitude']; //echo $city; //$theresult[]=$city;
/** @param $start<Location> the starting location (address) @param $end<Location> the ending location (address) */ function findDirPath($start, $end, $start_stations, $end_stations) { $debug = false; if ($debug) { echo "findDirPath<br/>"; } if ($start == $end) { return "same"; } if (distance($start, $end) < 0.25) { return "walk"; } $WALKING_SPEED = 2 / 3600; // determine original bounding box $original_box = new Box($start->point, $end->point); // create end marker $end_name = $end->name; if ($end_name == "") { $end_name = $end->getAddressString(); } $end_marker = new Marker($end->point->lat, $end->point->lng, "end", $end_name); if ($debug) { echo "end marker = "; $end_marker->printInfo(); } // create array of paths $open = array(); $start_name = $start->name; if ($start_name == "") { $start_name = $start->getAddressString(); } $start_marker = new Marker($start->point->lat, $start->point->lng, "start", $start_name); if ($debug) { echo "start marker = "; $start_marker->printInfo(); } foreach ($start_stations as $station) { $segment = new Segment($start_marker, $station->marker, $station->marker->lines, $station->getDistance() / $WALKING_SPEED, "walking"); $visited = array(); $visited[] = $station->marker; $new_box = new Box($station->marker->point, $end_marker->point); $path = new Path2($segment, $new_box, $visited); $area = $new_box->getArea(); $array = $open["{$area}"]; if ($array == null) { $array = array(); } $array[] = $path; #echo "adding $array<br/>"; $open["{$area}"] = $array; } return findPath($open, $end_stations, $end_marker); }
function kmeans_clustering($data, $cPositions, &$clusters) { $nChanges = 0; foreach ($data as $dataKey => $value) { $minDistance = null; $cluster = null; foreach ($cPositions as $k => $position) { $distance = distance($value, $position); if (is_null($minDistance) || $minDistance > $distance) { $minDistance = $distance; $cluster = $k; } } if (!isset($clusters[$dataKey]) || $clusters[$dataKey] != $cluster) { $nChanges++; } $clusters[$dataKey] = $cluster; } return $nChanges; }
public function distanceTo(Locations $location_to) { return round(distance($this->lat, $this->lng, $location_to->lat, $location_to->lng), 2); }
return 0; } $word1len = mb_strlen($word1); $word2len = mb_strlen($word2); if (!$word1len) { return $word2len; } if (!$word2len) { return $word1len; } $distance = []; for ($i = 0; $i <= $word1len; $i++) { $distance[$i][0] = $i; } for ($j = 0; $j <= $word2len; $j++) { $distance[0][$j] = $j; } for ($i = 1; $i <= $word1len; $i++) { for ($j = 1; $j <= $word2len; $j++) { $cost = mb_substr($word1, $i - 1, 1) === mb_substr($word2, $j - 1, 1) ? 0 : 1; $distance[$i][$j] = min($distance[$i - 1][$j] + 1, $distance[$i][$j - 1] + 1, $distance[$i - 1][$j - 1] + $cost); } } return $distance[$word1len][$word2len]; } $data = [['', '', 0], ['kot', '', 3], ['', 'pies', 4], ['ptak', 'ptak', 0], ['granat', 'granit', 1], ['orczyk', 'oracz', 3], ['marka', 'ariada', 4], ['łabądź', 'łabędź', 1], ['łabądź', 'łabędz', 2], ['gęś', 'kęs', 2]]; foreach ($data as $input) { $distance = distance($input[0], $input[1]); echo $distance === $input[2] ? '[OK]' : '[FAIL]'; echo ' ' . $input[0] . ':' . $input[1] . ' expected: ' . $input[2] . ', result: ' . $distance . PHP_EOL; }
$map->height = '431'; // Lets add a marker now $marker = new Marker(['position' => $coord, 'title' => 'My Home Town']); // Lets add a marker now $circle = new Circle(['center' => $coord, 'radius' => 3000]); // Add marker to the map $map->addOverlay($marker); $map->addOverlay($circle); $map2 = new Map(['center' => $coord, 'zoom' => 14]); $map2->width = '100%'; $map2->height = '176'; // Lets add a marker now $marker2 = new Marker(['position' => $coord, 'title' => 'My Home Town']); // Add marker to the map $map2->addOverlay($marker2); echo distance($model->location->lat, $model->location->lng, $model2->location->lat, $model2->location->lng); ?> <?php echo Yii::$app->request->url == '/index' ? 'yes' : 'no'; ?> <div class="site-index"> <div class="body-content"> <div class="card_container record-md grid-item fadeInUp animated" id="card_container" style="float:none;"> <a href="<?php echo Url::to('/services'); ?> "> <div class="media-area"> <div class="image">
echo "<p class='box'>Grid reports that agent is at position: " . $curposResult . "</p>\n"; // first, read position again, just to see what we get /* echo "This is how Destination Cube looks like: <br \>\n"; var_dump($destCube); echo "<br />\n"; */ $currentPosition = explode(",", trim($curposResult, " ()<>")); /* echo "Distance comparison: Current Position:<br />\n"; var_dump($currentPosition); echo "Target Cube<br />\n"; var_dump($targetCube); echo "<br />\n"; */ $distance = distance($cubePosition, $currentPosition); if ($distance < 1.1) { echo "<p class='box success'>Within rounding errors of " . $destCube['Name'] . ", distance is merely {$distance} m; let's sit down</p>\n"; // if we're close enough, sit on it $sitResult = callURL($masterController['PermURL'], "npc=" . $agent['OwnerKey'] . "&command=osNpcSit&key=" . $destCube['UUID'], "&integer=" . OS_NPC_SIT_NOW); echo "Result from sitting: " . $sitResult . "<br />\n"; } elseif ($distance < 2.5) { echo "<p class='box warning'>Very close to " . $destCube['Name'] . ", distance is now {$distance} m</p>\n"; } else { echo "<p class='box warning'>Still {$distance} m away from " . $destCube['Name'] . " (" . $cubePosition[0] . "," . $cubePosition[1] . "," . $cubePosition[2] . ")</p>\n"; } $time_end = microtime(true); $time = $time_end - $time_start; echo "<p>CPU time used: {$time} seconds</p>\n"; // Now place a button to save/export to CSV or XML ?>