module Data.Geo.Jord.LatLong
( isValidLatLong
, latLongDmsP
, latLongDmsCompactP
, latLongDmsSymbolsP
, showLatLong
) where
import Control.Applicative ((<|>))
import Control.Monad.Fail (MonadFail)
import Data.Char ()
import Data.Maybe ()
import Text.ParserCombinators.ReadP (ReadP, char, option, pfail)
import Data.Geo.Jord.Angle
import Data.Geo.Jord.Model
import Data.Geo.Jord.Parser
isValidLatLong :: (Model a) => Angle -> Angle -> a -> Bool
isValidLatLong lat lon m = isValidLat lat && isValidLong lon m
latLongDmsP :: (Model a) => a -> ReadP (Angle, Angle)
latLongDmsP m = latLongDmsCompactP m <|> latLongDmsSymbolsP m
latLongDmsCompactP :: (Model a) => a -> ReadP (Angle, Angle)
latLongDmsCompactP m = do
lat <- blat
lon <- blon
if isValidLatLong lat lon m
then return (lat, lon)
else pfail
blat :: ReadP Angle
blat = do
d' <- digits 2
(m', s') <- option (0, 0.0) (ms <|> mi)
h <- hemisphere
if h == 'N'
then dmsF d' m' s'
else dmsF (-d') m' s'
blon :: ReadP Angle
blon = do
d' <- digits 3
(m', s') <- option (0, 0.0) (ms <|> mi)
m'' <- meridian
if m'' == 'E'
then dmsF d' m' s'
else dmsF (-d') m' s'
hemisphere :: ReadP Char
hemisphere = char 'N' <|> char 'S'
meridian :: ReadP Char
meridian = char 'E' <|> char 'W'
ms :: ReadP (Int, Double)
ms = do
m' <- digits 2
s' <- digits 2
return (m', fromIntegral s')
mi :: ReadP (Int, Double)
mi = do
m' <- digits 2
return (m', 0.0)
latLongDmsSymbolsP :: (Model a) => a -> ReadP (Angle, Angle)
latLongDmsSymbolsP m = do
lat <- hlat
_ <- char ' ' <|> char ','
lon <- hlon
if isValidLatLong lat lon m
then return (lat, lon)
else pfail
hlat :: ReadP Angle
hlat = do
lat <- angleP
h <- hemisphere
if h == 'N'
then return lat
else return (negate' lat)
hlon :: ReadP Angle
hlon = do
lon <- angleP
m' <- meridian
if m' == 'E'
then return lon
else return (negate' lon)
showLatLong :: (Angle, Angle) -> String
showLatLong (lat, lon) = showLat lat ++ "," ++ showLon lon
showLat :: Angle -> String
showLat lat
| isNegative lat = show (negate' lat) ++ "S"
| otherwise = show lat ++ "N"
showLon :: Angle -> String
showLon lon
| isNegative lon = show (negate' lon) ++ "W"
| otherwise = show lon ++ "E"
dmsF :: (MonadFail m) => Int -> Int -> Double -> m Angle
dmsF degs mins secs =
case e of
Left err -> fail err
Right a -> return a
where
e = dms degs mins secs
isValidLat :: Angle -> Bool
isValidLat a = isWithin a (decimalDegrees (-90)) (decimalDegrees 90)
isValidLong :: (Model a) => Angle -> a -> Bool
isValidLong a m =
case longitudeRange m of
L180 -> isWithin a (decimalDegrees (-180)) (decimalDegrees 180)
L360 -> isWithin a (decimalDegrees 0) (decimalDegrees 360)