Aller au contenu

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

De Wreck
Modèle:Infobox>Orlodrim
Annulation des modifications 101266248 de FDo64 (d) il y a des erreurs partout
Modèle:Infobox>Orlodrim
Remplacement par la version de Zolo à partir de Module:Coordinates/Test
Ligne 1 : Ligne 1 :
--[[
local math_mod = require( "Module:Math" )
This module is intended to replace the functionality of {{Coord}} and related
local p = {}
templates.  It provides several methods, including


{{#Invoke:Coordinates | coord }} : General function formatting and displaying
local i18n = {
coordinate values.
N = ' N',
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',
}


{{#Invoke:Coordinates | dec2dms }} : Simple function for converting decimal
local globedata = {
degree values to DMS format.
--[[ notes:
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'}
}


{{#Invoke:Coordinates | dms2dec }} : Simple function for converting DMS format
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
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
]]--


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


coordinates = {};
function makeerror(args)
 
local errormessage = ''
--[[ Helper function, replacement for {{coord/display/title}} ]]
if args.message then
function displaytitle (s, notes ,globe)
errormessage = '<strong class="error">Coordonnées: ' .. args.message .. '</strong>'
    --local l = "[[Geographic coordinate system|Coordinates]]: " .. s
end
    local l = "" .. s
local errorcat = ''
    local extracat = ""
if mw.title.getCurrentTitle().namespace == 0 then  
   
errorcat = makecat(i18n.errorcat, args.sortkey)
    if mw.title.getCurrentTitle().nsText == "" then
end
        if globe~= nil and globe~= "earth" then
errorstring = errormessage .. errorcat -- reinitializes the string to avoid absurdly long messages
            if globe == "moon" then
return nil
                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


--[[ Helper function, Replacement for {{coord/display/inline}} ]]
function showerrors()
function displayinline (s, notes)
return errorstring
    return s .. notes   
end
end
 
-------------------------------------------
--[[ Helper function, used in detecting DMS formatting ]]
function makecat(cat, sortkey)
local dmsTest = function(first, second)
return '[[Category:' .. cat .. '|' .. (sortkey or '*') .. ']]'
    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


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


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


    local mode = coordinates.determineMode( lat, long );
-- convertit en km en fonction du globe
    coordinateSpec["dms-lat"]  = convert_dec2dms( lat, "N", "S", mode)  -- {{coord/dec2dms|{{{1}}}|N|S|{{coord/prec dec|{{{1}}}|{{{2}}}}}}}
if not globe or not globedata[globe] then
    coordinateSpec["dms-long"] = convert_dec2dms( long, "E", "O", mode)  -- {{coord/dec2dms|{{{2}}}|E|W|{{coord/prec dec|{{{1}}}|{{{2}}}}}}} 
return error('globe: ' .. globe .. 'is not supported')
    coordinateSpec["dmslong-lat"]  = convert_dec2dms( lat, "Nord", "Sud", mode)  -- {{coord/dec2dms|{{{1}}}|N|S|{{coord/prec dec|{{{1}}}|{{{2}}}}}}}
end
    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
radius = globedata[globe].radius
return radius * angle
end
end


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


--[[
parseDMS


Transforms degrees, minutes, seconds format latitude and longitude
------------------------
into the a structure to be used in displaying coordinates
--HTML builder for a geohack link
]]
local function buildHTML(decLat, decLong, dmsLat, dmsLong, globe, displayformat, displayinline, displaytitle, objectname, extraparams)
function parseDMS( lat_d, lat_m, lat_s, lat_f, long_d, long_m, long_s, long_f, format )
local htmlBuilder = require("Module:HtmlBuilder")
    local coordinateSpec = {}
     local root, text, url, noprint
     local errors = {}
extraparams = extraparams or ''
      
     -- geohack url and parameters
     lat_f = lat_f:upper();
     local decimalcoords = p.displaydec(decLat, decLong, displayformat)
     long_f = string.gsub(long_f:upper(),'W','O');
     local geohacklatitude, geohacklongitude


     local lat_flong = 'Nord';
     -- format latitude and longitude for the URL
     if lat_f == 'S' then
     if tonumber(decLat) < 0 then
        lat_flong = 'Sud';
    geohacklatitude = tostring(-tonumber(decLat)) .. '_S'
     end
     else
    local long_flong = 'Ouest';
    geohacklatitude = decLat .. '_N'
    if long_f == 'E' then
end
        long_flong = 'Est';
if tonumber(decLong) < 0 then
    end
geohacklongitude = tostring(-tonumber(decLong)) .. '_W'
   
    else
   
    geohacklongitude = decLong .. '_E'
    -- Check if specified backward
end
    if lat_f == 'E' or lat_f == 'O' or lat_f == 'W' then
-- prepares the 'paramss=' parameter
        local t_d, t_m, t_s, t_f;
local geohackparams = geohacklatitude .. '_' .. geohacklongitude .. '_' ..extraparams
        t_d = lat_d;
-- concatenate parameteres for geohack
        t_m = lat_m;
local url = i18n.geohackurl ..
        t_s = lat_s;
"&pagename=" .. mw.uri.encode(mw.title.getCurrentTitle().prefixedText, "WIKI") ..
        t_f = lat_f;
"&params=" .. geohackparams ..
        lat_d = long_d;
(objectname and ("&title=" .. mw.uri.encode(objectname)) or "")
        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
     root = htmlBuilder.create()
end
    root
        .tag("span")
            .addClass("plainlinks nourlexpansion")
            .wikitext("[" .. url)
            .tag("span")
                .addClass(string.sub(displayformat,1,3) == "dec" and "geo-nondefault" or "geo-default")
                .tag("span")
                    .addClass("geo-dms")
                    .attr("title", i18n.tooltip)
                    .tag("span")
                        .addClass("latitude")
                        .wikitext(p.displaydmsdimension(dmsLat, displayformat))
                        .done()
                    .wikitext(" ")
                    .tag("span")
                        .addClass("longitude")
                        .wikitext(p.displaydmsdimension(dmsLong, displayformat))
                        .done()
                    .done()
                .done()
            .tag("span")
                .addClass("geo-multi-punct")
                .wikitext("&#xfeff; / &#xfeff;")
                .done()
            .tag("span")
                .addClass(string.sub(displayformat,1,3) == 'dec' and "geo-default" or "geo-nondefault")
                .wikitext(objectname and "<span class=\"vcard\">" or "")
                .tag("span")
                    .addClass("geo-dec")
                    .attr("title", i18n.tooltip)
                    .wikitext(decimalcoords)
                    .done()
                .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")
specPrinter
    text = tostring(root)


Output formatter.  Takes the structure generated by either parseDec
     noprint = displayinline and "class=\"noprint\" " or ""
or parseDMS and formats it for inclusion on Wikipedia.
     htmlTitle = "<span style=\"font-size: small;\"><span " .. noprint .. "id=\"coordinates\">"  
]]
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
     return (displayinline and text or "") ..
    if long < 0 then
          (displaytitle and (htmlTitle .. text .. "</span></span>") or "")
        -- FIXME does not handle unicode minus
end
        --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">'
-- Fonctions de manipualation/coonversion des coordonnées
            .. coordinateSpec["dec-lat"] .. '; '
            .. coordinateSpec["dec-long"]
            .. '</span>'


--cf http://www.mediawiki.org/wiki/Extension:GeoData
function p._dec2dms(dec, coordtype, precision) -- type: latitude or longitude
    local geodata = ''
local dec = tonumber(dec)
    local r,s,t=string.match (coordinateSpec["param"],'(.*)_(E?W?)_(.*)')
local dms = {}
    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


-- precision
if precision and precision ~= '' and precision ~= 'd' and precision ~= 'dm' and precision ~= 'dms' then
return makeerror({sortkey = 'C'})
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


    if args["name"] == "" or args["name"] == nil then
function p.dec2dms(frame) -- legacy function somewhat cumbersome syntax
        inner = inner .. geodechtml
args = frame.args
                .. '<span style="display:none">&#xfeff; / ' .. geonumhtml .. '</span></span>'
local dec = args[1]  
    else
local precision = string.lower(args[4])
        inner = inner .. '<span class="vcard">' .. geodechtml
local displayformat, coordtype
                .. '<span style="display:none">&#xfeff; / ' .. geonumhtml .. '</span>'
                .. '<span style="display:none">&#xfeff; (<span class="fn org">'
if args[2] == 'N' or 'Nord' then
                .. args["name"] .. '</span>)</span></span></span>'
coordtype = 'latitude'
    end
else
coordtype = 'longitude'
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


    return '<span class="plainlinksneverexpand">' .. globalFrame:preprocess(
function p._dms2dec(dmsobject) -- transforme une table degré minute secondes en nombre décimal
        '[//tools.wmflabs.org/geohack/geohack.php?pagename={{FULLPAGENAMEE}}&language=' .. lang .. '&params=' ..
local direction, degrees, minutes, seconds = dmsobject.direction, dmsobject.degrees, dmsobject.minutes, dmsobject.seconds
        uriComponents .. ' ' .. inner .. ']') .. '</span>'
local factor = 0
local precision = 0
if not minutes then minutes = 0 end
if not seconds then seconds = 0 end
if direction == "N" or direction == "E" then
factor = 1
elseif direction == "W" or direction == "S" then
factor = -1
elseif not direction then
makeerror({message = 'no cardinal direction found in coordinates', sortkey = 'A'})
return nil
else
makeerror({message = 'invalid direction', sortkey = 'A'})
return nil
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
Formats any error messages generated for display
local args = frame.args
]]
if tonumber(args[1]) then
function errorPrinter(errors)
return args[1] -- coordonnées déjà en décimal
    local result = ""
elseif not args[2] then
    for i,v in ipairs(errors) do
return p._dms2dec(parsedmsstring(args[1])) -- coordonnées sous la fore 23/22/N
        local errorHTML = '<strong class="error">Coordonnées: ' .. v[2] .. '</strong>'
else
        result = result .. errorHTML .. "<br />"
return p._dms2dec({direction = args[1], degrees = args[2], minutes = args[3], seconds = args[4]})
    end
end
    return result
end
end


--[[
function parsedmsstring(str) -- prend une séquence et donne des noms aux paramètres
Determine the required CSS class to display coordinates
-- output table: {latitude=, longitude = , direction =  }
if not tonumber(str) and not string.find(str, '/') then
makeerror({message ='invalid coordinate format', sortkey= 'A'})
return nil
end
args = mw.text.split(str, '/', true)
if #args > 4 then
makeerror({message = "too many parameters for coordinates", sortkey= 'A' })
end
local direction = args[#args]
table.remove(args)
local degrees, minutes, seconds = args[1], args[2], args[3]
local dimensionobject = builddmsdimension(degrees, minutes, seconds, direction)
if validdms(dimensionobject) then
return dimensionobject
else
return nil
end
end


Usually geo-nondefault is hidden by CSS, unless a user has overridden this for himself
function builddmsdimension(degrees, minutes, seconds, direction)
default is the mode as specificied by the user when calling the {{coord}} template
-- no error checking, done in function validdms
mode is the display mode (dec or dms) that we will need to determine the css class for
local dimensionobject = {}
]]
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
-- direction and dimension (= latitude or longitude)
and then make the necessary processing.
dimensionobject.direction = direction
]]
if direction == 'N' or direction == 'S' then
function formatTest(args)
dimensionobject.dimension = 'latitude'
    local result, errors;
else
    local primary = false;
dimensionobject.dimension = 'longitude'
   
end
    if args[1] == "" then
        -- no lat logic
-- degrees, minutes, seconds
        return errorPrinter( {{"formatTest", "Missing latitude"}} )
dimensionobject.degrees = tonumber(degrees)
    elseif args[4] == "" and args[5] == "" and args[6] == "" then
dimensionobject.minutes = tonumber(minutes)
        -- dec logic
dimensionobject.seconds = tonumber(seconds)
        result, errors = parseDec( args[1], args[2], args['format'] )
if degrees and not dimensionobject.degrees then dimensionobject.degrees = 'error' end
        if result == nil then
if minutes and not dimensionobject.minutes then dimensionobject.minutes = 'error' end
            return errorPrinter( errors );
if seconds and not dimensionobject.seconds then dimensionobject.seconds = 'error' end
        end             
return dimensionobject
        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 p.displaydmsdimension(valuetable, format) -- formate en latitude ou une longitude dms
Helper function, convert decimal latitude or longitude to
local str = ''
degrees, minutes, and seconds format based on the specified precision. 
local direction = valuetable.direction
]]
local degrees, minutes, seconds = '', '', ''
function convert_dec2dms(coordinate, firstPostfix, secondPostfix, precision)
local dimension
    local coord = tonumber(coordinate) or 0
    local postfix
    if coord >= 0 then
        postfix = firstPostfix
    else
        postfix = secondPostfix
    end


    precision = precision:lower();
if format == 'dms long' then
    if precision == "dms" then
direction = i18n[direction .. 'long']
        return convert_dec2dms_dms( math.abs( coord ) ) .. postfix;
else
    elseif precision == "dm" then
direction = i18n[direction]
        return convert_dec2dms_dm( math.abs( coord ) ) .. postfix;
end
    elseif precision == "d" then
degrees = valuetable.degrees .. i18n.degrees
        return convert_dec2dms_d( math.abs( coord ) ) .. postfix;
if valuetable.minutes then
    end
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


--[[ Helper function, convert decimal to degrees ]]
function validdms(coordtable)
function convert_dec2dms_d(coordinate)
local direction = coordtable.direction
    local d = math_mod._round( coordinate, 0 ) .. "°&nbsp;"
local degrees = coordtable.degrees or 0
    return d .. ""
local minutes = coordtable.minutes or 0
local seconds = coordtable.seconds or 0
local dimension = coordtable.dimension
if type(degrees) ~= 'number' or type(minutes) ~= 'number' or type(seconds) ~= 'number' then
makeerror({message = 'coordinates should be numeric', sortkey = 'A'})
return false
end
if dimension == 'latitude' and direction ~= 'N' and direction ~= 'S' then
makeerror({message = 'could not find latitude direction (should be N or S)', sortkey = 'A'})
return false
end
if dimension == 'longitude' and direction ~= 'W' and direction ~= 'E' then
makeerror({message = 'could not find longitude direction (should be W or E) ', sortkey = 'A'})
return false
end
if dimension == 'latitude' and degrees > 90 then
makeerror({'latitude > 90', sortkey = 'A'})
return false
end
if dimension == 'longitude' and degrees > 180 then
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


--[[ Helper function, convert decimal to degrees and minutes ]]
function validlatitude(value) -- decimal latitude
function convert_dec2dms_dm(coordinate)  
if type(value) ~= 'number' or math.abs(value) > 90 then
    coordinate = math_mod._round( coordinate * 60, 0 );
makeerror({message = 'latitude should be number < 90, is ' .. (value or 'nil')})
    local m = coordinate % 60;
return false
    coordinate = math.floor( (coordinate - m) / 60 );
end
    local d = coordinate % 360 .."°&nbsp;"
return true
   
    return d .. string.format( "%02d′&nbsp;", m )
end
end


--[[ Helper function, convert decimal to degrees, minutes, and seconds ]]
function validlongitude(value) -- decimal longitude
function convert_dec2dms_dms(coordinate)
if type(value) ~= 'number' or math.abs(value) > 180 then
    coordinate = math_mod._round( coordinate * 60 * 60, 0 );
makeerror({message = 'longitude should be number < 180, is ' .. (value or 'nil')})
    local s = coordinate % 60
return false
    coordinate = math.floor( (coordinate - s) / 60 );
end
    local m = coordinate % 60
return true
    coordinate = math.floor( (coordinate - m) / 60 );
end
    local d = coordinate % 360 .."°&nbsp;"


    return d .. string.format( "%02d′&nbsp;", m ) .. string.format( "%02d″&nbsp;", s )
function p.displaydec(latitude, longitude, format)
if format == 'dec west' then
local latsymbol = i18n.N
longitude = - longitude
if latitude < 0 then latsymbol = i18n.S end
if longitude < 0 then
long = 360 + longitude
end
return latitude .. i18n.degrees .. latsymbol .. ', ' .. longitude ..  i18n.degrees .. i18n.W
elseif format == 'dec west' then
local latsymbol = i18n.N
if latitude < 0 then latsymbol = i18n.S end
if longitude < 0 then
longitude = 360 + longitude
end
return latitude .. i18n.degrees .. latsymbol .. ', ' .. longitude  ..  i18n.degrees .. i18n.E
else
return latitude .. ', ' .. longitude
end
end
end


--[[
function wikidatacoords(query)
Convert DMS format into a N or E decimal coordinate
query = query or {property = 'p625'}
]]
local wd = require('Module:Wikidata')
function convert_dms2dec(direction_str, degrees_str, minutes_str, seconds_str)
local claim = wd.getClaims(query)
    local degrees = tonumber(degrees_str) or 0
if claim and claim[1] then -- redundant but more robust in case of a change in the code of Module:Wikidata
    local minutes = tonumber(minutes_str) or 0
local coords = wd.formatSnak(claim[1].mainsnak) -- todo: check for special values
    local seconds = tonumber(seconds_str) or 0
return coords.latitude, coords.longitude, coords.globe
    local direction = direction_str:match( '^%s*(.-)%s*$' );  --remove whitespace
end
   
return nil
    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
end


--[[
--- fonctions principales
Checks input values to for out of range errors.
function p._coord(args)
]]
local latitude, longitude = tonumber(args.latitude), tonumber(args.longitude) -- must be in decimal format
function validate( lat_d, lat_m, lat_s, long_d, long_m, long_s, source, strong )
if latitude and longitude and (not validlatitude(latitude) or not validlongitude(longitude)) then
    local errors = {};
return showerrors()
    lat_d = tonumber( lat_d ) or 0;
end
    lat_m = tonumber( lat_m ) or 0;
local displayformat, inputformat = args.format, args.inputformat -- one of: 'dms', 'dms long', 'dec', 'dec east' and 'dec west'
    lat_s = tonumber( lat_s ) or 0;
local displayplace = string.lower(args.display or 'inline') -- on of 'inline', 'title' or 'inline,title'
    long_d = tonumber( long_d ) or 0;
local globe = string.lower(args.globe or '') -- planet see the globedata table for accepted values
    long_m = tonumber( long_m ) or 0;
local objectname = args.name -- name of the title displayed in geohack
    long_s = tonumber( long_s ) or 0;
local notes = (' ' and args.notes) or '' -- notes à afficher après les coordonnées
 
local wikidata = args.wikidata -- string set to true when
    if strong then
local dmslatitude, dmslongitude -- type: table when created
        if lat_d < 0 then
local extraparams = string.lower(args.extraparams or '') -- chaîne destinée à geohack dernier paramètre avec argument numérique dans {{Coord}}
            table.insert(errors, {source, "latitude degrees < 0 with hemisphere flag"})
local wikidataquery = args.wikidataquery
        end
local trackingstring = '' -- tracking cats except error cats (already in errorstring)
        if long_d < 0 then
            table.insert(errors, {source, "longitude degrees < 0 with hemisphere flag"})
        end
-- parsage des donnés en format non-décimal
        --[[
if (not latitude and args.latitude and args.latitude ~= '') then -- latitude was not a number
        #coordinates is inconsistent about whether this is an error.  If globe: is
dmslatitude = parsedmsstring(args.latitude)
        specified, it won't error on this condition, but otherwise it will.
if not dmslatitude then return showerrors() end
       
latitude = p._dms2dec(dmslatitude)
        For not simply disable this check.
end
       
if (not longitude and args.longitude and args.longitude ~= '') then -- latitude was not a number
        if long_d > 180 then
dmslongitude = parsedmsstring(args.longitude)
            table.insert(errors, {source, "longitude degrees > 180 with hemisphere flag"})
if not dmslongitude then return showerrors() end
        end
longitude = p._dms2dec(dmslongitude)
        ]]
end
    end  
       
    if lat_d > 90 then
-- récuparation des coordonnées Wikidata
        table.insert(errors, {source, "latitude degrees > 90"})
local wikidatalatitude, wikidatalongitude, wikidataglobe
    end
if wikidata == 'true' then
    if lat_d < -90 then
wikidatalatitude, wikidatalongitude, wikidataglobe = wikidatacoords(wikidataquery)
        table.insert(errors, {source, "latitude degrees < -90"})
end
    end
if wikidatalatitude and latitude then
    if lat_m >= 60 then
local maxdistance = tonumber(args.maxdistance) or wikidatathreshold
        table.insert(errors, {source, "latitude minutes >= 60"})
if p._distance({latitude = latitude, longitude= longitude}, {latitude = wikidatalatitude, longitude= wikidatalongitude}, wikidataglobe) <  maxdistance then
    end
trackingstring = trackingstring .. makecat(i18n.sameaswikidata)
    if lat_m < 0 then
else
        table.insert(errors, {source, "latitude minutes < 0"})
trackingstring = trackingstring .. makecat(i18n.notaswikidata)
    end
end
    if lat_s >= 60 then
end
        table.insert(errors, {source, "latitude seconds >= 60"})
if wikidatalatitude and not latitude then
    end
latitude, longitude, globe = wikidatalatitude, wikidatalongitude, wikidataglobe
    if lat_s < 0 then
trackingstring = trackingstring .. makecat(i18n.throughwikidata)
        table.insert(errors, {source, "latitude seconds < 0"})
end
    end
-- exit if stil no latitude or not longitude
    if long_d >= 360 then
if not latitude and not longitude then
        table.insert(errors, {source, "longitude degrees >= 360"})
return nil -- ne rien ajouter ici pour que l'appel à cette fonction retourne bien nil en l'absence de données
    end
end
     if long_d <= -360 then
if not latitude or not longitude then  
        table.insert(errors, {source, "longitude degrees <= -360"})
makeerror({message = 'latitude or longitude missing', sortkey = 'A'})
     end
return showerrors()
    if long_m >= 60 then
end
        table.insert(errors, {source, "longitude minutes >= 60"})
-- 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
     end
     if long_m < 0 then
     if displaytitle and mw.title.getCurrentTitle().namespace == 0 then
        table.insert(errors, {source, "longitude minutes < 0"})
    trackingstring = trackingstring .. makecat(globedata[globe].trackingcat)
    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
     end
      
      
    return errors;
-- standardize format for astronomical objects so that it can be used by geohack (back converted afterwards, pretty fast)
end
if inputformat == 'dec east' then
if longitude > 180 then
longitude = longitude - 360
end
longitude = - longitude
end
if inputformat == 'dec west' then
if longitude > 180 then
longitude = longitude - 360
end
end


--[[
-- finish up
dec2dms
if not dmslatitude then
 
dmslatitude, dmslongitude = p._dec2dms(latitude, 'latitude'), p._dec2dms(longitude, 'longitude')
Wrapper to allow templates to call dec2dms directly.
end
 
extraparams = extraparams .. '_globe:' .. globe -- pas de problème si le globe est en double
Usage:
    {{ Invoke:Coordinates | dec2dms | decimal_coordinate | positive_suffix |
-- final output
        negative_suffix | precision }}
local mainstring = ''
   
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)
mainstring = buildHTML(latitude, longitude, dmslatitude, dmslongitude, globe, displayformat, displayinline, displaytitle, objectname,extraparams )
return mainstring .. notes .. trackingstring .. showerrors()
end
end


--[[
function p.coord(frame) -- parrses the strange parameters of Template:Coord before sending them to p.coord
Helper function to determine whether to use D, DM, or DMS
local args = frame.args
format depending on the precision of the decimal input.
local numericargs = {}
]]
for i, j in ipairs(args) do
function coordinates.determineMode( value1, value2 )
args[i] = mw.text.trim(j)
    local precision = math.max( math_mod._precision( value1 ), math_mod._precision( value2 ) );
if type(i) == 'number' and args[i] ~= '' then
    if precision <= 0 then
table.insert(numericargs, args[i])
        return 'd'
end
    elseif precision <= 2 then
end
        return 'dm';
    else
        return 'dms';
    end
end      


--[[
dms2dec


Wrapper to allow templates to call dms2dec directly.
if #numericargs == 1 then
makeerror({message = 'invalid coordinates format', sortkey = 'A'})
return showerrors()
elseif #numericargs %2 == 1 then -- if the number of args is odd, the last one provides formatting parameters
args.extraparams = numericargs[#numericargs]
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


Usage:
if string.find(args.latitude or '', 'E') or string.find(args.latitude or '', 'W') then
    {{ Invoke:Coordinates | dms2dec | direction_flag | degrees |
args.latitude, args.longitude = args.longitude, args.latitude
        minutes | seconds }}
end
   
if args.formatitle then -- legacy parameter
Converts DMS values specified as degrees, minutes, seconds too decimal format.
args.display = 'inline'
direction_flag is one of N, S, E, W, and determines whether the output is
local inline = p._coord(args)
positive (i.e. N and E) or negative (i.e. S and W).
args.display = 'title'
]]
args.format = args.formatitle
function coordinates.dms2dec(frame)
local title = p._coord(args)
    globalFrame = frame
return (inline or '') .. (title or '')
   
else
    local direction = frame.args[1]
return p._coord(args)
    local degrees = frame.args[2]
end
    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
end


--[[
function p.Coord(frame)
coord
return p.coord(frame)
 
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
end


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


function coordinates.coord(frame)
return p
    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

Version du 18 février 2014 à 22:05

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

local math_mod = require( "Module:Math" )
local p = {}

local i18n = {
	N = ' N',
	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 = 	{
	--[[ notes:
		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

----------------------------------------
--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 = ''

function makeerror(args)
	local errormessage = ''
	if args.message then 
		errormessage = '<strong class="error">Coordonnées: ' .. args.message .. '</strong>' 
	end
	local errorcat = ''
	if mw.title.getCurrentTitle().namespace == 0 then 
		errorcat = makecat(i18n.errorcat, args.sortkey)
	end
	errorstring = errormessage .. errorcat -- reinitializes the string to avoid absurdly long messages
	return nil
end

function showerrors()
	return errorstring
end
-------------------------------------------
function makecat(cat, sortkey)
	return '[[Category:' .. cat .. '|' .. (sortkey or '*') .. ']]'
end

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

	globe = string.lower(globe or 'earth')
	
	-- check arguments and converts degreees to radians
	local latA, latB, longA, longB = a.latitude, b.latitude, a.longitude, b.longitude
	if not latA or not latB or not longA or not longB then return
		error('coordinates missing, can\'t compute distance')
	end
	if type(latA) ~= 'number' or type(latB) ~= 'number' or type(longA) ~= 'number' or type(longB) ~= 'number' then
		error('coordinates are not numeric, can\'t compute distance')
	end
	
	-- distance angulaire en radians
	local convratio = math.pi / 180 -- convertit en radians
	latA, latB, longA, longB = convratio * latA, convratio * latB, convratio * longA, convratio * longB
	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
	if not globe or not globedata[globe] then
		return error('globe: ' .. globe .. 'is not supported')
	end

	radius = globedata[globe].radius
	
	return radius * angle
end

function p.distance(frame)
	local args = frame.args
	return p._distance(
		{latitude = tonumber(args.latitude1), longitude = tonumber(args.longitude1)}, 
		{latitude = tonumber(args.latitude2), longitude = tonumber(args.longitude2)},
		args.globe)
end


------------------------
--HTML builder for a geohack link
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
    	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()
    root
        .tag("span")
            .addClass("plainlinks nourlexpansion")
            .wikitext("[" .. url)
            .tag("span")
                .addClass(string.sub(displayformat,1,3) == "dec" and "geo-nondefault" or "geo-default") 
                .tag("span")
                    .addClass("geo-dms")
                    .attr("title", i18n.tooltip)
                    .tag("span")
                        .addClass("latitude")
                        .wikitext(p.displaydmsdimension(dmsLat, displayformat))
                        .done()
                    .wikitext(" ")
                    .tag("span")
                        .addClass("longitude")
                        .wikitext(p.displaydmsdimension(dmsLong, displayformat))
                        .done()
                    .done()
                 .done()
            .tag("span")
                .addClass("geo-multi-punct")
                .wikitext("&#xfeff; / &#xfeff;")
                .done()
            .tag("span")
                .addClass(string.sub(displayformat,1,3) == 'dec' and "geo-default" or "geo-nondefault")
	                .wikitext(objectname and "<span class=\"vcard\">" or "")
                .tag("span")
                    .addClass("geo-dec")
                    .attr("title", i18n.tooltip)
                    .wikitext(decimalcoords)
                    .done()
                .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")
    text = tostring(root)

    noprint = displayinline and "class=\"noprint\" " or ""
    htmlTitle = "<span style=\"font-size: small;\"><span " .. noprint .. "id=\"coordinates\">" 

    return (displayinline and text or "") ..
           (displaytitle and (htmlTitle .. text .. "</span></span>") or "")
end

-- Fonctions de manipualation/coonversion des coordonnées

function p._dec2dms(dec, coordtype, precision) -- type: latitude or longitude
	local dec = tonumber(dec)
	local dms = {}

	-- precision
	if precision and precision ~= '' and precision ~= 'd' and precision ~= 'dm' and precision ~= 'dms' then
		return makeerror({sortkey = 'C'})
	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

function p.dec2dms(frame) -- legacy function somewhat cumbersome syntax
	args = frame.args
	local dec = args[1] 
	local precision = string.lower(args[4])
	local displayformat, coordtype
	
	if args[2] == 'N' or 'Nord' then
		coordtype = 'latitude'
	else 
		coordtype = 'longitude'
	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

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
	local factor = 0
	local precision = 0
	if not minutes then minutes = 0 end
	if not seconds then seconds = 0 end
	
	if direction == "N" or direction == "E" then
		factor = 1
	elseif direction == "W" or direction == "S" then
		factor = -1
	elseif not direction then 
		makeerror({message = 'no cardinal direction found in coordinates', sortkey = 'A'})
		return nil
	else
		makeerror({message = 'invalid direction', sortkey = 'A'})
		return nil
	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

function p.dms2dec(frame) -- legacy function, somewhat bizarre syntax
	local args = frame.args
	if tonumber(args[1]) then 
		return args[1] -- coordonnées déjà en décimal
	elseif not args[2] then
		return p._dms2dec(parsedmsstring(args[1])) -- coordonnées sous la fore 23/22/N
	else 
		return p._dms2dec({direction = args[1], degrees = args[2], minutes = args[3], seconds = args[4]})
	end
end

function parsedmsstring(str) -- prend une séquence et donne des noms aux paramètres 
	-- output table: {latitude=, longitude = , direction =  }
	if not tonumber(str) and not string.find(str, '/') then
		makeerror({message ='invalid coordinate format', sortkey= 'A'})
		return nil
	end
	args = mw.text.split(str, '/', true)
	if #args > 4 then
		makeerror({message = "too many parameters for coordinates", sortkey= 'A' })
	end	
	local direction = args[#args]
	table.remove(args)
	local degrees, minutes, seconds = args[1], args[2], args[3]
	local dimensionobject = builddmsdimension(degrees, minutes, seconds, direction)
	if validdms(dimensionobject) then
		return dimensionobject
	else
		return nil
	end
	
end

function builddmsdimension(degrees, minutes, seconds, direction)
	-- no error checking, done in function validdms
	local dimensionobject = {}

	
	-- direction and dimension (= latitude or longitude)
	dimensionobject.direction = direction
	if direction == 'N' or direction == 'S' then
		dimensionobject.dimension = 'latitude'
	else
		dimensionobject.dimension = 'longitude'
	end
	
	-- 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

function p.displaydmsdimension(valuetable, format) -- formate en latitude ou une longitude dms
	local str = ''
	local direction = valuetable.direction
	local degrees, minutes, seconds = '', '', ''
	local dimension

	if format == 'dms long' then
		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

function validdms(coordtable)
	local direction = coordtable.direction
	local degrees = coordtable.degrees or 0
	local minutes = coordtable.minutes or 0
	local seconds = coordtable.seconds or 0
	local dimension = coordtable.dimension
	
	if type(degrees) ~= 'number' or type(minutes) ~= 'number' or type(seconds) ~= 'number' then
		makeerror({message = 'coordinates should be numeric', sortkey = 'A'})
		return false
	end
	
	if dimension == 'latitude' and direction ~= 'N' and direction ~= 'S' then
		makeerror({message = 'could not find latitude direction (should be N or S)', sortkey = 'A'})
		return false
	end
	if dimension == 'longitude' and direction ~= 'W' and direction ~= 'E' then
		makeerror({message = 'could not find longitude direction (should be W or E) ', sortkey = 'A'})
		return false
	end
	
	if dimension == 'latitude' and degrees > 90 then
		makeerror({'latitude > 90', sortkey = 'A'})
		return false
	end
	
	if dimension == 'longitude' and degrees > 180 then
		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

function validlatitude(value) -- decimal latitude
	if type(value) ~= 'number' or math.abs(value) > 90 then
		makeerror({message = 'latitude should be number < 90, is ' .. (value or 'nil')})
		return false
	end
	return true
end

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

function p.displaydec(latitude, longitude, format)
	if format == 'dec west' then
		local latsymbol = i18n.N
		longitude = - longitude
		if latitude < 0 then latsymbol = i18n.S end
		if longitude < 0 then 
			long = 360 + longitude
		end
	return latitude .. i18n.degrees .. latsymbol .. ', ' .. longitude ..  i18n.degrees .. i18n.W
		
	elseif format == 'dec west' then
		local latsymbol = i18n.N
		if latitude < 0 then latsymbol = i18n.S end
		if longitude < 0 then 
			longitude = 360 + longitude
		end
		return latitude .. i18n.degrees .. latsymbol .. ', ' .. longitude  ..  i18n.degrees .. i18n.E
		
	else 
		return latitude .. ', ' .. longitude 
	end
end

function wikidatacoords(query)
	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

--- fonctions principales
function p._coord(args)
	local latitude, longitude = tonumber(args.latitude), tonumber(args.longitude) -- must be in decimal format
	if latitude and longitude and (not validlatitude(latitude) or not validlongitude(longitude)) then
		return showerrors()
	end
	local displayformat, inputformat = args.format, args.inputformat -- one of: 'dms', 'dms long', 'dec', 'dec east' and 'dec west'
	local displayplace = string.lower(args.display or 'inline') -- on of 'inline', 'title' or 'inline,title' 
	local globe = string.lower(args.globe or '') -- planet see the globedata table for accepted values
	local objectname = args.name -- name of the title displayed in geohack
	local notes = (' ' and args.notes) or '' -- notes à afficher après les coordonnées
	local wikidata = args.wikidata -- string set to true when
	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
    
	-- standardize format for astronomical objects so that it can be used by geohack (back converted afterwards, pretty fast)
	if inputformat == 'dec east' then
		if longitude > 180 then
			longitude = longitude - 360
		end
		longitude = - longitude
	end
	if inputformat == 'dec west' then
		if longitude > 180 then
			longitude = longitude - 360
		end
	end

	-- finish up
	if not dmslatitude then
			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 )
	return mainstring .. notes .. trackingstring .. showerrors()
end

function p.coord(frame) -- parrses the strange parameters of Template:Coord before sending them to p.coord
	local args = frame.args
	local numericargs = {}
	for i, j in ipairs(args) do
		args[i] = mw.text.trim(j)
		if type(i) == 'number' and args[i] ~= '' then
			table.insert(numericargs, args[i])
		end
	end


	if #numericargs == 1 then
		makeerror({message = 'invalid coordinates format', sortkey = 'A'})
		return showerrors()
	elseif #numericargs %2 == 1 then -- if the number of args is odd, the last one provides formatting parameters
		args.extraparams = numericargs[#numericargs]
		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

	if string.find(args.latitude or '', 'E') or string.find(args.latitude or '', 'W') then
		args.latitude, args.longitude = args.longitude, args.latitude
	end
	if args.formatitle then -- legacy parameter
		args.display = 'inline'
		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

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

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

return p