PHP - Check Distance Between Previous And Current Gps Position
Hi
i am looping through some history data i have collected via soap. i have the data in an array containing lat, lon and timestamp. Code: [Select] foreach($history['data'] as $record) { echo 'add(jQuery(this), number += 1, "' . date("d-m-Y @ h:i:s",$record['timestamp']) . '", "map_post.php?n=' . $name . 'u=' . $history['user'] . '", "' . $history['user'] . '", "' . $record['latitude'] . '", "' . $record['longitude'] . '");'; } i wondered it it would be possible to check if each position is within say 300 metres of the last position and if so dont display it? Similar TutorialsI'm not sure if this is a pure mySQL question or if it's more PHP but I thought this seemed like a good place to ask it.
I have a table which has data stored into it twice daily. The data stored is the timestamp, an account_ID, and the number of followers.
I am trying to add another field of "gains_losses". This should look at the previous entry for that account_ID, find out the followers data, and then find out the difference between the data being submitted today.
How would you go about doing this? I'm a bit stuck because I can't do it based on the date previously, and the times can change so I can't do a search for "Where time = this minus one day".
Here's a screenie of the table, you can see the account_ID repeats often as these are entries for each of these accounts.
Hi all, Is there a function or method to delete element from current position in array without knowing the index. For example: $ar = array( 1, 2, 3, "test", 4, 5, "test2" ); while( $v = current( $ar ) ) { if( key( $ar ) == "test" ) { // remove element from the array where key equals "test" // i could count every cycle and splice from that index but i wonder can that be done without it // i am looking at the php array functions but i can't find any that will delete from element from current position in array echo 'key( $ar ) je test. key( $ar ): ' . key( $ar ); } next( $ar ); } One thing that i don't understand is that when i run example above the "test" key is found and when i echo it it gives me 0. Most blogs/forums I know (such as this one ) allow not only for the uploading and inclusion of images in a post (this I know how how to implement), but also the luxury of automatically
inserting the image at the precise place the cursor was in the post when the user clicked the "image" icon in order to upload.
This involves keeping track of the cursor’s whereabouts in a text field and I have no idea about how to do it with php or html. How is it done ? Where should I learn how to implement this in my made-from-scratch blog ?
Is there a function to check the name of the current page? Such as login.php or something like that? If not, does anyone have a custom function already created? Hi, I need to insert some code into my current form code which will check to see if a username exist and if so will display an echo message. If it does not exist will post the form (assuming everything else is filled in correctly). I have tried some code in a few places but it doesn't work correctly as I get the username message exist no matter what. I think I am inserting the code into the wrong area, so need assistance as to how to incorporate the username check code. $sql="select * from Profile where username = '$username'; $result = mysql_query( $sql, $conn ) or die( "ERR: SQL 1" ); if(mysql_num_rows($result)!=0) { process form } else { echo "That username already exist!"; } the current code of the form <?PHP //session_start(); require_once "formvalidator.php"; $show_form=true; if (!isset($_POST['Submit'])) { $human_number1 = rand(1, 12); $human_number2 = rand(1, 38); $human_answer = $human_number1 + $human_number2; $_SESSION['check_answer'] = $human_answer; } if(isset($_POST['Submit'])) { if (!isset($_SESSION['check_answer'])) { echo "<p>Error: Answer session not set</p>"; } if($_POST['math'] != $_SESSION['check_answer']) { echo "<p>You did not pass the human check.</p>"; exit(); } $validator = new FormValidator(); $validator->addValidation("FirstName","req","Please fill in FirstName"); $validator->addValidation("LastName","req","Please fill in LastName"); $validator->addValidation("UserName","req","Please fill in UserName"); $validator->addValidation("Password","req","Please fill in a Password"); $validator->addValidation("Password2","req","Please re-enter your password"); $validator->addValidation("Password2","eqelmnt=Password","Your passwords do not match!"); $validator->addValidation("email","email","The input for Email should be a valid email value"); $validator->addValidation("email","req","Please fill in Email"); $validator->addValidation("Zip","req","Please fill in your Zip Code"); $validator->addValidation("Security","req","Please fill in your Security Question"); $validator->addValidation("Security2","req","Please fill in your Security Answer"); if($validator->ValidateForm()) { $con = mysql_connect("localhost","uname","pw") or die('Could not connect: ' . mysql_error()); mysql_select_db("beatthis_beatthis") or die(mysql_error()); $FirstName=mysql_real_escape_string($_POST['FirstName']); //This value has to be the same as in the HTML form file $LastName=mysql_real_escape_string($_POST['LastName']); //This value has to be the same as in the HTML form file $UserName=mysql_real_escape_string($_POST['UserName']); //This value has to be the same as in the HTML form file $Password= md5($_POST['Password']); //This value has to be the same as in the HTML form file $Password2= md5($_POST['Password2']); //This value has to be the same as in the HTML form file $email=mysql_real_escape_string($_POST['email']); //This value has to be the same as in the HTML form file $Zip=mysql_real_escape_string($_POST['Zip']); //This value has to be the same as in the HTML form file $Birthday=mysql_real_escape_string($_POST['Birthday']); //This value has to be the same as in the HTML form file $Security=mysql_real_escape_string($_POST['Security']); //This value has to be the same as in the HTML form file $Security2=mysql_real_escape_string($_POST['Security2']); //This value has to be the same as in the HTML form file $sql="INSERT INTO Profile (`FirstName`,`LastName`,`Username`,`Password`,`Password2`,`email`,`Zip`,`Birthday`,`Security`,`Security2`) VALUES ('$FirstName','$LastName','$UserName','$Password','$Password2','$email','$Zip','$Birthday','$Security','$Security2')"; //echo $sql; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } else{ mail('email@gmail.com','A profile has been submitted!',$FirstName.' has submitted their profile',$body); echo "<h3>Your profile information has been submitted successfully.</h3>"; } mysql_close($con); $show_form=false; } else { echo "<h3 class='ErrorTitle'>Validation Errors:</h3>"; $error_hash = $validator->GetErrors(); foreach($error_hash as $inpname => $inp_err) { echo "<p class='errors'>$inpname : $inp_err</p>\n"; } } } if(true == $show_form) { ?> i wanting users to be able to update there email address and check to see if the new email already exists. if the email is the same as current email ignore the check. i have no errors showing up but if I enter a email already in the db it still accepts the new email instead of bringing the back the error message. Code: [Select] // email enterd from form // $email=$_POST['email']; $queryuser=mysql_query("SELECT * FROM members WHERE inv='$ivn' ") or die (mysql_error()); while($info = mysql_fetch_array( $queryuser )) { $check=$info['email']; // gets current email // } if($check!=$email){ // if check not equal to $email check the new email address already exists// $queryuser=mysql_query("SELECT * FROM members WHERE email='$email' "); //$result=mysql_query($sql); $checkuser=mysql_num_rows($queryuser); if($checkuser != 0) { $error= "0"; header('LOCATION:../pages/myprofile.php?id='.$error.''); } } cheers i get this error Warning: current() [function.current]: Passed variable is not an array or object.. for this Code: [Select] $lastblock = current( ${"s".$row} ); print_r($lastblock); when i change to this it works.. Code: [Select] $lastblock = current( $s0 ); print_r($lastblock); The problem is i won't know the $row seeing as it is in a while loop. Solution? Hi, I have database stored a field of date. I want to check if the date in the DB field is the same as the current date, how to do it? Code: $oracle = mysqli_real_escape_string($con, $_POST['oracle']); $query = mysqli_query($con, "SELECT indate FROM staff WHERE OracleID ='$oracle'"); $row = mysqli_fetch_array($query); $num_row = mysqli_num_rows($query); if ($num_row > 0) { $curdate = date(); if ($row['indate'] !== $curdate) { $query1=mysqli_query($con, "update staff set ClockedIn = 0, ClockedOut = 0 where OracleID='$session_id'")or die('Error In Session'); header('location:home.php'); } }
Hi, I'm wanting to find rows whose date is within the next week of the current month of the current year. The format of the date is, for example: 2010-10-28 Any ideas guys? Thanks lots! Hello - I've come to an issue with something I'm working on and have searched around with no luck. When editing user accounts I want it to not be able to change the e-mail address into existing ones on other rows, but when submitting the form it takes into account that this particular rows email address is the same as the one which was sent via $_POST and throws up the error. The desired behaviour I want is for it to ignore the ID of the row which was posted, but take into account every other row. Here's the code as it stands at the moment: $email = $_POST['email']; $checkemail = mysql_query("SELECT email FROM users WHERE email='$email'"); } if (mysql_num_rows($checkemail) > 0) { return $this->error("The e-mail address you provided is already associated with an account."); } How do I show how many miles away the nearest location is? This code works with showing stores within the radius of the zip code entered, but it does not show the miles. Can anybody see what I have to do to display the miles? Code: [Select] <?php // Create page variables $r = NULL; $z = NULL; $stores = NULL; $Errors = NULL; include('inc/connect.db.mrk.php'); // Declare page functions function Dist($lat1, $lon1, $lat2, $lon2) { $distance = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($lon1 - $lon2)); $distance = (rad2deg(acos($distance))) * 69.09; return $distance; } ### Handle form if submitted if (isset ($_POST['submitted'])) { // Validate Postcode code field if (!empty ($_POST['zip']) && is_numeric ($_POST['zip'])) { $z = (int)$_POST['zip']; // Verify Postcode code exists $query = "SELECT latitude, longitude FROM zipdata WHERE zip = '$z'"; //$result = mysql_query ($query); $result=mysql_query($query) or die ('Invalid query.'); if (mysql_num_rows ($result) == 1) { $zip = mysql_fetch_assoc ($result); } else { $Errors = '<p>The postcode code you entered was not found!</p>'; $z=NULL; } } // Validate radius field if (isset ($_POST['radius']) && is_numeric ($_POST['radius'])) { $r = (int)$_POST['radius']; } // Proceed if no errors were found if ($r && $z) { // Retrieve coordinates of the locations $result = mysql_query("SELECT LocAddState, MktName, LocAddSt, LocAddZip, LocAddCity, x1, y1 FROM store INNER JOIN zipdata ON store.LocAddZip=zipdata.zip") or die(mysql_error()); //$result = mysql_query ($query); // Go through and check all locations while ($row = mysql_fetch_assoc ($result)) { // Separate closest locations $distance = Dist($row['y1'], $row['x1'], $zip['latitude'], $zip['longitude']); // Check if store is in radius if ($distance <= $r) { $stores[] = array ( 'name' => $row['MktName'], 'address' => $row['LocAddSt'], 'state' => $row['LocAddState'], 'town' => $row['LocAddCity'], 'postal' => $row['LocAddZip'], ); } } } else { $Errors = ($Errors) ? $Errors : '<p>Errors were found please try again!</p>'; } } ?><html> <head> <title>Store Locator</title> </head> <body> <form action="" method="post"> <p>Enter your zip code below to find locations near you.</p> <?php echo ($Errors) ? $Errors : ''; ?> <div> <label>Zip:</label> <input name="zip" type="text" size="10" maxlength="5" /> </div> <div> <label>Search Area:</label> <select name="radius" id="radius"> <option value="5">5 mi.</option> <option value="10">10 mi.</option> <option value="15">15 mi.</option> <option value="20">20 mi.</option> <option value="50">50 mi.</option> <option value="100">100 mi.</option> </select> </div> <div> <input type="hidden" name="submitted" value="submitted" /> <input type="submit" value="Submit" /> </div> </form> <?php if (isset ($stores)) { if (!empty ($stores)) { echo '<p><strong>' . count ($stores) . ' results were found.</strong></p>'; foreach ($stores as $value) { echo '<p><strong>' . $value['name'] . '</strong><br />'; echo $value['address'] . '<br />'; echo $value['town'] . ', ' . $value['state'] . ' ' . $value['postal'].'<br />'; echo $distance . ' miles away <br />'; /*echo ' <a target="_blank" href="http://maps.google.com/maps?q=', $value['address'], ' ', $value['town'], ', ', $value['state'], ' ', $value['postal'], '">Map this location</a><br />'; */ echo '</p>'; } } else { echo '<p><strong>No results found</strong></p>'; } } ?> </body> </html> Right now it shows like this Code: [Select] 1482.92070414 miles away Thanks in advance
Hi,
Write a function that calculates the Euclidean distance for points: eucl(q1,z1,r2,z2). Date:
$r1=1; $z1=12; $r1=43; $z1=123;
formula to the Euclidean distance: (r1,z1,r2,z2)=sqrt[(r1-z1)*(r1-z1) + (r2-z2)*(r2-z2)],
Can anyone help?
I made a post a while back about this topic he 1. The input from the project will be coming from a mobile app which will be using a qr code. The qr code contains the Room Number and the 2 Access Points for each room. When a user scans the qr code it will pass that info to the web app that has the algorithm and verify what room he/she is in the access point that was 'scanned'. 2. For the testing of the project we decided to use two rooms of the building of our alma mater and the access points were already defined based on tests:
Room 413 has Access Point 1 that have the values of -67 dBm to -89 dBm and Access Point 2 that have the values of -40 dbm to -57 dBm while
3. I already inputted the values and the rooms I've mentioned above in mysql to verify if the input from the qr code that was scanned it correct. but sadly we are stuck with the algorithm itself.
Table Of Contents - General Description - Database Image - Code - Code - Issue I have the following code (from outside sources), which, is apparently incompatible with my co-ordinate types. Here is a database excerpt (first thirty rows) of about 9200 airports from around the world. <?php 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.8684); } else { return $miles; } } $dep = $_GET['dep']; $arr = $_GET['arr']; $sql = 'SELECT * FROM `airports` WHERE `iata` = \'' . $dep . '\''; $query = mysql_query($sql); $dep = mysql_fetch_array($query); $sql = 'SELECT * FROM `airports` WHERE `iata` = \'' . $arr . '\''; $query = mysql_query($sql); $arr = mysql_fetch_array($query); echo distance($dep['latt'], $dep['long'], $arr['latt'], $arr['latt'], "k") . " km<br>"; ?> Here is my output [dep=yyz, arr=yul] with [yyz = 43.68, -79.63; yul = 45.47, -73.74] : 8719.64724823 km Obviously, with YYZ being Toronto, Canada and YUL being Montreal, Canada, it is definitely not 9000 km away (actually, ~500 km). Can you help me convert the units, or re-write the algorithms in order to make it function correctly. Thank you in advance. Hi Guys I need a PHP function to which I pass two postcodes and it works out the road distance, I dont mind using google or any other API I have managed to fing JS ways and php functions using crow route but I really really need a traffic distance in PHP Please advice, Help Thank you This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=348500.0 I have this script that works 9/10 of how it's suppose too. This does not calculate the correct distance for the results. Can anybody see where the problem lies? Here is the code Code: [Select] // see if our zip code has been posted, and if it is a 5 digit # if (isset($_POST['zip'])) { // remember to sanitize your inputs // this removes whitespace around the data and the next line makes sure its a 5 digit number $findzip = trim($_POST['zip']); if (preg_match("#^\d{5}$#",$findzip)) { include('inc/connect.php'); include('inc/functions.php'); // create a query that will select the zip code (if we can't find the user entered zip, we return an error) $query = "SELECT latitude,longitude,state,city FROM zipdata WHERE zip=".$findzip." LIMIT 1"; $result = mysql_query($query); if (mysql_num_rows($result) > 0) { // grab the latitude, longitude,state and city from our result list($flat,$flon,$fstate,$fcity) = mysql_fetch_row($result); // now get all markets in the same state, or all markets if no states match // we want to reduce the amount of work the database has to do so we see if a state matches $query = "SELECT * FROM mrk WHERE state='".$fstate."'"; $result = mysql_query($query); if (mysql_num_rows($result) < 1) { $query = "SELECT * FROM mrk"; $result = mysql_query($query); } // now we process the markets to gather their data, //this result should not be empty, so I was lazy and didn't write an else case if (mysql_num_rows($result) > 0) { while($row = mysql_fetch_assoc($result)) { // first put all of the data for this market into an array, with the market id as the key $storeinfo[$row['id']] = $row; // get the store zip $dzip = $row['zip']; // query for the store's latitude and longitude $query = "SELECT latitude,longitude FROM zipdata WHERE zip=".$dzip." LIMIT 1"; $result2 = mysql_query($query); if (mysql_num_rows($result2) > 0) { list($dlat,$dlon) = mysql_fetch_row($result2); // now get the distance from the user entered zip $stores[$row['id']] = calcDist($flat,$flon,$dlat,$dlon); } } } asort($stores); print "<p>The Markets closest to you: $findzip</p><br>\n"; $maploc = "'You are here','$findzip',"; foreach($stores as $k=>$v) { $output .= "<h3 style='margin:0;padding:0'><b>".$storeinfo[$k]['company']."</b><br>(approx ".round($v)." miles)</h3>"; $output .= "<p style='margin:0 0 10px 0;padding:0'><a href='".$storeinfo[$k]['url']."'>".$storeinfo[$k]['url']."</a><br>"; $output .= $storeinfo[$k]['city']." ".$storeinfo[$k]['state'].", ".$storeinfo[$k]['zip']."</p>"; } echo $output; } } } Here is the function.php Code: [Select] function calcDist($flat, $flon, $dlat, $dlon) { $distance = sin(deg2rad($flat)) * sin(deg2rad($dlat)) + cos(deg2rad($flat)) * cos(deg2rad($dlat)) * cos(deg2rad($flon - $dlon)); $distance = (rad2deg(acos($distance))) * 69.09; return $distance; } Thank you in advance Hi, I have been using the following function on my server and it works fine but when I try and use it on a different server it wont seem to work. Any ideas on why it wont work on the new server and any ideas on how I can do some error checking to figure out why ? Thanks in advance, Scott Code: [Select] <?php function get_driving_information($start, $finish, $raw = false) { # Convert any lon / lat coordingates if(preg_match('@-?[0-9]+\.?[0-9]*\s*,\s*-?[0-9]+\.?[0-9]@', $start)) { $url = 'http://maps.google.co.uk/m/local?q='.urlencode($start); if($data = file_get_contents($url)) { if(preg_match('@<div class="cpfxql"><a href="[^"]*defaultloc=(.*?)&ll=@smi', $data, $found)) { $start = trim(urldecode($found[1])); } else { throw new Exception('Start lon / lat coord conversion failed'); } } else { throw new Exception('Start lon / lat coord conversion failed'); } } if(preg_match('@-?[0-9]+\.?[0-9]*\s*,\s*-?[0-9]+\.?[0-9]@', $finish)) { $url = 'http://maps.google.co.uk/m/local?q='.urlencode($finish); if($data = file_get_contents($url)) { if(preg_match('@<div class="cpfxql"><a href="[^"]*defaultloc=(.*?)&ll=@smi', $data, $found)) { $finish = trim(urldecode($found[1])); } else { throw new Exception('Finish lon / lat coord conversion failed'); } } else { throw new Exception('Finish lon / lat coord conversion failed'); } } if(strcmp($start, $finish) == 0) { $time = 0; if($raw) { $time .= ' seconds'; } return array('distance' => 0, 'time' => $time); } $start = urlencode($start); $finish = urlencode($finish); $distance = 'unknown'; $time = 'unknown'; $url = 'http://maps.google.co.uk/m/directions?saddr='.$start.'&daddr='.$finish.'&hl=en&oi=nojs&dirflg=d'; if($data = file_get_contents($url)) { if(preg_match('@<span[^>]+>([^<]+) (mi|km)</span>@smi', $data, $found)) { $distanceNum = trim($found[1]); $distanceUnit = trim($found[2]); if($raw) { $distance = $distanceNum.' '.$distanceUnit; } else { $distance = number_format($distanceNum, 2); if(strcmp($distanceUnit, 'km') == 0) { $distance = $distanceNum / 1.609344; } } } else { throw new Exception('Could not find that route'); } if(preg_match('@<b>([^<]*)</b>@smi', $data, $found)) { $timeRaw = trim($found[1]); if($raw) { $time = $timeRaw; } else { $time = 0; $parts = preg_split('@days?@i', $timeRaw); if(count($parts) > 1) { $time += (86400 * $parts[0]); $timeRaw = $parts[1]; } $parts = preg_split('@hours?@i', $timeRaw); if(count($parts) > 1) { $time += (3600 * $parts[0]); $timeRaw = $parts[1]; } $time += (60 * (int)$timeRaw); } } return array('distance' => $distance, 'time' => $time); } else { throw new Exception('Could not resolve URL'); } } Getting the difference in seconds between two timestamps is easy. Taking the seconds and doing a breakdown of time frames is also easy. Code: [Select] <?php echo '<p>There are a total of ' . round($seconds) . ' seconds between Timestamp 1 and Timestamp 2.</p>'; echo '<p>There are a total of ' . round($seconds / 60) . ' minutes between Timestamp 1 and Timestamp 2.</p>'; echo '<p>There are a total of ' . round(($seconds / 60) / 1440) . ' days between Timestamp 1 and Timestamp 2.</p>'; echo '<p>There are a total of ' . round((($seconds / 60) / 1440) / 7) . ' weeks between Timestamp 1 and Timestamp 2.</p>'; echo '<p>There are a total of ' . round((((($seconds / 60) / 1440) / 7) / 30)) . ' months between Timestamp 1 and Timestamp 2.</p>'; echo '<p>The total breakdown of time from Timestamp 1 to Timestamp 2 is .</p>'; ?> What I am trying to figure out, is get a collective amount as well.... X years X months X weeks X days X minutes and X seconds. Does anyone have any good algorithm for handling that, or have any feedback on where to start to handle this type of math. I have a page that gets the closest stores to a latitude and longitude. I want to have a MySQL table like this: location_id:::::items showing how many items are at each store and then show 'spit' them in the following format with the lowest number of items first: location_id, distance to location_id, items. here is the code I am using to show location_id by distance Code: [Select] <?php include "connectionfile.php"; $lat = $_GET["lat"]; $lng = $_GET["lng"]; $sql = mysql_query("SELECT id, ( 6371 * acos( cos( radians($lat) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( lat ) ) ) ) AS distance FROM locations HAVING distance < 250 ORDER BY distance LIMIT 0 , 60; "); WHILE($lstlocations = mysql_fetch_array($sql)) { $location_id[$count]=$lstlocations['id']; $distance=$lstlocations['distance']; echo "id = " . $location_id[$count] . " Distance = " . $distance. "<br>"; $count = $count + 1; } ?> What would be the best way to achieve this? |