PHP - Php Postcode Traffic Distance Calculator
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 Similar Tutorialshi i need some help . i see some person use bot traffic or proxey taffic software or script like jiggling and hitleap . they give a url of any sites then this software proxey view this websites.. i want asked can it possible stop these bot traffic its any procedure in php or javascript to stop this traffic..
Hi, Is it possible to make some kind of network/web traffic sniffer than can give you stats on how much p2p, mail etc etc traffic is going out your router? If so, does anyone know of any tutorials on the subject? Hello. I have a quick question. In my database I have Business's and members. I want the business to be able to advertise to members in their local area (lets say within 30 miles) for a cost. When a member within that distance of the office logs on they see this advert. Outside this distance they do not. Obviously the best way to do this is by postcode of the business compared to the member. I'm basically after some advise as I have been all over the internet looking for answers. First of all is it possible to write this script and what type of functions do I need to learn to do this? Second of all does anybody know of software that can do this out there already? I have found some but they are actual written programs with their own GUI that can not be changed to suit my needs. Thank you I would like to be able to detect, for instance, people who are using the TOR browser when they attempt to log in to one of my sites. my traffic report globals can already tell me if they are coming from a TOR node, but I would like to reject a login if an onion system or an anonymity browser is being used. I have only ran into one other site that has the capability of doing this, in terms of talking about forums only, and that is MrExcel: https://www.mrexcel.com/board/ if you try to register an account there with TOR, the page renders and says “we have detected you are trying to use automated queries to register an account”. there are of course, ways to get around that, if you click buttons in a timely manner, so they are not that good. but regardless, the pre-packaged software they bought does the job fairly well. can anyone offer any help in this regard? I know for a fact that most of the big banks in the USA have this covered, so I know that technology exists to block traffic coming from these sources, but I don’t know if it’s available to the little guy like me. Hi, I have this code but i cant get it to work. I have broken it down to sections and I think the get file contents may be at fault as when i dump the array it come back bool false. The URL creates a page with CSV values of longitude and latitude from a postcode. I want to give the variables $custlat1 and $custlong1 the values from the geocoded co-ordinates. The CSV values returned from the URL input are 200,5,54.1202442,-3.2078272 Code: [Select] $pc1 = 'http://maps.google.com/maps/geo?q=la139hu,+UK&output=csv&sensor=false&key=ABQIAAAAcclaxnepdvvxx5D2PAnHtRSLcuoGw6G6HnB4VN4WqoMz7tmtKhTHGV82iKKTXvAg7YFpCFA6ptRc9g'; $data1 = @file_get_contents($pc1); $result1 = explode(",", $data1); $custlat1 = $result1[2]; $custlong1 = $result1[3]; can anyone help? or point me in the right direction Hi All, Long long long time lurker here!
A little background to understand how this fits in So I am building a local directory for my local area as part of a community project. Part of this there is the ability for local stores to sell online locally for people to have delivered or collect. So in the UK we have postcodes in the formats: AB12 3CD, A1 2BC A12 3CD, A1B 2CD
Most delivery pricing solutions only care about the full postcode as they are all about national delivery or at best only care about the first half. Due to the local nature we need more granularity to it so we have some rules: Delivery Available EH => Price EH3 => Price EH3 1 => Price EH3 1-4 => Price
Exceptions - No Delivery allowed EH => null EH3 => null EH3 1 => null EH3 1-4 => null
Can mix and match for example:
EH3 = £2.00 EH3 2 => £2.25 EH3 5 => null
This means that ALL EH3 address the delivery cost is £2 BUT If they are in EH3 2 then its £2.25 or if the are in EH3 5 then no delivery is possible.
I have came up with this monstrosity of code that for the most part works but also can throw the wrong delivery prices out due to bugs and issues that I can't seem to work out!
Main Function: function isDeliverable($postcode, $rules){ $canDeliver = false; $deliveryValue = 0.00; $found = false; list($outward, $inward) = explode(' ', $postcode); $area = substr($outward, 0, 2); $district = substr($outward, 2); $sector = substr($inward, 0, 1); $unit = substr($inward, 1,1); $rulez = json_decode($rules, true); //RULE START - EH10 9RJ $pcFound = inRule($rulez, $postcode); if($pcFound){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } //RULE END - EH10 9RJ //RULE START - EH10 9R $pcFound = inRule($rulez, $area.$district.' '.$sector.$unit); if($pcFound && !strpos($pcFound['postcode'], "-")){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } //RULE END - EH10 9R //RULE START - EH10 9A-F $pcFound = inRule($rulez, $area.$district.' '.$sector.$unit, 1); if($pcFound){ $postArray = postcodeExploder($pcFound, 1); $pcFound = inRule($postArray, $area.$district.' '.$sector.$unit); if($pcFound){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } } //RULE END - EH10 9A-F //RULE START - EH10 9 $pcFound = inRule($rulez, $area.$district.' '.$sector); if($pcFound && !strpos($pcFound['postcode'], "-")){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } //RULE END - EH10 9 //RULE START - EH10 1-4 $pcFound = inRule($rulez, $area.$district.' '.$sector, 2); if($pcFound){ $postArray = postcodeExploder($pcFound, 2); $pcFound = inRule($postArray, $area.$district.' '.$sector); if($pcFound){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } } //RULE END - EH10 1-4 //RULE START - EH10 $pcFound = inRule($rulez, $area.$district); if($pcFound && !strpos($pcFound['postcode'], "-")){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } //RULE END - EH20 //RULE START - EH1-20 $pcFound = inRule($rulez, $area.$district, 3); if($pcFound){ $postArray = postcodeExploder($pcFound, 3); $pcFound = inRule($postArray, $area.$district); if($pcFound){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } } //RULE END - EH1-20 //RULE START - EH $pcFound = inRule($rulez, $area); if($pcFound && !strpos($pcFound['postcode'], "-")){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } //RULE END - EH return ['canDeliver' => $canDeliver, 'deliveryValue' => $deliveryValue]; }
Helper Functions: function inRule($rules, $postcode, $type = null){ foreach($rules as $key => $rule){ if(substr_count($rule['postcode'], '-') !== 0 && strlen($postcode) > 2){ $pEX = postcodeExploder($rule, $type); foreach($pEX as $r){ if($r['postcode'] == $postcode){ return $rules[$key]; } //$rule['postcode'] = trim(substr($rule['postcode'], 0, strpos($rule['postcode'], "-")-1)); } } if ( $rule['postcode'] == $postcode ) return $rules[$key]; } return false; } function postcodeExploder($rule, $type){ $out = []; $r = explode(' ', $rule['postcode']); $count = count($r); //It must be in the form AB1 1C //$first = AB1 //$last = 1C-G if($count == 2){ list($first, $last) = $r; } else { $last = $r[0]; } list($left, $right) = explode('-', $last); $sec = $left[0]; $leftInward = substr($last, strpos($last, '-')-1,1); $rightInward = substr($last, strpos($last, '-')+1,1); $range = range($leftInward, $rightInward); foreach($range as $key => $ra){ if($type == 1){ $out['a'.$key] = [ 'postcode' => $first.' '.$sec.$ra, 'deliverable' => $rule['deliverable'], 'price' => $rule['price'] ]; } else if($type == 2){ $out['a'.$key] = [ 'postcode' => $first.' '.$ra, 'deliverable' => $rule['deliverable'], 'price' => $rule['price'] ]; } else { $out['a'.$key] = [ 'postcode' => preg_replace('/\PL/u', '', $left).$ra, 'deliverable' => $rule['deliverable'], 'price' => $rule['price'] ]; } } return $out; } Stores Rules: $rules = '{"a1":{"postcode":"EH9","deliverable":true,"price":"1.50"},"a2":{"postcode":"EH9 7","deliverable":true,"price":"1.60"},"a3":{"postcode":"EH9 7A","deliverable":true,"price":"1.70"},"a4":{"postcode":"EH9 7AY","deliverable":true,"price":"1.80"},"a5":{"postcode":"EH1-2","deliverable":true,"price":"1.90"},"a6":{"postcode":"EH1 2-3","deliverable":true,"price":"2.00"},"a7":{"postcode":"EH4 5A-N","deliverable":true,"price":"2.10"},"a8":{"postcode":"EH","deliverable":true,"price":"1.40"},"a9":{"postcode":"TD14","deliverable":true,"price":"2.00"},"a10":{"postcode":"TD14 5DC","deliverable":false,"price":null}}';
Hi I have a function that takes a postcode and splits it so i can enter into DB into two formats, full postcode and prefix. The function is: function check_form_postcode($postcode) { $postcode = strtoupper(str_replace(chr(32),'',$postcode)); $suffix = substr($postcode,-3,3); $prefix = substr($postcode,0,(strlen($postcode)-3)); if (preg_match('/(^[A-Z]{1,2}[0-9]{1,2}|^[A-Z]{1,2}[0-9]{1}[A-Z]{1})$/',$prefix) && preg_match('/^[0-9]{1}[ABD-HJLNP-UW-Z]{2}$/',$suffix)) { $postcode_syntax_check = 1; } else { $postcode_syntax_check = 0; } if($postcode_syntax_check){ $return = $prefix."::".$suffix; } return($return); } I POST the form data and in the top of the same page I get all of the form data and here is is where things go wrong: if ($b == 'go') { //Gets form data $main_event_name = my_import('main_event_name', 'P', 'TXT'); $main_event_type = my_import('main_event_type', 'P', 'TXT'); $main_event_date = my_import('main_event_date', 'P', 'TXT'); $main_event_city = my_import('main_event_city', 'P', 'TXT'); $postcode = my_import('postcode', 'P', 'TXT'); $main_event_added = my_import('main_event_added', 'P', 'INT'); $main_event_active = my_import('main_event_active', 'P', 'INT'); $postcode_array = check_form_postcode($postcode); $postcode = explode($postcode_array, "::"); $prefix = $postcode[0]; $fullpostcode = $postcode[0]." ".$postcode[1]; $valkey = md5(microtime()); $info = array( "main_event_name"=> $main_event_name, "main_event_type" => $main_event_type, "main_event_date" => $main_event_date, "main_event_city" => $main_event_city, "main_event_active" => $main_event_active, "main_event_added" => $sys['now'], "main_event_pcode" => $fullpostcode, "main_event_pcode_prefix" => $prefix, "eo_id" => $eo['id'] ); $table = $db['main_event']; $userid = my_insert($info, $table); When I enter into the DB all I get is the "::" no data. I know that the POST works as I can enter the data easily without the function going wrong. Thanks for any help, i am new to arrays go easy if I have made an obvious mistake! Cheers... Ok, first let me tell you what I want to do. Google sends me traffic from many keywords, but I want to track what keyword does best for me as sales and so. The Analytics is good but I can't send the data to outside sites. So I figured this out : from the $_SERVER['HTTP_REFERER'] I can get the "q" value from the _GET and pass it on to track it... now I'm kind of stuck and I know it's easy but can't seem to find the function. This is what I have so far: /* Code to try and store the keyword that was used to find and land on my site. */ $exurl = 'http://www.google.ca/url?sa=t&source=web&cd=1&ved=0CBYQFjAA&rct=j&q=mykeyword&ei=pJ2STMy8MsP-8AaqvuznBQ'; //set a demo refferer url that would usually be $exurl = $_SERVER['HTTP_REFERER'] $refurl = parse_url($exurl, PHP_URL_QUERY); // remove all before and including the "?" echo $refurl; // echo "sa=t&source=web&cd=1&ved=0CBYQFjAA&rct=j&q=mykeyword&ei=pJ2STMy8MsP-8AaqvuznBQ" Ok, so I managed to get the important part out of the google URL, now how do I split this into an array that I can then use. For instance somefunction($refurl, $newarray); and then I could say | echo $newarray['q']; | and it would echo "mykeyword" Of course If there is a space in the keywords I should use the urldecode() function to avoid the % char... Let me know if you know of any way to get this done. Hi, can anyone help me?
I am trying to create a form which asks the user to input their postcode then submit. the purpose is so if the service my site offers is not available in the location that the end user lives, then I want to display a message saying 'Sorry, not available', but if they are in area then it redirects to another page.
My form code is:
<form method="post" action="forwarder.php"> <p> Enter Post Code He <input type = "text" name = "zip" id = "zip" size = "10" maxlength = "5" "> <input type='submit'> </form>My PHP is: <?php $zip = isset ($_POST['zip']) { if ($zip=='NG15') { header('Location: https://www.bing.com'); } else { header('Location: http://www.google.co.uk') } ?>I am a bit of a newbie at this, and I know my PHP won't give me my desired result, but I was using this to try and test the concept. Help would be really appreciated, and if you can show me how to do it for multiple postcodes even better How can I make my PHP script non accessible to users? I am wanting to cron the script and don't want anybody to spam the script as it would cause performance issues if it was constantly spammed by a user. Can I put the PHP file anywhere that only the server can run it?
Thanks any info would be awesome.
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 succesfully managed to route all the traffic to the file controller.php using this command line of .htaccess :
RewriteEngine On RewriteRule (.*) /var/www/html/site/controller.php [L,QSA]Now how to tell the controller.php to process the url that was passed. For example i have tried that: controller.php : <?php include( $_SERVER["REQUEST_URI"] ); ?>but the controller.php didn't do anything i keep getting a blank page when i browse any webpage such as site/index.php so how to tell controller.php to echo the content of the request ? because the user shouldn't notice any change as if there is no controller.php. Thank you.
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.
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 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? This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=348500.0 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, 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'); } } |