Skip to main content

Map Coordinates Converter from DMS to DD Format

Author

Robert Loncaric

Timestamps

Created: 01 August 2024
Modified: 01 August 2024

If a client has, or delivers coordinates in DMS (40° 26' 46 N, 79° 58' 56 W) format, that's utterly useless to us since everything uses DD (45.16161651, 15.66841681) format.

This piece of magic will convert those coordinates for you :)

Steps

Use this in the front where needed. You can if needed/wanted, also throw the function part of this code to functions.php and call the function from the front on each lat / lon coordinates.

<?php
	function dmsToDecimal($degrees, $minutes, $seconds, $direction) {
		$decimal = $degrees + ($minutes / 60) + ($seconds / 3600);

		// Check the direction and make the decimal value negative if it's S or W
		if ($direction == 'S' || $direction == 'W') {
			$decimal = -$decimal;
		}

		return $decimal;
	}

	// Add your source coordinates here
	$src_lat = "40° 26' 46\" N";
	$src_lon = "79° 58' 56\" W";

	// Extract degrees, minutes, seconds and direction from the source latitude
	preg_match('/(\d+)° (\d+)\\' . "' (\d+(\.\d+)?)\\" . '" ([NSEW])/', $src_lat, $matches_lat);
	$degrees_lat = $matches_lat[1];
	$minutes_lat = $matches_lat[2];
	$seconds_lat = $matches_lat[3];
	$direction_lat = $matches_lat[5];

	// Extract degrees, minutes, seconds and direction from the source longitude
	preg_match('/(\d+)° (\d+)\'' . "' (\d+(\.\d+)?)\"" . ' ([NSEW])/', $src_lon, $matches_lon);
	$degrees_lon = $matches_lon[1];
	$minutes_lon = $matches_lon[2];
	$seconds_lon = $matches_lon[3];
	$direction_lon = $matches_lon[5];

	// Convert DMS to DD for latitude
	$lat = dmsToDecimal($degrees_lat, $minutes_lat, $seconds_lat, $direction_lat);

	// Convert DMS to DD for longitude
	$lon = dmsToDecimal($degrees_lon, $minutes_lon, $seconds_lon, $direction_lon);

	echo "Latitude in DD format: $lat\n";
	echo "Longitude in DD format: $lon\n";
?>