Conversion tables A-K
  Conversion tables L-Z
  SPAM database query
  Reverse WHOIS utility
  North America area codes
  PHP Example forums

PHP example repository.

Web www.web-max.ca
Back to examples
Converting DMS longitude and latidude to decimal format and visa-versa.

This code will convert longitude and latitude in D'M'S format into a decimal format. It also contains the function to do the reverse.

The example below does contain a couple of strange lines of code. You will notice that we seperate the integer and floating point values from the decimal format using a set of string functions, instead of using the math round or floor functions. This fixes a 'feature' in some versions of PHP that causes it to behave in an unpredictable manner when handling math with floating points.

For example, if you include the code print(91.1 - 91); in PHP you may not get the result you expect. You will actually get 0.099999999999994, not 1 ! This tends to throw of the calculations in the example.

<?php

function DMStoDEC($deg,$min,$sec)
{

// Converts DMS ( Degrees / minutes / seconds ) 
// to decimal format longitude / latitude

    
return $deg+((($min*60)+($sec))/3600);
}    

function 
DECtoDMS($dec)
{

// Converts decimal longitude / latitude to DMS
// ( Degrees / minutes / seconds ) 

// This is the piece of code which may appear to 
// be inefficient, but to avoid issues with floating
// point math we extract the integer part and the float
// part by using a string function.

    
$vars explode(".",$dec);
    
$deg $vars[0];
    
$tempma "0.".$vars[1];

    
$tempma $tempma 3600;
    
$min floor($tempma 60);
    
$sec $tempma - ($min*60);

    return array(
"deg"=>$deg,"min"=>$min,"sec"=>$sec);
}    

?>
 
Example
Downloads

 misc_6.zip