Page 1 of 1

Help with GPS

Posted: Thu Nov 11, 2010 1:30 am
by cusackd
Hello Everyone im having a slight bit of trouble i have the code below which outputs the distance of two gps coordinates, i have this done but my next step is to get the variables which i have received and input the one with the shortest distance in to my database, due to my limited skills i can only output the results to the screen. Any help would be great cheers.

Code: Select all

$resultPoints = mysql_query("SELECT * FROM points");
	while($rowPoints = mysql_fetch_array($resultPoints)){
		$id = $rowPoints['id'];
		$lat = $rowPoints['lat'];
		$lng = $rowPoints['lng'];
						
		$lat1=53.283716;
		$lon1=-6.426905;

		$lat2=$lat;
		$lon2=$lng;

		$dlat = ($lat2-$lat1)*pi() / 180;
		$dlon = ($lon2-$lon1)*pi() / 180;
		$a= sin($dlat/2)*sin($dlat/2)+cos($lat1 * pi()/180) * cos($lat2 *pi()/180) * sin($dlon/2) * sin ($dlon/2);

		$c=2 * atan2(sqrt($a),sqrt(1-$a));
		$distance=6371000*$c;
						
						
		$resultdistance = round ($distance/1000,1) ;
						
		echo "
			<table>
				<tr><td>ID:</td><td>$id</td><td></td><td></td><tr>
				<tr><td>Latitude:</td><td>$lat</td><td>Longitude:</td><td>$lng</td><tr>
				<tr><td>Distance</td><td>$resultdistance km</td><td></td><td></td><tr>
			</table>
			<br>
			<br>
			";
			}

Re: Help with GPS

Posted: Thu Nov 11, 2010 7:43 am
by saltwine
Hi cusackd


The simplest way to achieve this would be to keep track of your shortest distance found so far as you're iterating over your results:

Code: Select all

$resultdistance = round($distance/1000, 1);

if(!isset($shortestdistance) || $resultdistance < $shortestdistance)
    $shortestdistance = $resultdistance;
Once your while loop is complete, you should have the $shortestdistance variable populated to then update your database. NB You might lose some accuracy this way as $resultdistance is performing the rounding before running the comparison.