Aller au contenu

« Module:Coordinates » : différence entre les versions

De Wreck
Modèle:Infobox>Orlodrim
Remplacement par la version de Zolo à partir de Module:Coordinates/Test
Modèle:Infobox>Orlodrim
Retour en arrière
Ligne 1 : Ligne 1 :
local math_mod = require( "Module:Math" )
--[[
local p = {}
This module is intended to replace the functionality of {{Coord}} and related
templates.  It provides several methods, including


local i18n = {
{{#Invoke:Coordinates | coord }} : General function formatting and displaying
N = ' N',
coordinate values.
Nlong = ' Nord',
W = ' O',
Wlong = ' Ouest',
E = ' E',
Elong = ' Est',
S = ' S',
Slong = ' Sud',
degrees = '° ',
minutes = '\′ ',
seconds = '″ ',
geohackurl = 'http://tools.wmflabs.org/geohack/geohack.php?language=fr',
tooltip = 'Cartes, vues aériennes et autres données pour cet endroit',
errorcat = 'Pages avec des balises de coordonnées mal formées',
sameaswikidata = 'Page avec coordonnées similaires sur Wikidata',
notaswikidata = 'Page avec coordonnées différentes sur Wikidata',
throughwikidata = 'Page géolocalisée par Wikidata',
}


local globedata = {
{{#Invoke:Coordinates | dec2dms }} : Simple function for converting decimal
--[[ notes:
degree values to DMS format.
radius in kilometers (especially imprecise for non spheric bodies)
defaultdisplay is currently disabled, activate it ?
]]--
ariel = {radius = 580, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
callisto =  {radius = 2410, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
ceres =  {radius = 470, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
deimos =  {radius = 7, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
dione =  {radius = 560, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
enceladus =  {radius = 255, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
ganymede =  {radius = 1631, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
earth = {radius = 6371, defaultdisplay = 'dms', trackingcat = 'Article géolocalisé sur Terre'},
europe =  {radius = 1561, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
hyperion =  {radius = 140, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
iapetus =  {radius = 725, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
['io'] =  {radius = 1322, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
jupiter =  {radius = 68911, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
mars =  {radius = 3389.5, defaultdisplay = 'dec east', trackingcat =  'Article géolocalisé sur Mars' },
mercury =  {radius = 2439.7, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
mimas =  {radius = 197, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
miranda =  {radius = 335, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
moon =  {radius = 1736, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé sur la Lune'},
neptune =  {radius = 24553, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
oberon =  {radius = 761, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
phoebe =  {radius = 110, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
phobos =  {radius = 11, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
rhea =  {radius = 765, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
saturn =  {radius = 58232, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
titan =  {radius = 2575.5, defaultdisplay = 'dec west', trackingcat = 'Article géolocalisé extraterrestre'},
tethys =  {radius = 530, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
titania =  {radius = 394, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
triton = {radius = 1353, defaultdisplay = 'dec west', trackingcat = 'Article géolocalisé extraterrestre'},
umbriel =  {radius = 584, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
uranus =  {radius = 25266, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
venus =  {radius = 6051.8, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
vesta =  {radius = 260, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'}
}


local wikidatathreshold = 10 -- si la distance entre coordonnées Wikipédia et Wikidata dépasse se seuil (en kilomètes), une catégorie de maintenance est ajoutée
{{#Invoke:Coordinates | dms2dec }} : Simple function for converting DMS format
to decimal degree format.


----------------------------------------
]]
--Error handling
--[[ Notes:
when errors occure a new error message is concatenated to errorstring
an error message contains an error category with a sortkey
For major errors, it can also display an error message (the error message will the usually be returned and the function terminated)
More minor errors do only add a category, so that readers are not bothered with error texts
sortkeys:
* A: invalid latitude, longitude or direction
* B: invalid globe
* C: something wrong with other parameters
]]--


errorstring = ''
math_mod = require( "Module:Math" );
globalFrame = nil


function makeerror(args)
coordinates = {};
local errormessage = ''
 
if args.message then
--[[ Helper function, replacement for {{coord/display/title}} ]]
errormessage = '<strong class="error">Coordonnées: ' .. args.message .. '</strong>'
function displaytitle (s, notes ,globe)
end
    --local l = "[[Geographic coordinate system|Coordinates]]: " .. s
local errorcat = ''
    local l = "" .. s
if mw.title.getCurrentTitle().namespace == 0 then  
    local extracat = ""
errorcat = makecat(i18n.errorcat, args.sortkey)
   
end
    if mw.title.getCurrentTitle().nsText == "" then
errorstring = errormessage .. errorcat -- reinitializes the string to avoid absurdly long messages
        if globe~= nil and globe~= "earth" then
return nil
            if globe == "moon" then
                extracat = "[[Catégorie:Article géolocalisé sur la Lune]]";               
            elseif globe == "mars" then
                extracat = "[[Catégorie:Article géolocalisé sur Mars]]";
            else
                extracat = "[[Catégorie:Article géolocalisé extraterrestre]]";
            end           
        else
            extracat = "[[Catégorie:Article géolocalisé sur Terre]]";
        end
    end
   
    local co = '<span id="coordinates">' .. l .. notes .. '</span>';
    return '<span style="font-size: small;">' .. co .. '</span>' .. extracat;
end
end


function showerrors()
--[[ Helper function, Replacement for {{coord/display/inline}} ]]
return errorstring
function displayinline (s, notes)
    return s .. notes   
end
end
-------------------------------------------
 
function makecat(cat, sortkey)
--[[ Helper function, used in detecting DMS formatting ]]
return '[[Category:' .. cat .. '|' .. (sortkey or '*') .. ']]'
local dmsTest = function(first, second)
    local concatenated = first:upper() .. second:upper();
   
    return concatenated == "NE" or concatenated == "NO" or concatenated == "NW" or concatenated == "SE" or concatenated == "SO"  or concatenated == "SW" or
        concatenated == "EN" or concatenated == "ON" or concatenated == "WN" or concatenated == "ES" or concatenated == "OS"  or concatenated == "WS"
end
end


----------------------------------------
--[[
-- Distance computation
parseDec
function p._distance(a, b, globe) -- calcule la [[distance orthodromique]] en kilomètres entre deux points du globe


globe = string.lower(globe or 'earth')
Transforms decimal format latitude and longitude into the a
structure to be used in displaying coordinates
-- check arguments and converts degreees to radians
]]
local latA, latB, longA, longB = a.latitude, b.latitude, a.longitude, b.longitude
function parseDec( lat, long, format )
if not latA or not latB or not longA or not longB then return
    local coordinateSpec = {}
error('coordinates missing, can\'t compute distance')
    local errors = {}
end
   
if type(latA) ~= 'number' or type(latB) ~= 'number' or type(longA) ~= 'number' or type(longB) ~= 'number' then
    if long == "" or long == nil then
error('coordinates are not numeric, can\'t compute distance')
        return nil, {{"parseDec", "Missing longitude"}}
end
    end
   
-- distance angulaire en radians
    errors = validate( lat, nil, nil, long, nil, nil, 'parseDec', false );   
local convratio = math.pi / 180 -- convertit en radians
    coordinateSpec["dec-lat"]  = lat;
latA, latB, longA, longB = convratio * latA, convratio * latB, convratio * longA, convratio * longB
    coordinateSpec["dec-long"] = long;
local angle = math.acos(math.sin(latA) * math.sin(latB) + math.cos(latA) * math.cos(latB) * math.cos(longB - longA))


-- convertit en km en fonction du globe
    local mode = coordinates.determineMode( lat, long );
if not globe or not globedata[globe] then
    coordinateSpec["dms-lat"]  = convert_dec2dms( lat, "N", "S", mode)  -- {{coord/dec2dms|{{{1}}}|N|S|{{coord/prec dec|{{{1}}}|{{{2}}}}}}}
return error('globe: ' .. globe .. 'is not supported')
    coordinateSpec["dms-long"] = convert_dec2dms( long, "E", "O", mode)  -- {{coord/dec2dms|{{{2}}}|E|W|{{coord/prec dec|{{{1}}}|{{{2}}}}}}} 
end
    coordinateSpec["dmslong-lat"]  = convert_dec2dms( lat, "Nord", "Sud", mode)  -- {{coord/dec2dms|{{{1}}}|N|S|{{coord/prec dec|{{{1}}}|{{{2}}}}}}}
    coordinateSpec["dmslong-long"] = convert_dec2dms( long, "Est", "Ouest", mode)  -- {{coord/dec2dms|{{{2}}}|E|W|{{coord/prec dec|{{{1}}}|{{{2}}}}}}}     
   
    if format ~= "" then
        coordinateSpec.default = format
    else
        coordinateSpec.default = "dec"
    end


radius = globedata[globe].radius
    return coordinateSpec, errors
return radius * angle
end
end


function p.distance(frame)
--[[ Helper function, handle optional args. ]]
local args = frame.args
function optionalArg(arg, suplement)
return p._distance(
    if arg ~= nil and arg ~= "" then
{latitude = tonumber(args.latitude1), longitude = tonumber(args.longitude1)},
        return arg .. suplement
{latitude = tonumber(args.latitude2), longitude = tonumber(args.longitude2)},
    end
args.globe)
    return ""
end
end


--[[
parseDMS
Transforms degrees, minutes, seconds format latitude and longitude
into the a structure to be used in displaying coordinates
]]
function parseDMS( lat_d, lat_m, lat_s, lat_f, long_d, long_m, long_s, long_f, format )
    local coordinateSpec = {}
    local errors = {}
   
    lat_f = lat_f:upper();
    long_f = string.gsub(long_f:upper(),'W','O');
    local lat_flong = 'Nord';
    if lat_f == 'S' then
        lat_flong = 'Sud';
    end
    local long_flong = 'Ouest';
    if long_f == 'E' then
        long_flong = 'Est';
    end
   
   
    -- Check if specified backward
    if lat_f == 'E' or lat_f == 'O' or lat_f == 'W' then
        local t_d, t_m, t_s, t_f;
        t_d = lat_d;
        t_m = lat_m;
        t_s = lat_s;
        t_f = lat_f;
        lat_d = long_d;
        lat_m = long_m;
        lat_s = long_s;
        lat_f = long_f;
        long_d = t_d;
        long_m = t_m;
        long_s = t_s;
        long_f = t_f;
    end   
   
    errors = validate( lat_d, lat_m, lat_s, long_d, long_m, long_s, 'parseDMS', true );
    if long_d == nil or long_d == "" then
        table.insert(errors, {"parseDMS", "Missing longitude" })
    end
   
    if lat_m == nil and lat_s == nil and long_m == nil and long_s == nil and #errors == 0 then
        if math_mod._precision( lat_d ) > 0 or math_mod._precision( long_d ) > 0 then
            if lat_f:upper() == 'S' then
                lat_d = '-' .. lat_d;
            end
            if long_f:upper() == 'O' or long_f:upper() == 'W' then
                long_d = '-' .. long_d;
            end   
           
            return parseDec( lat_d, long_d, format );
        end       
    end 
   
    coordinateSpec["dms-lat"]  = lat_d.."°&nbsp;"..optionalArg(lat_m,"′&nbsp;") .. optionalArg(lat_s,"″&nbsp;") .. lat_f
    coordinateSpec["dmslong-lat"]  = lat_d.."°&nbsp;"..optionalArg(lat_m,"′&nbsp;") .. optionalArg(lat_s,"″&nbsp;") .. lat_flong
    coordinateSpec["dms-long"] = long_d.."°&nbsp;"..optionalArg(long_m,"′&nbsp;") .. optionalArg(long_s,"″&nbsp;") .. long_f
    coordinateSpec["dmslong-long"] = long_d.."°&nbsp;"..optionalArg(long_m,"′&nbsp;") .. optionalArg(long_s,"″&nbsp;") .. long_flong
    coordinateSpec["dec-lat"]  = convert_dms2dec(lat_f, lat_d, lat_m, lat_s) -- {{coord/dms2dec|{{{4}}}|{{{1}}}|0{{{2}}}|0{{{3}}}}}
    coordinateSpec["dec-long"] = convert_dms2dec(long_f, long_d, long_m, long_s) -- {{coord/dms2dec|{{{8}}}|{{{5}}}|0{{{6}}}|0{{{7}}}}}
   
    if format ~= "" then
        coordinateSpec.default = format
    else
        coordinateSpec.default = "dms"
    end 


------------------------
     return coordinateSpec, errors
--HTML builder for a geohack link
end
local function buildHTML(decLat, decLong, dmsLat, dmsLong, globe, displayformat, displayinline, displaytitle, objectname, extraparams)
local htmlBuilder = require("Module:HtmlBuilder")
    local root, text, url, noprint
extraparams = extraparams or ''
    -- geohack url and parameters
     local decimalcoords = p.displaydec(decLat, decLong, displayformat)
    local geohacklatitude, geohacklongitude


    -- format latitude and longitude for the URL
--[[
    if tonumber(decLat) < 0 then
specPrinter
    geohacklatitude = tostring(-tonumber(decLat)) .. '_S'
    else
    geohacklatitude = decLat .. '_N'
end
if tonumber(decLong) < 0 then
geohacklongitude = tostring(-tonumber(decLong)) .. '_W'
    else
    geohacklongitude = decLong .. '_E'
end
-- prepares the 'paramss=' parameter
local geohackparams = geohacklatitude .. '_' .. geohacklongitude .. '_' ..extraparams
-- concatenate parameteres for geohack
local url = i18n.geohackurl ..
"&pagename=" .. mw.uri.encode(mw.title.getCurrentTitle().prefixedText, "WIKI") ..
"&params=" .. geohackparams ..
(objectname and ("&title=" .. mw.uri.encode(objectname)) or "")


    root = htmlBuilder.create()
Output formatter. Takes the structure generated by either parseDec
    root
or parseDMS and formats it for inclusion on Wikipedia.
        .tag("span")
]]
            .addClass("plainlinks nourlexpansion")
function specPrinter(args, coordinateSpec)
            .wikitext("[" .. url)
    local uriComponents = coordinateSpec["param"]
            .tag("span")
    if uriComponents == "" then
                .addClass(string.sub(displayformat,1,3) == "dec" and "geo-nondefault" or "geo-default")
        -- RETURN error, should never be empty or nil
                .tag("span")
        return "ERROR param was empty"
                    .addClass("geo-dms")
    end
                    .attr("title", i18n.tooltip)
       
                    .tag("span")
    if args["name"] ~= "" and args["name"] ~= nil then
                        .addClass("latitude")
        uriComponents = uriComponents .. "&title=" .. mw.uri.encode(coordinateSpec["name"])
                        .wikitext(p.displaydmsdimension(dmsLat, displayformat))
    end
                        .done()
   
                    .wikitext(" ")
    local lang=mw.language.getContentLanguage():getCode();
                    .tag("span")
   
                        .addClass("longitude")
    local geodmshtml = '<span class="geo-dms" title="Cartes, vues aériennes et autres données pour cet endroit">'
                        .wikitext(p.displaydmsdimension(dmsLong, displayformat))
            .. '<span class="latitude">' .. coordinateSpec["dms-lat"] .. '</span> '
                        .done()
            .. '<span class="longitude">' ..coordinateSpec["dms-long"] .. '</span>'
                    .done()
            .. '</span>'
                .done()
    local geodmslonghtml = '<span class="geo-dms" title="Cartes, vues aériennes et autres données pour cet endroit">'
            .tag("span")
            .. '<span class="latitude">' .. coordinateSpec["dmslong-lat"] .. '</span> '
                .addClass("geo-multi-punct")
            .. '<span class="longitude">' ..coordinateSpec["dmslong-long"] .. '</span>'
                .wikitext("&#xfeff; / &#xfeff;")
            .. '</span>'
                .done()
    local lat = tonumber( coordinateSpec["dec-lat"] ) or 0
            .tag("span")
    if lat < 0 then
                .addClass(string.sub(displayformat,1,3) == 'dec' and "geo-default" or "geo-nondefault")
        -- FIXME this breaks the pre-existing precision
                .wikitext(objectname and "<span class=\"vcard\">" or "")
        --geodeclat = coordinateSpec["dec-lat"]:sub(2) .. "°S"
                .tag("span")
        geodeclat = "-" .. coordinateSpec["dec-lat"]:sub(2)
                    .addClass("geo-dec")
    else
                    .attr("title", i18n.tooltip)
        --geodeclat = (coordinateSpec["dec-lat"] or 0) .. "°N"
                    .wikitext(decimalcoords)
        geodeclat = (coordinateSpec["dec-lat"] or 0)
                    .done()
    end
                .wikitext(objectname and ("<span style=\"display:none\"> (<span class=\"fn org\">" ..
                          objectname .. "</span>)</span></span>") or "")
                .done()
            .wikitext("]")
            .done()


     -- formatta il risultato a seconda di args["display"] (nil, "inline", "title", "inline,title")
     local long = tonumber( coordinateSpec["dec-long"] ) or 0
    text = tostring(root)
    if long < 0 then
        -- FIXME does not handle unicode minus
        --geodeclong = coordinateSpec["dec-long"]:sub(2) .. "°O"
        geodeclong = '-' .. coordinateSpec["dec-long"]:sub(2)
    else
        --geodeclong = (coordinateSpec["dec-long"] or 0) .. "°E"
        geodeclong = (coordinateSpec["dec-long"] or 0)
    end
   
    local geodechtml = '<span class="geo-dec" title="Cartes, vues aériennes et autres données pour cet endroit">'
            .. geodeclat .. ', '
            .. geodeclong
            .. '</span>'


     noprint = displayinline and "class=\"noprint\" " or ""
     local geonumhtml = '<span class="geo">'
    htmlTitle = "<span style=\"font-size: small;\"><span " .. noprint .. "id=\"coordinates\">"
            .. coordinateSpec["dec-lat"] .. '; '
            .. coordinateSpec["dec-long"]
            .. '</span>'


     return (displayinline and text or "") ..
--cf http://www.mediawiki.org/wiki/Extension:GeoData
          (displaytitle and (htmlTitle .. text .. "</span></span>") or "")
    local geodata = ''
end
    local r,s,t=string.match (coordinateSpec["param"],'(.*)_(E?W?)_(.*)')
     local globe,globend=string.match (coordinateSpec["param"],'_globe:(.*)(_*)')
    --Désactivé pour les astres à cause de problèmes de longitudes planétocentriques/planétographiques
    if globe == nil or globe == 'earth' then
    geodata = '{{#coordinates:' .. coordinateSpec["dec-lat"] .. '|' .. coordinateSpec["dec-long"] .. '|primary|' .. t .. '}}'
    end
    if args['geodata'] ~= nil then
        return geodata;
    end
   
    local inner;
    if coordinateSpec["default"] == "dms" then
        inner = '<span class="' .. displayDefault(coordinateSpec["default"], "dms" ) .. '">' .. geodmshtml .. '</span>'
                    .. '<span class="geo-multi-punct">&#xfeff; / &#xfeff;</span>'
                    .. '<span class="' .. displayDefault(coordinateSpec["default"], "dec" ) .. '">';
    else
        inner = '<span class="' .. displayDefault(coordinateSpec["default"], "dms long" ) .. '">' .. geodmslonghtml .. '</span>'
                    .. '<span class="geo-multi-punct">&#xfeff; / &#xfeff;</span>'
                    .. '<span class="' .. displayDefault(coordinateSpec["default"], "dec" ) .. '">';       
    end


-- Fonctions de manipualation/coonversion des coordonnées


function p._dec2dms(dec, coordtype, precision) -- type: latitude or longitude
    if args["name"] == "" or args["name"] == nil then
local dec = tonumber(dec)
        inner = inner .. geodechtml
local dms = {}
                .. '<span style="display:none">&#xfeff; / ' .. geonumhtml .. '</span></span>'
    else
        inner = inner .. '<span class="vcard">' .. geodechtml
                .. '<span style="display:none">&#xfeff; / ' .. geonumhtml .. '</span>'
                .. '<span style="display:none">&#xfeff; (<span class="fn org">'
                .. args["name"] .. '</span>)</span></span></span>'
    end


-- precision
    return '<span class="plainlinksneverexpand">' .. globalFrame:preprocess(
if precision and precision ~= '' and precision ~= 'd' and precision ~= 'dm' and precision ~= 'dms' then
        '[//tools.wmflabs.org/geohack/geohack.php?pagename={{FULLPAGENAMEE}}&language=' .. lang .. '&params=' ..
return makeerror({sortkey = 'C'})
        uriComponents .. ' ' .. inner .. ']') .. '</span>'
end
if not precision then
precision = math_mod._precision(dec)
if precision <= 0 then
precision = 'd'
elseif precision <= 2 then
precision = 'dm';
else
precision = 'dms';
end
end  -- et fractions de secondes ?
if precision ~= 'd' and precision ~= 'dm' and precision ~= 'dms' then
makeerror({message = 'invalid precision in function dec2dms', sortkey = 'C'})
end
-- direction
if coordtype == 'latitude' then
if dec < 0 then
direction = 'S'
else
direction = 'N'
end
elseif coordtype == 'longitude' then
if dec < 0 then
direction = 'W'
else
direction = 'E'
end
end
-- conversion
dec = math.abs(dec) -- les coordonnées en dms sont toujours positives
if precision == 'dms' then
dec = math_mod._round( dec * 60 * 60, 0 )
seconds =  dec % 60
dec =  (dec - seconds) / 60 / 60
end
if precision == 'dm' or precision == 'dms' then
dec = math_mod._round( dec * 60, 0 )
minutes = dec % 60
dec = (dec - minutes) / 60
end
degrees = math_mod._round(dec, 0)
return builddmsdimension(degrees, minutes, seconds, direction)
end
end


function p.dec2dms(frame) -- legacy function somewhat cumbersome syntax
--[[
args = frame.args
Formats any error messages generated for display
local dec = args[1]  
]]
local precision = string.lower(args[4])
function errorPrinter(errors)
local displayformat, coordtype
    local result = ""
    for i,v in ipairs(errors) do
if args[2] == 'N' or 'Nord' then
        local errorHTML = '<strong class="error">Coordonnées: ' .. v[2] .. '</strong>'
coordtype = 'latitude'
        result = result .. errorHTML .. "<br />"
else
    end
coordtype = 'longitude'
    return result
end
if args[2] == 'Nord' or args[2] == 'Est' or args[2] == 'Ouest' then
displayformat = 'dms long'
end
local coordobject = p._dec2dms(dec, coordtype, precision)
return p.displaydmsdimension(coordobject, displayformat) .. showerrors()
end
end


function p._dms2dec(dmsobject) -- transforme une table degré minute secondes en nombre décimal
--[[
local direction, degrees, minutes, seconds = dmsobject.direction, dmsobject.degrees, dmsobject.minutes, dmsobject.seconds
Determine the required CSS class to display coordinates
local factor = 0
 
local precision = 0
Usually geo-nondefault is hidden by CSS, unless a user has overridden this for himself
if not minutes then minutes = 0 end
default is the mode as specificied by the user when calling the {{coord}} template
if not seconds then seconds = 0 end
mode is the display mode (dec or dms) that we will need to determine the css class for
]]
if direction == "N" or direction == "E" then
function displayDefault(default, mode)
factor = 1
    if default == "" then
elseif direction == "W" or direction == "S" then
        default = "dec"
factor = -1
    end
elseif not direction then
   
makeerror({message = 'no cardinal direction found in coordinates', sortkey = 'A'})
    if default:sub(1,4) == mode:sub(1,4) then
return nil
        return "geo-default"
else
    else
makeerror({message = 'invalid direction', sortkey = 'A'})
        return "geo-nondefault"
return nil
    end
end
if dmsobject.seconds then -- vérifie la précision des données initiales
precision = 5 + math.max( math_mod._precision(tostring(seconds), 0 ) ) -- passage par des strings assez tarabiscoté ?
elseif dmsobject.minutes then
precision = 3 + math.max( math_mod._precision(tostring(minutes), 0 ) )
else
precision = math.max( math_mod._precision(tostring(degrees), 0 ) )
end
local decimal = factor * (degrees+(minutes+seconds/60)/60)
return math_mod._round(decimal, precision)
end
end


function p.dms2dec(frame) -- legacy function, somewhat bizarre syntax
--[[
local args = frame.args
Check the input arguments for coord to determine the kind of data being provided
if tonumber(args[1]) then  
and then make the necessary processing.
return args[1] -- coordonnées déjà en décimal
]]
elseif not args[2] then
function formatTest(args)
return p._dms2dec(parsedmsstring(args[1])) -- coordonnées sous la fore 23/22/N
    local result, errors;
else
    local primary = false;
return p._dms2dec({direction = args[1], degrees = args[2], minutes = args[3], seconds = args[4]})
   
end
    if args[1] == "" then
        -- no lat logic
        return errorPrinter( {{"formatTest", "Missing latitude"}} )
    elseif args[4] == "" and args[5] == "" and args[6] == "" then
        -- dec logic
        result, errors = parseDec( args[1], args[2], args['format'] )
        if result == nil then
            return errorPrinter( errors );
        end             
        result.param    = table.concat( {args[1], "_N_", args[2], "_E_", args[3] } );
    elseif dmsTest(args[4], args[8]) then
        -- dms logic
        result, errors = parseDMS( args[1], args[2], args[3], args[4],
            args[5], args[6], args[7], args[8], args['format'] )
        result.param = table.concat( { args[1], args[2], args[3], args[4], args[5],
            args[6], args[7], args[8], args[9] } , '_' );
        if args[10] ~= '' then
            table.insert( errors, { 'formatTest', 'Extra unexpected parameters' } );
        end       
    elseif dmsTest(args[3], args[6]) then
        -- dm logic
        result, errors = parseDMS( args[1], args[2], nil, args[3],
            args[4], args[5], nil, args[6], args['format'] )
        result.param = table.concat( { args[1], args[2], args[3], args[4], args[5],
            args[6], args[7] } , '_' );
        if args[8] ~= '' then
            table.insert( errors, { 'formatTest', 'Extra unexpected parameters' } );
        end       
    elseif dmsTest(args[2], args[4]) then
        -- d logic
        result, errors = parseDMS( args[1], nil, nil, args[2],
            args[3], nil, nil, args[4], args['format'] )
        result.param = table.concat( { args[1], args[2], args[3], args[4], args[5] } , '_' );
        if args[6] ~= '' then
            table.insert( errors, { 'formatTest', 'Extra unexpected parameters' } );
        end       
    else
        -- Error
        return errorPrinter( {{"formatTest", "Unknown argument format"}} )
    end
    result.name    = args["name"]
   
    local extra_param = {'dim', 'globe', 'scale', 'region', 'source', 'type', 'scale', 'src'}
    for _, v in ipairs( extra_param ) do
        if (args[v] or '') ~= '' then
            table.insert( errors, {'formatTest', 'Parameter: "' .. v .. '=" should be "' .. v .. ':"' } );
        end
    end
   
    if #errors == 0 then
        return specPrinter( args, result )   
    else
    local cat = ''
    if mw.title.getCurrentTitle().namespace == 0 then
    cat = '[[Catégorie:Article posant un problème de coordonnées]]'
    end
        return specPrinter( args, result ) .. " " .. errorPrinter(errors) .. cat
    end  
end
end


function parsedmsstring(str) -- prend une séquence et donne des noms aux paramètres
--[[
-- output table: {latitude=, longitude = , direction = }
Helper function, convert decimal latitude or longitude to
if not tonumber(str) and not string.find(str, '/') then
degrees, minutes, and seconds format based on the specified precision.  
makeerror({message ='invalid coordinate format', sortkey= 'A'})
]]
return nil
function convert_dec2dms(coordinate, firstPostfix, secondPostfix, precision)
end
    local coord = tonumber(coordinate) or 0
args = mw.text.split(str, '/', true)
    local postfix
if #args > 4 then
    if coord >= 0 then
makeerror({message = "too many parameters for coordinates", sortkey= 'A' })
        postfix = firstPostfix
end
    else
local direction = args[#args]
        postfix = secondPostfix
table.remove(args)
    end
local degrees, minutes, seconds = args[1], args[2], args[3]
 
local dimensionobject = builddmsdimension(degrees, minutes, seconds, direction)
    precision = precision:lower();
if validdms(dimensionobject) then
    if precision == "dms" then
return dimensionobject
        return convert_dec2dms_dms( math.abs( coord ) ) .. postfix;
else
    elseif precision == "dm" then
return nil
        return convert_dec2dms_dm( math.abs( coord ) ) .. postfix;
end
    elseif precision == "d" then
        return convert_dec2dms_d( math.abs( coord ) ) .. postfix;
    end
end
end


function builddmsdimension(degrees, minutes, seconds, direction)
--[[ Helper function, convert decimal to degrees ]]
-- no error checking, done in function validdms
function convert_dec2dms_d(coordinate)
local dimensionobject = {}
    local d = math_mod._round( coordinate, 0 ) .. "°&nbsp;"
    return d .. ""
end


--[[ Helper function, convert decimal to degrees and minutes ]]
-- direction and dimension (= latitude or longitude)
function convert_dec2dms_dm(coordinate)  
dimensionobject.direction = direction
    coordinate = math_mod._round( coordinate * 60, 0 );
if direction == 'N' or direction == 'S' then
    local m = coordinate % 60;
dimensionobject.dimension = 'latitude'
    coordinate = math.floor( (coordinate - m) / 60 );
else
    local d = coordinate % 360 .."°&nbsp;"
dimensionobject.dimension = 'longitude'
   
end
    return d .. string.format( "%02d′&nbsp;", m )
-- degrees, minutes, seconds
dimensionobject.degrees = tonumber(degrees)
dimensionobject.minutes = tonumber(minutes)
dimensionobject.seconds = tonumber(seconds)
if degrees and not dimensionobject.degrees then dimensionobject.degrees = 'error' end
if minutes and not dimensionobject.minutes then dimensionobject.minutes = 'error' end
if seconds and not dimensionobject.seconds then dimensionobject.seconds = 'error' end
return dimensionobject
end
end


function p.displaydmsdimension(valuetable, format) -- formate en latitude ou une longitude dms
--[[ Helper function, convert decimal to degrees, minutes, and seconds ]]
local str = ''
function convert_dec2dms_dms(coordinate)
local direction = valuetable.direction
    coordinate = math_mod._round( coordinate * 60 * 60, 0 );
local degrees, minutes, seconds = '', '', ''
    local s = coordinate % 60
local dimension
    coordinate = math.floor( (coordinate - s) / 60 );
    local m = coordinate % 60
    coordinate = math.floor( (coordinate - m) / 60 );
    local d = coordinate % 360 .."°&nbsp;"


if format == 'dms long' then
    return d .. string.format( "%02d′&nbsp;", m ) .. string.format( "%02d″&nbsp;", s )
direction = i18n[direction .. 'long']
else
direction = i18n[direction]
end
degrees = valuetable.degrees .. i18n.degrees
if valuetable.minutes then
minutes = valuetable.minutes .. i18n.minutes
if (valuetable.minutes < 10) then
minutes = '0' .. minutes
end
end
if valuetable.seconds then
seconds = valuetable.seconds .. i18n.seconds
if (valuetable.seconds < 10) then
seconds = '0' .. seconds
end
end
return degrees .. minutes .. seconds .. direction
end
end


function validdms(coordtable)
--[[
local direction = coordtable.direction
Convert DMS format into a N or E decimal coordinate
local degrees = coordtable.degrees or 0
]]
local minutes = coordtable.minutes or 0
function convert_dms2dec(direction_str, degrees_str, minutes_str, seconds_str)
local seconds = coordtable.seconds or 0
    local degrees = tonumber(degrees_str) or 0
local dimension = coordtable.dimension
    local minutes = tonumber(minutes_str) or 0
    local seconds = tonumber(seconds_str) or 0
if type(degrees) ~= 'number' or type(minutes) ~= 'number' or type(seconds) ~= 'number' then
    local direction = direction_str:match( '^%s*(.-)%s*$' );  --remove whitespace
makeerror({message = 'coordinates should be numeric', sortkey = 'A'})
   
return false
    local factor
end
    if direction == "N" or direction == "E" then
        factor = 1
if dimension == 'latitude' and direction ~= 'N' and direction ~= 'S' then
    else
makeerror({message = 'could not find latitude direction (should be N or S)', sortkey = 'A'})
        factor = -1
return false
    end
end
   
if dimension == 'longitude' and direction ~= 'W' and direction ~= 'E' then
    local precision = 0
makeerror({message = 'could not find longitude direction (should be W or E) ', sortkey = 'A'})
    if seconds_str ~= nil and seconds_str ~= '' then
return false
        precision = 5 + math.max( math_mod._precision(seconds_str), 0 );
end
    elseif minutes_str ~= nil and minutes_str ~= '' then
        precision = 3 + math.max( math_mod._precision(minutes_str), 0 );
if dimension == 'latitude' and degrees > 90 then
    else
makeerror({'latitude > 90', sortkey = 'A'})
        precision = math.max( math_mod._precision(degrees_str), 0 );
return false
    end
end
   
    local decimal = factor * (degrees+(minutes+seconds/60)/60)  
if dimension == 'longitude' and degrees > 180 then
    return string.format( "%." .. precision .. "f", decimal ) -- not tonumber since this whole thing is string based.
makeerror({'longitude > 180', sortkey = 'A'})
return false
end
if degrees < 0 or minutes < 0 or seconds < 0 then
makeerror({message = 'dms coordinates should be positive', sortkey = 'A'})
return false
end
if (math.floor(degrees) ~= degrees and minutes ~= 0) or (math.floor(minutes) ~= minutes and seconds ~= 0) then
makeerror({message = 'degrees and minutes should be integers', sortkey = 'A'})
return false
end
return true
end
end


function validlatitude(value) -- decimal latitude
--[[
if type(value) ~= 'number' or math.abs(value) > 90 then
Checks input values to for out of range errors.
makeerror({message = 'latitude should be number < 90, is ' .. (value or 'nil')})
]]
return false
function validate( lat_d, lat_m, lat_s, long_d, long_m, long_s, source, strong )
end
    local errors = {};
return true
    lat_d = tonumber( lat_d ) or 0;
    lat_m = tonumber( lat_m ) or 0;
    lat_s = tonumber( lat_s ) or 0;
    long_d = tonumber( long_d ) or 0;
    long_m = tonumber( long_m ) or 0;
    long_s = tonumber( long_s ) or 0;
 
    if strong then
        if lat_d < 0 then
            table.insert(errors, {source, "latitude degrees < 0 with hemisphere flag"})
        end
        if long_d < 0 then
            table.insert(errors, {source, "longitude degrees < 0 with hemisphere flag"})
        end
        --[[
        #coordinates is inconsistent about whether this is an error.  If globe: is
        specified, it won't error on this condition, but otherwise it will.
       
        For not simply disable this check.
       
        if long_d > 180 then
            table.insert(errors, {source, "longitude degrees > 180 with hemisphere flag"})
        end
        ]]
    end   
       
    if lat_d > 90 then
        table.insert(errors, {source, "latitude degrees > 90"})
    end
    if lat_d < -90 then
        table.insert(errors, {source, "latitude degrees < -90"})
    end
    if lat_m >= 60 then
        table.insert(errors, {source, "latitude minutes >= 60"})
    end
    if lat_m < 0 then
        table.insert(errors, {source, "latitude minutes < 0"})
    end
    if lat_s >= 60 then
        table.insert(errors, {source, "latitude seconds >= 60"})
    end
    if lat_s < 0 then
        table.insert(errors, {source, "latitude seconds < 0"})
    end
    if long_d >= 360 then
        table.insert(errors, {source, "longitude degrees >= 360"})
    end
    if long_d <= -360 then
        table.insert(errors, {source, "longitude degrees <= -360"})
    end
    if long_m >= 60 then
        table.insert(errors, {source, "longitude minutes >= 60"})
    end
    if long_m < 0 then
        table.insert(errors, {source, "longitude minutes < 0"})
    end
    if long_s >= 60 then
        table.insert(errors, {source, "longitude seconds >= 60"})
    end
    if long_s < 0 then
        table.insert(errors, {source, "longitude seconds < 0"})
    end
   
    return errors;
end
end


function validlongitude(value) -- decimal longitude
--[[
if type(value) ~= 'number' or math.abs(value) > 180 then
dec2dms
makeerror({message = 'longitude should be number < 180, is ' .. (value or 'nil')})
 
return false
Wrapper to allow templates to call dec2dms directly.
end
return true
end


function p.displaydec(latitude, longitude, format)
Usage:
if format == 'dec west' then
    {{ Invoke:Coordinates | dec2dms | decimal_coordinate | positive_suffix |
local latsymbol = i18n.N
        negative_suffix | precision }}
longitude = - longitude
   
if latitude < 0 then latsymbol = i18n.S end
decimal_coordinate is converted to DMS format. If positive, the positive_suffix
if longitude < 0 then
is appended (typical N or E), if negative, the negative suffix is appended.  The
long = 360 + longitude
specified precision is one of 'D', 'DM', or 'DMS' to specify the level of detail
end
to use.
return latitude .. i18n.degrees .. latsymbol .. ', ' .. longitude ..  i18n.degrees .. i18n.W
]]
function coordinates.dec2dms(frame)
elseif format == 'dec west' then
    globalFrame = frame
local latsymbol = i18n.N
    local coordinate = frame.args[1]
if latitude < 0 then latsymbol = i18n.S end
    local firstPostfix = frame.args[2]
if longitude < 0 then
    local secondPostfix = frame.args[3]
longitude = 360 + longitude
    local precision = frame.args[4]
end
return latitude .. i18n.degrees .. latsymbol .. ', ' .. longitude  ..  i18n.degrees .. i18n.E
else
return latitude .. ', ' .. longitude
end
end


function wikidatacoords(query)
    return convert_dec2dms(coordinate, firstPostfix, secondPostfix, precision)
query = query or {property = 'p625'}
local wd = require('Module:Wikidata')
local claim = wd.getClaims(query)
if claim and claim[1] then -- redundant but more robust in case of a change in the code of Module:Wikidata
local coords = wd.formatSnak(claim[1].mainsnak) -- todo: check for special values
return coords.latitude, coords.longitude, coords.globe
end
return nil
end
end


--- fonctions principales
--[[
function p._coord(args)
Helper function to determine whether to use D, DM, or DMS
local latitude, longitude = tonumber(args.latitude), tonumber(args.longitude) -- must be in decimal format
format depending on the precision of the decimal input.
if latitude and longitude and (not validlatitude(latitude) or not validlongitude(longitude)) then
]]
return showerrors()
function coordinates.determineMode( value1, value2 )
end
    local precision = math.max( math_mod._precision( value1 ), math_mod._precision( value2 ) );
local displayformat, inputformat = args.format, args.inputformat -- one of: 'dms', 'dms long', 'dec', 'dec east' and 'dec west'
    if precision <= 0 then
local displayplace = string.lower(args.display or 'inline') -- on of 'inline', 'title' or 'inline,title'
        return 'd'
local globe = string.lower(args.globe or '') -- planet see the globedata table for accepted values
    elseif precision <= 2 then
local objectname = args.name -- name of the title displayed in geohack
        return 'dm';
local notes = (' ' and args.notes) or '' -- notes à afficher après les coordonnées
    else
local wikidata = args.wikidata -- string set to true when
        return 'dms';
local dmslatitude, dmslongitude -- type: table when created
local extraparams = string.lower(args.extraparams or '') -- chaîne destinée à geohack dernier paramètre avec argument numérique dans {{Coord}}
local wikidataquery = args.wikidataquery
local trackingstring = '' -- tracking cats except error cats (already in errorstring)
-- parsage des donnés en format non-décimal
if (not latitude and args.latitude and args.latitude ~= '') then -- latitude was not a number
dmslatitude = parsedmsstring(args.latitude)
if not dmslatitude then return showerrors() end
latitude = p._dms2dec(dmslatitude)
end
if (not longitude and args.longitude and args.longitude ~= '') then -- latitude was not a number
dmslongitude = parsedmsstring(args.longitude)
if not dmslongitude then return showerrors() end
longitude = p._dms2dec(dmslongitude)
end
-- récuparation des coordonnées Wikidata
local wikidatalatitude, wikidatalongitude, wikidataglobe
if wikidata == 'true' then
wikidatalatitude, wikidatalongitude, wikidataglobe = wikidatacoords(wikidataquery)
end
if wikidatalatitude and latitude then
local maxdistance = tonumber(args.maxdistance) or wikidatathreshold
if p._distance({latitude = latitude, longitude= longitude}, {latitude = wikidatalatitude, longitude= wikidatalongitude}, wikidataglobe) < maxdistance then
trackingstring = trackingstring .. makecat(i18n.sameaswikidata)
else
trackingstring = trackingstring .. makecat(i18n.notaswikidata)
end
end
if wikidatalatitude and not latitude then
latitude, longitude, globe = wikidatalatitude, wikidatalongitude, wikidataglobe
trackingstring = trackingstring .. makecat(i18n.throughwikidata)
end
-- exit if stil no latitude or not longitude
if not latitude and not longitude then
return nil -- ne rien ajouter ici pour que l'appel à cette fonction retourne bien nil en l'absence de données
end
if not latitude or not longitude then
makeerror({message = 'latitude or longitude missing', sortkey = 'A'})
return showerrors()
end
-- best guesses for missing parameters
--- globe
if globe == '' then -- cherche le globe dans l'extraparams destinée à geohack
local globe2 = string.match(extraparams, 'globe\:%a+')
if globe2 then globe = string.sub(globe2, 7) end
end
if globe == '' then
globe = 'earth'
end
if not globedata[globe] then
makeerror({message = 'invalid globe:' .. globe})
globe = 'earth'
end
--- diplayformat
if not displayformat or displayformat == '' then
if dmslatitude then -- keeps the same format for output as for input, but dms by default when coordinates come from Wikidata
displayformat = 'dms'
else
displayformat = 'dec'
end
end
-- displayinline/displaytitle
    local displayinline =  string.find(displayplace, 'inline')
    local displaytitle = string.find(displayplace, 'title')
    if not displayinline and not displaytitle then
    displayinline = true
    if displayplace ~= '' then
    makeerror({sortkey = 'C'}) --error if display not empty, but not not a major error, continue
    end
    end
    if displaytitle and mw.title.getCurrentTitle().namespace == 0 then
    trackingstring = trackingstring .. makecat(globedata[globe].trackingcat)
     end
     end
end       
--[[
dms2dec
Wrapper to allow templates to call dms2dec directly.
Usage:
    {{ Invoke:Coordinates | dms2dec | direction_flag | degrees |
        minutes | seconds }}
   
Converts DMS values specified as degrees, minutes, seconds too decimal format.
direction_flag is one of N, S, E, W, and determines whether the output is
positive (i.e. N and E) or negative (i.e. S and W).
]]
function coordinates.dms2dec(frame)
    globalFrame = frame
   
    local direction = frame.args[1]
    local degrees = frame.args[2]
    local minutes = frame.args[3]
    local seconds = frame.args[4] 
      
      
-- standardize format for astronomical objects so that it can be used by geohack (back converted afterwards, pretty fast)
    if frame.args[2] == nil then
if inputformat == 'dec east' then
        local explode=mw.text.split( frame.args[1]:match( '^%s*(.-)%s*$' ), '/' )
if longitude > 180 then
        if (#explode > 1) then
longitude = longitude - 360
            direction = explode[#explode]
end
            degrees = explode[1]
longitude = - longitude
        else
end
            local sign, val=string.match (explode[1], '([\-]*)([%d.]*)')
if inputformat == 'dec west' then
            if sign == '-' then direction='S' else direction='N' end
if longitude > 180 then
            degrees = val
longitude = longitude - 360
        end   
end
        if(#explode>2) then  
end
            minutes = explode[2]
        end
        if(#explode>3) then  
            seconds = explode[3]
        end
    end    
 
    return convert_dms2dec(direction, degrees, minutes, seconds)
end


-- finish up
--[[
if not dmslatitude then
coord
dmslatitude, dmslongitude = p._dec2dms(latitude, 'latitude'), p._dec2dms(longitude, 'longitude')
end
extraparams = extraparams .. '_globe:' .. globe -- pas de problème si le globe est en double
-- final output
local mainstring = ''


mainstring = buildHTML(latitude, longitude, dmslatitude, dmslongitude, globe, displayformat, displayinline, displaytitle, objectname,extraparams )
Main entry point for Lua function to replace {{coord}}
return mainstring .. notes .. trackingstring .. showerrors()
end


function p.coord(frame) -- parrses the strange parameters of Template:Coord before sending them to p.coord
Usage:
local args = frame.args
    {{ Invoke:Coordinates | coord }}
local numericargs = {}
    {{ Invoke:Coordinates | coord | lat | long }}
for i, j in ipairs(args) do
    {{ Invoke:Coordinates | coord | lat | lat_flag | long | long_flag }}
args[i] = mw.text.trim(j)
    ...
if type(i) == 'number' and args[i] ~= '' then
   
table.insert(numericargs, args[i])
    Refer to {{coord}} documentation page for many additional parameters and
end
    configuration options.
end
   
Note: This function provides the visual display elements of {{coord}}. In
order to load coordinates into the database, the {{#coordinates:}} parser
function must also be called, this is done automatically in the Lua
version of {{coord}}.
]]


function wikidatacoords(dimension) --récupère les coordonnées sur Wikidata (2013-08/2013-09 intégration wikidata >> Utilisateur Zolo, Tpt & Xfigpowert)
        local item = mw.wikibase.getEntity()
        if item and item.claims and item.claims['p625'] then
            for _, statement in pairs( item.claims['p625'] ) do
                if statement.mainsnak.snaktype == 'value' then
                    return tostring( statement.mainsnak.datavalue.value[dimension])
                end
            end
        end   
end


if #numericargs == 1 then
function coordinates.latitude(frame) -- retourne nil quand il n'y a pas de latitude (nécessaire pour certains modèles)
makeerror({message = 'invalid coordinates format', sortkey = 'A'})
if frame.args[1] and frame.args[1] ~= ''then
return showerrors()
return frame.args[1]
elseif #numericargs %2 == 1 then -- if the number of args is odd, the last one provides formatting parameters
elseif frame.args['wikidata'] == 'true' then
args.extraparams = numericargs[#numericargs]
return wikidatacoords('latitude')
table.remove(numericargs)
end
for i, j in ipairs(numericargs) do
if i <= (#numericargs / 2) then
if not args.latitude then
args.latitude = j
else
args.latitude = args.latitude .. '/' .. j
end
else
if not args.longitude then
args.longitude = j
else
args.longitude = args.longitude .. '/' .. j
end
end
end
end
end


if string.find(args.latitude or '', 'E') or string.find(args.latitude or '', 'W') then
function coordinates.longitude(frame)
args.latitude, args.longitude = args.longitude, args.latitude
if frame.args[1] and frame.args[1] ~= ''then
end
return frame.args[1]
if args.formatitle then -- legacy parameter
elseif frame.args['wikidata'] == 'true' then
args.display = 'inline'
return wikidatacoords('longitude')
local inline = p._coord(args)
args.display = 'title'
args.format = args.formatitle
local title = p._coord(args)
return (inline or '') .. (title or '')
else
return p._coord(args)
end
end
end
end


function p.Coord(frame)
function coordinates.coord(frame)
return p.coord(frame)
    globalFrame = frame
   
    local text = ''
   
    local args = frame.args
    if args[1] == nil then
        local pFrame = frame:getParent();
        args = pFrame.args;
        for k,v in pairs( frame.args ) do
            args[k] = v;
        end
    end
   
    for i=1,10 do
        if args[i] == nil then
            args[i] = ""
        else
            args[i] = args[i]:match( '^%s*(.-)%s*$' );  --remove whitespace
        end       
    end
    args['format'] = args['format'] or '';
   
    if args[2] == '' and args['wikidata'] == 'true' then
        local arggeo=args[1]
args[1] = wikidatacoords('latitude')
args[2] = wikidatacoords('longitude')
    end
    local latdms=mw.text.split( args[1], '/' )
    local lngdms=mw.text.split( args[2], '/' )
    if #latdms > 1 or #lngdms >1 then
        -- je copie
        local argsN=mw.clone(args) 
        local i = 1 -- point de départ
        local ia = 1 -- point de départ
        while (latdms[i] ~= nil) do
          args[ia]=mw.text.trim(latdms[i])
          i = i + 1
          ia = ia +1
        end
        local i = 1 -- point de départ
        while (lngdms[i] ~= nil) do
          args[ia]=mw.text.trim(lngdms[i])
          i = i + 1
          ia = ia +1
        end
        local i = 3 -- point de départ
        while (argsN[i] ~= nil) do
          args[ia]=argsN[i]
          i = i + 1
          ia = ia +1
        end
    end
 
    --définition de la planète
    local astre
    for _, l in ipairs(args) do
        for w in string.gmatch(l, "globe:(%a+)") do
            astre=w
            break
        end
    end
 
    --par défaut, on format pour un affichage en ligne
    local contents = formatTest(args)
    local Notes = args.notes or ""
    local Display = string.lower(args.display or "inline")
    if Display == '' then
        Display = 'inline';
    end
    local havedisplay = "";
   
    if string.find( Display, 'inline' ) ~= nil or Display == 'i' or
            Display == 'it' or Display == 'ti' then
        text = text .. displayinline(contents, Notes)
        havedisplay = havedisplay .. "i";
    end
    if string.find( Display, 'title' ) ~= nil or Display == 't' or
            Display == 'it' or Display == 'ti' then
        if args['formatitle'] ~= nil then
            args['format'] = args['formatitle'] or args['format']
            contents = formatTest(args)
        end 
        text = text .. displaytitle(contents, Notes, astre)
        args['geodata']="primary"
        text = text ..  globalFrame:preprocess(formatTest(args) )
       
        havedisplay = havedisplay .. "t";
    end
   
    if havedisplay == "" then
        --rien n'a été affiché!
        text = text .. displayinline(contents, Notes) .. errorPrinter( {{"display", "argument display incorrect"}} )
       
    end   
   
    return text
end
end


function p.latitude(frame) -- helper function for infoboxes, à déprécier
function coordinates.Coord(frame)
if frame.args[1] and frame.args[1] ~= '' then
    return coordinates.coord(frame)
return frame.args[1]
else
return wikidatacoords(frame.args.query)
end
end
end


return p
 
return coordinates

Version du 18 février 2014 à 23:07

La documentation pour ce module peut être créée à Module:Coordinates/doc

--[[
This module is intended to replace the functionality of {{Coord}} and related
templates.  It provides several methods, including

{{#Invoke:Coordinates | coord }} : General function formatting and displaying
coordinate values.

{{#Invoke:Coordinates | dec2dms }} : Simple function for converting decimal
degree values to DMS format.

{{#Invoke:Coordinates | dms2dec }} : Simple function for converting DMS format
to decimal degree format.

]]

math_mod = require( "Module:Math" );
globalFrame = nil

coordinates = {};

--[[ Helper function, replacement for {{coord/display/title}} ]]
function displaytitle (s, notes ,globe)
    --local l = "[[Geographic coordinate system|Coordinates]]: " .. s
    local l = "" .. s
    local extracat = ""
    
    if mw.title.getCurrentTitle().nsText == "" then
        if globe~= nil and globe~= "earth" then
            if globe == "moon" then
                extracat = "[[Catégorie:Article géolocalisé sur la Lune]]";                
            elseif globe == "mars" then
                extracat = "[[Catégorie:Article géolocalisé sur Mars]]";
            else
                extracat = "[[Catégorie:Article géolocalisé extraterrestre]]";
            end            
        else
            extracat = "[[Catégorie:Article géolocalisé sur Terre]]";
        end
    end
    
    local co = '<span id="coordinates">' .. l .. notes .. '</span>';
    return '<span style="font-size: small;">' .. co .. '</span>' .. extracat;
end

--[[ Helper function, Replacement for {{coord/display/inline}} ]]
function displayinline (s, notes)
    return s .. notes    
end

--[[ Helper function, used in detecting DMS formatting ]]
local dmsTest = function(first, second)
    local concatenated = first:upper() .. second:upper();
    
    return concatenated == "NE" or concatenated == "NO" or concatenated == "NW" or concatenated == "SE" or concatenated == "SO"  or concatenated == "SW" or
        concatenated == "EN" or concatenated == "ON" or concatenated == "WN" or concatenated == "ES" or concatenated == "OS"  or concatenated == "WS"
end

--[[
parseDec

Transforms decimal format latitude and longitude into the a
structure to be used in displaying coordinates
]]
function parseDec( lat, long, format )
    local coordinateSpec = {}
    local errors = {}
    
    if long == "" or long == nil then
        return nil, {{"parseDec", "Missing longitude"}}
    end
    
    errors = validate( lat, nil, nil, long, nil, nil, 'parseDec', false );    
    coordinateSpec["dec-lat"]  = lat;
    coordinateSpec["dec-long"] = long;

    local mode = coordinates.determineMode( lat, long );
    coordinateSpec["dms-lat"]  = convert_dec2dms( lat, "N", "S", mode)  -- {{coord/dec2dms|{{{1}}}|N|S|{{coord/prec dec|{{{1}}}|{{{2}}}}}}}
    coordinateSpec["dms-long"] = convert_dec2dms( long, "E", "O", mode)  -- {{coord/dec2dms|{{{2}}}|E|W|{{coord/prec dec|{{{1}}}|{{{2}}}}}}}  
    coordinateSpec["dmslong-lat"]  = convert_dec2dms( lat, "Nord", "Sud", mode)  -- {{coord/dec2dms|{{{1}}}|N|S|{{coord/prec dec|{{{1}}}|{{{2}}}}}}}
    coordinateSpec["dmslong-long"] = convert_dec2dms( long, "Est", "Ouest", mode)  -- {{coord/dec2dms|{{{2}}}|E|W|{{coord/prec dec|{{{1}}}|{{{2}}}}}}}      
    
    if format ~= "" then
        coordinateSpec.default = format
    else
        coordinateSpec.default = "dec"
    end

    return coordinateSpec, errors
end

--[[ Helper function, handle optional args. ]]
function optionalArg(arg, suplement)
    if arg ~= nil and arg ~= "" then
        return arg .. suplement
    end
    return ""
end

--[[
parseDMS

Transforms degrees, minutes, seconds format latitude and longitude 
into the a structure to be used in displaying coordinates
]]
function parseDMS( lat_d, lat_m, lat_s, lat_f, long_d, long_m, long_s, long_f, format )
    local coordinateSpec = {}
    local errors = {}
    
    lat_f = lat_f:upper();
    long_f = string.gsub(long_f:upper(),'W','O');

    local lat_flong = 'Nord';
    if lat_f == 'S' then
        lat_flong = 'Sud';
    end
    local long_flong = 'Ouest';
    if long_f == 'E' then
        long_flong = 'Est';
    end
    
    
    -- Check if specified backward
    if lat_f == 'E' or lat_f == 'O' or lat_f == 'W' then
        local t_d, t_m, t_s, t_f;
        t_d = lat_d;
        t_m = lat_m;
        t_s = lat_s;
        t_f = lat_f;
        lat_d = long_d;
        lat_m = long_m;
        lat_s = long_s;
        lat_f = long_f;
        long_d = t_d;
        long_m = t_m;
        long_s = t_s;
        long_f = t_f;
    end    
    
    errors = validate( lat_d, lat_m, lat_s, long_d, long_m, long_s, 'parseDMS', true );
    if long_d == nil or long_d == "" then
        table.insert(errors, {"parseDMS", "Missing longitude" })
    end
    
    if lat_m == nil and lat_s == nil and long_m == nil and long_s == nil and #errors == 0 then 
        if math_mod._precision( lat_d ) > 0 or math_mod._precision( long_d ) > 0 then
            if lat_f:upper() == 'S' then 
                lat_d = '-' .. lat_d;
            end
            if long_f:upper() == 'O' or long_f:upper() == 'W' then 
                long_d = '-' .. long_d;
            end     
            
            return parseDec( lat_d, long_d, format );
        end        
    end   
    
    coordinateSpec["dms-lat"]  = lat_d.."°&nbsp;"..optionalArg(lat_m,"′&nbsp;") .. optionalArg(lat_s,"″&nbsp;") .. lat_f
    coordinateSpec["dmslong-lat"]  = lat_d.."°&nbsp;"..optionalArg(lat_m,"′&nbsp;") .. optionalArg(lat_s,"″&nbsp;") .. lat_flong
    coordinateSpec["dms-long"] = long_d.."°&nbsp;"..optionalArg(long_m,"′&nbsp;") .. optionalArg(long_s,"″&nbsp;") .. long_f
    coordinateSpec["dmslong-long"] = long_d.."°&nbsp;"..optionalArg(long_m,"′&nbsp;") .. optionalArg(long_s,"″&nbsp;") .. long_flong
    coordinateSpec["dec-lat"]  = convert_dms2dec(lat_f, lat_d, lat_m, lat_s) -- {{coord/dms2dec|{{{4}}}|{{{1}}}|0{{{2}}}|0{{{3}}}}}
    coordinateSpec["dec-long"] = convert_dms2dec(long_f, long_d, long_m, long_s) -- {{coord/dms2dec|{{{8}}}|{{{5}}}|0{{{6}}}|0{{{7}}}}}
    
    if format ~= "" then
        coordinateSpec.default = format
    else
        coordinateSpec.default = "dms"
    end   

    return coordinateSpec, errors
end

--[[
specPrinter

Output formatter.  Takes the structure generated by either parseDec
or parseDMS and formats it for inclusion on Wikipedia.
]]
function specPrinter(args, coordinateSpec)
    local uriComponents = coordinateSpec["param"]
    if uriComponents == "" then
        -- RETURN error, should never be empty or nil
        return "ERROR param was empty"
    end
        
    if args["name"] ~= "" and args["name"] ~= nil then
        uriComponents = uriComponents .. "&title=" .. mw.uri.encode(coordinateSpec["name"])
    end
    
    local lang=mw.language.getContentLanguage():getCode();
    
    local geodmshtml = '<span class="geo-dms" title="Cartes, vues aériennes et autres données pour cet endroit">'
             .. '<span class="latitude">' .. coordinateSpec["dms-lat"] .. '</span> '
             .. '<span class="longitude">' ..coordinateSpec["dms-long"] .. '</span>'
             .. '</span>'
    local geodmslonghtml = '<span class="geo-dms" title="Cartes, vues aériennes et autres données pour cet endroit">'
             .. '<span class="latitude">' .. coordinateSpec["dmslong-lat"] .. '</span> '
             .. '<span class="longitude">' ..coordinateSpec["dmslong-long"] .. '</span>'
             .. '</span>'
    local lat = tonumber( coordinateSpec["dec-lat"] ) or 0
    if lat < 0 then
        -- FIXME this breaks the pre-existing precision
        --geodeclat = coordinateSpec["dec-lat"]:sub(2) .. "°S"
        geodeclat = "-" .. coordinateSpec["dec-lat"]:sub(2)
    else
        --geodeclat = (coordinateSpec["dec-lat"] or 0) .. "°N"
        geodeclat = (coordinateSpec["dec-lat"] or 0)
    end

    local long = tonumber( coordinateSpec["dec-long"] ) or 0
    if long < 0 then
        -- FIXME does not handle unicode minus
        --geodeclong = coordinateSpec["dec-long"]:sub(2) .. "°O"
        geodeclong = '-' .. coordinateSpec["dec-long"]:sub(2)
    else
        --geodeclong = (coordinateSpec["dec-long"] or 0) .. "°E"
        geodeclong = (coordinateSpec["dec-long"] or 0)
    end
    
    local geodechtml = '<span class="geo-dec" title="Cartes, vues aériennes et autres données pour cet endroit">'
             .. geodeclat .. ', '
             .. geodeclong
             .. '</span>'

    local geonumhtml = '<span class="geo">'
             .. coordinateSpec["dec-lat"] .. '; '
             .. coordinateSpec["dec-long"]
             .. '</span>'

--cf http://www.mediawiki.org/wiki/Extension:GeoData
    local geodata = ''
    local r,s,t=string.match (coordinateSpec["param"],'(.*)_(E?W?)_(.*)')
    local globe,globend=string.match (coordinateSpec["param"],'_globe:(.*)(_*)')
    --Désactivé pour les astres à cause de problèmes de longitudes planétocentriques/planétographiques
    if globe == nil or globe == 'earth' then
    	geodata = '{{#coordinates:' .. coordinateSpec["dec-lat"] .. '|' .. coordinateSpec["dec-long"] .. '|primary|' .. t .. '}}'
    end
    if args['geodata'] ~= nil then
        return geodata;
    end
    
    local inner;
    if coordinateSpec["default"] == "dms" then
        inner = '<span class="' .. displayDefault(coordinateSpec["default"], "dms" ) .. '">' .. geodmshtml .. '</span>'
                    .. '<span class="geo-multi-punct">&#xfeff; / &#xfeff;</span>'
                    .. '<span class="' .. displayDefault(coordinateSpec["default"], "dec" ) .. '">';
    else
        inner = '<span class="' .. displayDefault(coordinateSpec["default"], "dms long" ) .. '">' .. geodmslonghtml .. '</span>'
                    .. '<span class="geo-multi-punct">&#xfeff; / &#xfeff;</span>'
                    .. '<span class="' .. displayDefault(coordinateSpec["default"], "dec" ) .. '">';        
    end


    if args["name"] == "" or args["name"] == nil then
        inner = inner .. geodechtml 
                .. '<span style="display:none">&#xfeff; / ' .. geonumhtml .. '</span></span>'
    else
        inner = inner .. '<span class="vcard">' .. geodechtml 
                .. '<span style="display:none">&#xfeff; / ' .. geonumhtml .. '</span>'
                .. '<span style="display:none">&#xfeff; (<span class="fn org">'
                .. args["name"] .. '</span>)</span></span></span>'
    end

    return '<span class="plainlinksneverexpand">' .. globalFrame:preprocess(
        '[//tools.wmflabs.org/geohack/geohack.php?pagename={{FULLPAGENAMEE}}&language=' .. lang .. '&params=' ..
        uriComponents .. ' ' .. inner .. ']') .. '</span>'
end

--[[
Formats any error messages generated for display
]]
function errorPrinter(errors)
    local result = ""
    for i,v in ipairs(errors) do
        local errorHTML = '<strong class="error">Coordonnées: ' .. v[2] .. '</strong>'
        result = result .. errorHTML .. "<br />"
    end
    return result
end

--[[
Determine the required CSS class to display coordinates

Usually geo-nondefault is hidden by CSS, unless a user has overridden this for himself
default is the mode as specificied by the user when calling the {{coord}} template
mode is the display mode (dec or dms) that we will need to determine the css class for 
]]
function displayDefault(default, mode)
    if default == "" then
        default = "dec"
    end
    
    if default:sub(1,4) == mode:sub(1,4) then
        return "geo-default"
    else
        return "geo-nondefault"
    end
end

--[[ 
Check the input arguments for coord to determine the kind of data being provided
and then make the necessary processing.
]]
function formatTest(args)
    local result, errors;
    local primary = false;
    
    if args[1] == "" then
        -- no lat logic
        return errorPrinter( {{"formatTest", "Missing latitude"}} )
    elseif args[4] == "" and args[5] == "" and args[6] == "" then
        -- dec logic
        result, errors = parseDec( args[1], args[2], args['format'] )
        if result == nil then
            return errorPrinter( errors );
        end              
        result.param    = table.concat( {args[1], "_N_", args[2], "_E_", args[3] } );
    elseif dmsTest(args[4], args[8]) then
        -- dms logic
        result, errors = parseDMS( args[1], args[2], args[3], args[4], 
            args[5], args[6], args[7], args[8], args['format'] )
        result.param = table.concat( { args[1], args[2], args[3], args[4], args[5],
            args[6], args[7], args[8], args[9] } , '_' );
        if args[10] ~= '' then
            table.insert( errors, { 'formatTest', 'Extra unexpected parameters' } );
        end        
    elseif dmsTest(args[3], args[6]) then
        -- dm logic
        result, errors = parseDMS( args[1], args[2], nil, args[3], 
            args[4], args[5], nil, args[6], args['format'] )
        result.param = table.concat( { args[1], args[2], args[3], args[4], args[5],
            args[6], args[7] } , '_' );
        if args[8] ~= '' then
            table.insert( errors, { 'formatTest', 'Extra unexpected parameters' } );
        end        
    elseif dmsTest(args[2], args[4]) then
        -- d logic
        result, errors = parseDMS( args[1], nil, nil, args[2], 
            args[3], nil, nil, args[4], args['format'] )
        result.param = table.concat( { args[1], args[2], args[3], args[4], args[5] } , '_' );
        if args[6] ~= '' then
            table.insert( errors, { 'formatTest', 'Extra unexpected parameters' } );
        end        
    else
        -- Error
        return errorPrinter( {{"formatTest", "Unknown argument format"}} )
    end
    result.name     = args["name"]
    
    local extra_param = {'dim', 'globe', 'scale', 'region', 'source', 'type', 'scale', 'src'}
    for _, v in ipairs( extra_param ) do
        if (args[v] or '') ~= '' then 
            table.insert( errors, {'formatTest', 'Parameter: "' .. v .. '=" should be "' .. v .. ':"' } );
        end
    end
    
    if #errors == 0 then
        return specPrinter( args, result )    
    else
    	local cat = ''
    	if mw.title.getCurrentTitle().namespace == 0 then
    		cat = '[[Catégorie:Article posant un problème de coordonnées]]'
    	end
        return specPrinter( args, result ) .. " " .. errorPrinter(errors) .. cat 
    end    
end

--[[ 
Helper function, convert decimal latitude or longitude to 
degrees, minutes, and seconds format based on the specified precision.  
]]
function convert_dec2dms(coordinate, firstPostfix, secondPostfix, precision)
    local coord = tonumber(coordinate) or 0
    local postfix
    if coord >= 0 then
        postfix = firstPostfix
    else
        postfix = secondPostfix
    end

    precision = precision:lower();
    if precision == "dms" then
        return convert_dec2dms_dms( math.abs( coord ) ) .. postfix;
    elseif precision == "dm" then
        return convert_dec2dms_dm( math.abs( coord ) ) .. postfix;
    elseif precision == "d" then
        return convert_dec2dms_d( math.abs( coord ) ) .. postfix;
    end
end

--[[ Helper function, convert decimal to degrees ]]
function convert_dec2dms_d(coordinate)
    local d = math_mod._round( coordinate, 0 ) .. "°&nbsp;"
    return d .. ""
end

--[[ Helper function, convert decimal to degrees and minutes ]]
function convert_dec2dms_dm(coordinate)    
    coordinate = math_mod._round( coordinate * 60, 0 );
    local m = coordinate % 60;
    coordinate = math.floor( (coordinate - m) / 60 );
    local d = coordinate % 360 .."°&nbsp;"
    
    return d .. string.format( "%02d′&nbsp;", m )
end

--[[ Helper function, convert decimal to degrees, minutes, and seconds ]]
function convert_dec2dms_dms(coordinate)
    coordinate = math_mod._round( coordinate * 60 * 60, 0 );
    local s = coordinate % 60
    coordinate = math.floor( (coordinate - s) / 60 );
    local m = coordinate % 60
    coordinate = math.floor( (coordinate - m) / 60 );
    local d = coordinate % 360 .."°&nbsp;"

    return d .. string.format( "%02d′&nbsp;", m ) .. string.format( "%02d″&nbsp;", s )
end

--[[
Convert DMS format into a N or E decimal coordinate
]]
function convert_dms2dec(direction_str, degrees_str, minutes_str, seconds_str)
    local degrees = tonumber(degrees_str) or 0
    local minutes = tonumber(minutes_str) or 0
    local seconds = tonumber(seconds_str) or 0
    local direction = direction_str:match( '^%s*(.-)%s*$' );  --remove whitespace
    
    local factor
    if direction == "N" or direction == "E" then
        factor = 1
    else
        factor = -1
    end
    
    local precision = 0
    if seconds_str ~= nil and seconds_str ~= '' then
        precision = 5 + math.max( math_mod._precision(seconds_str), 0 );
    elseif minutes_str ~= nil and minutes_str ~= '' then
        precision = 3 + math.max( math_mod._precision(minutes_str), 0 );
    else
        precision = math.max( math_mod._precision(degrees_str), 0 );
    end
    
    local decimal = factor * (degrees+(minutes+seconds/60)/60) 
    return string.format( "%." .. precision .. "f", decimal ) -- not tonumber since this whole thing is string based.
end

--[[ 
Checks input values to for out of range errors.
]]
function validate( lat_d, lat_m, lat_s, long_d, long_m, long_s, source, strong )
    local errors = {};
    lat_d = tonumber( lat_d ) or 0;
    lat_m = tonumber( lat_m ) or 0;
    lat_s = tonumber( lat_s ) or 0;
    long_d = tonumber( long_d ) or 0;
    long_m = tonumber( long_m ) or 0;
    long_s = tonumber( long_s ) or 0;

    if strong then
        if lat_d < 0 then
            table.insert(errors, {source, "latitude degrees < 0 with hemisphere flag"})
        end
        if long_d < 0 then
            table.insert(errors, {source, "longitude degrees < 0 with hemisphere flag"})
        end
        --[[ 
        #coordinates is inconsistent about whether this is an error.  If globe: is
        specified, it won't error on this condition, but otherwise it will.
        
        For not simply disable this check.
        
        if long_d > 180 then
            table.insert(errors, {source, "longitude degrees > 180 with hemisphere flag"})
        end
        ]]
    end    
        
    if lat_d > 90 then
        table.insert(errors, {source, "latitude degrees > 90"})
    end
    if lat_d < -90 then
        table.insert(errors, {source, "latitude degrees < -90"})
    end
    if lat_m >= 60 then
        table.insert(errors, {source, "latitude minutes >= 60"})
    end
    if lat_m < 0 then
        table.insert(errors, {source, "latitude minutes < 0"})
    end
    if lat_s >= 60 then
        table.insert(errors, {source, "latitude seconds >= 60"})
    end
    if lat_s < 0 then
        table.insert(errors, {source, "latitude seconds < 0"})
    end
    if long_d >= 360 then
        table.insert(errors, {source, "longitude degrees >= 360"})
    end
    if long_d <= -360 then
        table.insert(errors, {source, "longitude degrees <= -360"})
    end
    if long_m >= 60 then
        table.insert(errors, {source, "longitude minutes >= 60"})
    end
    if long_m < 0 then
        table.insert(errors, {source, "longitude minutes < 0"})
    end
    if long_s >= 60 then
        table.insert(errors, {source, "longitude seconds >= 60"})
    end
    if long_s < 0 then
        table.insert(errors, {source, "longitude seconds < 0"})
    end
    
    return errors;
end

--[[
dec2dms

Wrapper to allow templates to call dec2dms directly.

Usage:
    {{ Invoke:Coordinates | dec2dms | decimal_coordinate | positive_suffix | 
        negative_suffix | precision }}
    
decimal_coordinate is converted to DMS format.  If positive, the positive_suffix
is appended (typical N or E), if negative, the negative suffix is appended.  The
specified precision is one of 'D', 'DM', or 'DMS' to specify the level of detail
to use.
]]
function coordinates.dec2dms(frame)
    globalFrame = frame
    local coordinate = frame.args[1]
    local firstPostfix = frame.args[2]
    local secondPostfix = frame.args[3]
    local precision = frame.args[4]

    return convert_dec2dms(coordinate, firstPostfix, secondPostfix, precision)
end

--[[
Helper function to determine whether to use D, DM, or DMS
format depending on the precision of the decimal input.
]]
function coordinates.determineMode( value1, value2 )
    local precision = math.max( math_mod._precision( value1 ), math_mod._precision( value2 ) );
    if precision <= 0 then
        return 'd'
    elseif precision <= 2 then
        return 'dm';
    else
        return 'dms';
    end
end        

--[[
dms2dec

Wrapper to allow templates to call dms2dec directly.

Usage:
    {{ Invoke:Coordinates | dms2dec | direction_flag | degrees | 
        minutes | seconds }}
    
Converts DMS values specified as degrees, minutes, seconds too decimal format.
direction_flag is one of N, S, E, W, and determines whether the output is 
positive (i.e. N and E) or negative (i.e. S and W).
]]
function coordinates.dms2dec(frame)
    globalFrame = frame
    
    local direction = frame.args[1]
    local degrees = frame.args[2]
    local minutes = frame.args[3]
    local seconds = frame.args[4]  
    
    if frame.args[2] == nil then 
        local explode=mw.text.split( frame.args[1]:match( '^%s*(.-)%s*$' ), '/' )
        if (#explode > 1) then
            direction = explode[#explode]
            degrees = explode[1]
        else
            local sign, val=string.match (explode[1], '([\-]*)([%d.]*)')
            if sign == '-' then direction='S' else direction='N' end
            degrees = val
        end    
        if(#explode>2) then 
            minutes = explode[2]
        end
        if(#explode>3) then 
            seconds = explode[3]
        end
    end     

    return convert_dms2dec(direction, degrees, minutes, seconds)
end

--[[
coord

Main entry point for Lua function to replace {{coord}}

Usage:
    {{ Invoke:Coordinates | coord }}
    {{ Invoke:Coordinates | coord | lat | long }}
    {{ Invoke:Coordinates | coord | lat | lat_flag | long | long_flag }}
    ...
    
    Refer to {{coord}} documentation page for many additional parameters and 
    configuration options.
    
Note: This function provides the visual display elements of {{coord}}.  In
order to load coordinates into the database, the {{#coordinates:}} parser 
function must also be called, this is done automatically in the Lua
version of {{coord}}.
]]

function wikidatacoords(dimension) --récupère les coordonnées sur Wikidata (2013-08/2013-09 intégration wikidata >> Utilisateur Zolo, Tpt & Xfigpowert)
        local item = mw.wikibase.getEntity()
        if item and item.claims and item.claims['p625'] then
            for _, statement in pairs( item.claims['p625'] ) do
                if statement.mainsnak.snaktype == 'value' then
                    return tostring( statement.mainsnak.datavalue.value[dimension])
                end
            end
        end     
end

function coordinates.latitude(frame)  -- retourne nil quand il n'y a pas de latitude (nécessaire pour certains modèles)
	if frame.args[1] and frame.args[1] ~= ''then
		return frame.args[1]
	elseif frame.args['wikidata'] == 'true' then
		return wikidatacoords('latitude')
	end
end

function coordinates.longitude(frame)
	if frame.args[1] and frame.args[1] ~= ''then
		return frame.args[1]
	elseif frame.args['wikidata'] == 'true' then
		return wikidatacoords('longitude')
	end
end

function coordinates.coord(frame)
    globalFrame = frame
    
    local text = ''
    
    local args = frame.args
    if args[1] == nil then
        local pFrame = frame:getParent();
        args = pFrame.args;
        for k,v in pairs( frame.args ) do
            args[k] = v;
        end
    end
    
    for i=1,10 do 
        if args[i] == nil then 
            args[i] = ""
        else
            args[i] = args[i]:match( '^%s*(.-)%s*$' );  --remove whitespace
        end        
    end
    args['format'] = args['format'] or '';
    
    if args[2] == '' and args['wikidata'] == 'true' then
        local arggeo=args[1]
		args[1] = wikidatacoords('latitude')
		args[2] = wikidatacoords('longitude')
    end
    local latdms=mw.text.split( args[1], '/' )
    local lngdms=mw.text.split( args[2], '/' )
    if #latdms > 1 or #lngdms >1 then 
        -- je copie
        local argsN=mw.clone(args)   
        local i = 1 -- point de départ
        local ia = 1 -- point de départ
        while (latdms[i] ~= nil) do
          args[ia]=mw.text.trim(latdms[i])
          i = i + 1
          ia = ia +1
        end
        local i = 1 -- point de départ
        while (lngdms[i] ~= nil) do
          args[ia]=mw.text.trim(lngdms[i])
          i = i + 1
          ia = ia +1
        end
        local i = 3 -- point de départ
        while (argsN[i] ~= nil) do
          args[ia]=argsN[i]
          i = i + 1
          ia = ia +1
        end
    end

    --définition de la planète
    local astre
    for _, l in ipairs(args) do
        for w in string.gmatch(l, "globe:(%a+)") do
            astre=w
            break
        end
    end

    --par défaut, on format pour un affichage en ligne
    local contents = formatTest(args)
    local Notes = args.notes or ""
    local Display = string.lower(args.display or "inline")
    if Display == '' then
        Display = 'inline';
    end
    local havedisplay = "";
    
    if string.find( Display, 'inline' ) ~= nil or Display == 'i' or 
            Display == 'it' or Display == 'ti' then
        text = text .. displayinline(contents, Notes)
        havedisplay = havedisplay .. "i";
    end
    if string.find( Display, 'title' ) ~= nil or Display == 't' or 
            Display == 'it' or Display == 'ti' then
        if args['formatitle'] ~= nil then
            args['format'] = args['formatitle'] or args['format']
            contents = formatTest(args)
        end   
        text = text .. displaytitle(contents, Notes, astre)
        args['geodata']="primary"
        text = text ..  globalFrame:preprocess(formatTest(args) )
        
        havedisplay = havedisplay .. "t";
    end
    
    if havedisplay == "" then
        --rien n'a été affiché!
        text = text .. displayinline(contents, Notes) .. errorPrinter( {{"display", "argument display incorrect"}} )
        
    end    
    
    return text
end

function coordinates.Coord(frame)
    return coordinates.coord(frame)
end


return coordinates