PHP - Euclidean Distance
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? Similar Tutorials
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.
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, 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'); } } 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? 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 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 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. 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? |