Aller au contenu

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

De Wreck
Modèle:Infobox>FDo64
comme demandé par Zolo
Modèle:Infobox>FDo64
Annulation des modifications 101233171 de FDo64 (d) Annulation demandée par Zolo
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
defaultdisplay is currently disabled, activate it ?
]]--
earth = {radius = 6371, defaultdisplay = 'dms', trackingcat = 'Article géolocalisé sur Terre'},
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'},
moon =  {radius = 1736, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé sur la Lune'},
neptune =  {radius = 24553, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
saturn =  {radius = 58232, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
sun =  {radius = 696342, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
titan =  {radius = 2575.5, defaultdisplay = 'dec west', trackingcat = 'Article géolocalisé extraterrestre'},
triton = {radius = 1353, defaultdisplay = 'dec west', 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'},
}


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 = 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';
--HTML builder for a geohack link
    if lat_f == 'S' then
local function buildHTML(decLat, decLong, dmsLat, dmsLong, globe, displayformat, displayinline, displaytitle, objectname, extraparams)
        lat_flong = 'Sud';
local htmlBuilder = require("Module:HtmlBuilder")
    end
     local root, text, url, noprint
    local long_flong = 'Ouest';
extraparams = extraparams or ''
    if long_f == 'E' then
     -- geohack url e parametri
        long_flong = 'Est';
     local decimalcoords = p.displaydec(decLat, decLong, displayformat)
    end
     local geohacklatitude, geohacklongitude
   
   
    -- 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 


     -- format latitude and longitude for the URL
     return coordinateSpec, errors
     if tonumber(decLat) < 0 then
end
    geohacklatitude = tostring(-tonumber(decLat)) .. '_S'
 
     else
--[[
    geohacklatitude = decLat .. '_N'
specPrinter
end
 
if tonumber(decLong) < 0 then
Output formatter.  Takes the structure generated by either parseDec
geohacklongitude = tostring(-tonumber(decLong)) .. '_W'
or parseDMS and formats it for inclusion on Wikipedia.
    else
]]
    geohacklongitude = decLong .. '_E'
function specPrinter(args, coordinateSpec)
end
    local uriComponents = coordinateSpec["param"]
-- prepares the 'paramss=' parameter
     if uriComponents == "" then
local geohackparams = geohacklatitude .. '_' .. geohacklongitude .. '_' ..extraparams
        -- RETURN error, should never be empty or nil
-- concatenate parameteres for geohack
        return "ERROR param was empty"
local url = i18n.geohackurl ..  
    end
"&pagename=" .. mw.uri.encode(mw.title.getCurrentTitle().prefixedText, "WIKI") ..
       
"&params=" .. geohackparams ..
     if args["name"] ~= "" and args["name"] ~= nil then
(objectname and ("&title=" .. objectname) or "")
        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>'


     root = htmlBuilder.create()
--cf http://www.mediawiki.org/wiki/Extension:GeoData
     root
     local geodata = ''
        .tag("span")
     local r,s,t=string.match (coordinateSpec["param"],'(.*)_(E?W?)_(.*)')
            .addClass("plainlinks nourlexpansion")
    local globe,globend=string.match (coordinateSpec["param"],'_globe:(.*)(_*)')
            .wikitext("[" .. url)
    --Désactivé pour les astres à cause de problèmes de longitudes planétocentriques/planétographiques
            .tag("span")
    if globe == nil or globe == 'earth' then
                .addClass(string.sub(displayformat,1,3) == "dec" and "geo-nondefault" or "geo-default")
    geodata = '{{#coordinates:' .. coordinateSpec["dec-lat"] .. '|' .. coordinateSpec["dec-long"] .. '|primary|' .. t .. '}}'
                .tag("span")
    end
                    .addClass("geo-dms")
    if args['geodata'] ~= nil then
                    .attr("title", i18n.tooltip)
        return geodata;
                    .tag("span")
    end
                        .addClass("latitude")
   
                        .wikitext(p.displaydmsdimension(dmsLat, displayformat))
    local inner;
                        .done()
    if coordinateSpec["default"] == "dms" then
                    .wikitext(" ")
        inner = '<span class="' .. displayDefault(coordinateSpec["default"], "dms" ) .. '">' .. geodmshtml .. '</span>'
                    .tag("span")
                    .. '<span class="geo-multi-punct">&#xfeff; / &#xfeff;</span>'
                        .addClass("longitude")
                    .. '<span class="' .. displayDefault(coordinateSpec["default"], "dec" ) .. '">';
                        .wikitext(p.displaydmsdimension(dmsLong, displayformat))
    else
                        .done()
        inner = '<span class="' .. displayDefault(coordinateSpec["default"], "dms long" ) .. '">' .. geodmslonghtml .. '</span>'
                    .done()
                    .. '<span class="geo-multi-punct">&#xfeff; / &#xfeff;</span>'
                .done()
                    .. '<span class="' .. displayDefault(coordinateSpec["default"], "dec" ) .. '">';       
            .tag("span")
    end
                .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 ""
     if args["name"] == "" or args["name"] == nil then
    htmlTitle = "<span style=\"font-size: small;\"><span " .. noprint .. "id=\"coordinates\">"  
        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 (displayinline and text or "") ..
     return '<span class="plainlinksneverexpand">' .. globalFrame:preprocess(
          (displaytitle and (htmlTitle .. text .. "</span></span>") or "")
        '[//tools.wmflabs.org/geohack/geohack.php?pagename={{FULLPAGENAMEE}}&language=' .. lang .. '&params=' ..
        uriComponents .. ' ' .. inner .. ']') .. '</span>'
end
end


-- Fonctions de manipualation/coonversion des coordonnées
--[[
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


function p._dec2dms(dec, coordtype, precision) -- type: latitude or longitude
--[[
local dec = tonumber(dec)
Determine the required CSS class to display coordinates
local dms = {}


-- precision
Usually geo-nondefault is hidden by CSS, unless a user has overridden this for himself
if precision and precision ~= '' and precision ~= 'd' and precision ~= 'dm' and precision ~= 'dms' then
default is the mode as specificied by the user when calling the {{coord}} template
return makeerror({sortkey = 'C'})
mode is the display mode (dec or dms) that we will need to determine the css class for
end
]]
if not precision then
function displayDefault(default, mode)
precision = math_mod._precision(dec)
    if default == "" then
if precision <= 0 then
        default = "dec"
precision = 'd'
    end
elseif precision <= 2 then
   
precision = 'dm';
    if default:sub(1,4) == mode:sub(1,4) then
else
        return "geo-default"
precision = 'dms';
    else
end
        return "geo-nondefault"
end  -- et fractions de secondes ?
    end
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
Check the input arguments for coord to determine the kind of data being provided
local dec = args[1]  
and then make the necessary processing.
local precision = string.lower(args[4])
]]
local displayformat, coordtype
function formatTest(args)
    local result, errors;
if args[2] == 'N' or 'Nord' then
    local primary = false;
coordtype = 'latitude'
   
else
    if args[1] == "" then
coordtype = 'longitude'
        -- no lat logic
end
        return errorPrinter( {{"formatTest", "Missing latitude"}} )
if args[2] == 'Nord' or args[2] == 'Est' or args[2] == 'Ouest' then
    elseif args[4] == "" and args[5] == "" and args[6] == "" then
displayformat = 'dms long'
        -- dec logic
end
        result, errors = parseDec( args[1], args[2], args['format'] )
local coordobject = p._dec2dms(dec, coordtype, precision)
        if result == nil then
return p.displaydmsdimension(coordobject, displayformat) .. showerrors()
            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 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
Helper function, convert decimal latitude or longitude to
local factor = 0
degrees, minutes, and seconds format based on the specified precision.
local precision = 0
]]
if not minutes then minutes = 0 end
function convert_dec2dms(coordinate, firstPostfix, secondPostfix, precision)
if not seconds then seconds = 0 end
    local coord = tonumber(coordinate) or 0
    local postfix
if direction == "N" or direction == "E" then
    if coord >= 0 then
factor = 1
        postfix = firstPostfix
elseif direction == "W" or direction == "S" then
    else
factor = -1
        postfix = secondPostfix
elseif not direction then
    end
makeerror({message = 'no cardinal direction found in coordinates', sortkey = 'A'})
 
return nil
    precision = precision:lower();
else
    if precision == "dms" then
makeerror({message = 'invalid direction', sortkey = 'A'})
        return convert_dec2dms_dms( math.abs( coord ) ) .. postfix;
return nil
    elseif precision == "dm" then
end
        return convert_dec2dms_dm( math.abs( coord ) ) .. postfix;
    elseif precision == "d" then
if dmsobject.seconds then -- vérifie la précision des données initiales
        return convert_dec2dms_d( math.abs( coord ) ) .. postfix;
precision = 5 + math.max( math_mod._precision(tostring(seconds), 0 ) ) -- passage par des strings assez tarabiscoté ?
    end
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
--[[ Helper function, convert decimal to degrees ]]
local args = frame.args
function convert_dec2dms_d(coordinate)
if tonumber(args[1]) then
    local d = math_mod._round( coordinate, 0 ) .. "°&nbsp;"
return args[1] -- coordonnées déjà en décimal
    return d .. ""
elseif not args[2] then
return p._dms2dms(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
end


function parsedmsstring(str) -- prend une séquence et donne des noms aux paramètres
--[[ Helper function, convert decimal to degrees and minutes ]]
-- output table: {latitude=, longitude = , direction =  }
function convert_dec2dms_dm(coordinate)  
args = mw.text.split(str, '/', true)
    coordinate = math_mod._round( coordinate * 60, 0 );
if #args > 4 then
    local m = coordinate % 60;
makeerror({message = "too many parameters for coordinates", sortkey= 'A' })
    coordinate = math.floor( (coordinate - m) / 60 );
end
    local d = coordinate % 360 .."°&nbsp;"
local direction = args[#args]
   
table.remove(args)
    return d .. string.format( "%02d′&nbsp;", m )
local degrees, minutes, seconds = args[1], args[2], args[3]
return builddmsdimension(degrees, minutes, seconds, direction)
end
end


function builddmsdimension(degrees, minutes, seconds, direction)
--[[ Helper function, convert decimal to degrees, minutes, and seconds ]]
-- no error checking, done in function validdms
function convert_dec2dms_dms(coordinate)
local dimensionobject = {}
    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


--[[
-- direction and dimension (= latitude or longitude)
Convert DMS format into a N or E decimal coordinate
dimensionobject.direction = direction
]]
if direction == 'N' or direction == 'S' then
function convert_dms2dec(direction_str, degrees_str, minutes_str, seconds_str)
dimensionobject.dimension = 'latitude'
    local degrees = tonumber(degrees_str) or 0
else
    local minutes = tonumber(minutes_str) or 0
dimensionobject.dimension = 'longitude'
    local seconds = tonumber(seconds_str) or 0
end
    local direction = direction_str:match( '^%s*(.-)%s*$' );  --remove whitespace
   
-- degrees, minutes, seconds
    local factor
dimensionobject.degrees = tonumber(degrees)
    if direction == "N" or direction == "E" then
dimensionobject.minutes = tonumber(minutes)
        factor = 1
dimensionobject.seconds = tonumber(seconds)
    else
return dimensionobject
        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


function p.displaydmsdimension(valuetable, format) -- formate en latitude ou une longitude dms
--[[
local str = ''
Checks input values to for out of range errors.
local direction = valuetable.direction
]]
local degrees, minutes, seconds = '', '', ''
function validate( lat_d, lat_m, lat_s, long_d, long_m, long_s, source, strong )
local dimension
    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 format == 'dms long' then
    if strong then
direction = i18n[direction .. 'long']
        if lat_d < 0 then
else
            table.insert(errors, {source, "latitude degrees < 0 with hemisphere flag"})
direction = i18n[direction]
        end
end
        if long_d < 0 then
degrees = valuetable.degrees .. i18n.degrees
            table.insert(errors, {source, "longitude degrees < 0 with hemisphere flag"})
if valuetable.minutes then
        end
minutes = valuetable.minutes .. i18n.minutes
        --[[  
if (valuetable.minutes < 10) then
        #coordinates is inconsistent about whether this is an error.  If globe: is
minutes = '0' .. minutes
        specified, it won't error on this condition, but otherwise it will.
end
       
end
        For not simply disable this check.
if valuetable.seconds then
       
seconds = valuetable.seconds .. i18n.seconds
        if long_d > 180 then
if (valuetable.seconds < 10) then
            table.insert(errors, {source, "longitude degrees > 180 with hemisphere flag"})
seconds = '0' .. seconds
        end
end
        ]]
end
    end   
return degrees .. minutes .. seconds .. direction
       
    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 validdms(coordtable)
--[[
local direction = coordtable.direction
dec2dms
local degrees = coordtable.degrees or 0
 
local minutes = coordtable.minutes or 0
Wrapper to allow templates to call dec2dms directly.
local seconds = coordtable.seconds or 0
 
local dimension = coordtable.dimension
Usage:
    {{ Invoke:Coordinates | dec2dms | decimal_coordinate | positive_suffix |
if type(degrees) ~= 'number' or type(minutes) ~= 'number' or type(seconds) ~= 'number' then
        negative_suffix | precision }}
makeerror({message = 'coordinates should be numeric', sortkey = 'A'})
   
return false
decimal_coordinate is converted to DMS format. If positive, the positive_suffix
end
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
if dimension == 'latitude' and direction ~= 'N' and direction ~= 'S' then
to use.
makeerror({message = 'latitude direction should be N or S is ' .. (direction or 'nil'), sortkey = 'A'})
]]
return false
function coordinates.dec2dms(frame)
end
    globalFrame = frame
if dimension == 'longitude' and direction ~= 'W' and direction ~= 'E' then
    local coordinate = frame.args[1]
makeerror({message = 'latitude direction should be W or E is ' .. (direction or 'nil'), sortkey = 'A'})
    local firstPostfix = frame.args[2]
return false
    local secondPostfix = frame.args[3]
end
    local precision = frame.args[4]
 
if dimension == 'longitude' and direction ~= 'W' and direction ~= 'E' then
    return convert_dec2dms(coordinate, firstPostfix, secondPostfix, precision)
makeerror({message = 'latitude direction should be W or E is ' .. (direction or 'nil'), 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 or math.floor(minutes) ~= minutes 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
Helper function to determine whether to use D, DM, or DMS
makeerror({message = 'latitude should be number < 90, is ' .. (value or 'nil')})
format depending on the precision of the decimal input.
return false
]]
end
function coordinates.determineMode( value1, value2 )
return true
    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
end


function validlongitude(value) -- decimal longitude
--[[
if type(value) ~= 'number' or math.abs(value) > 180 then
coord
makeerror({message = 'longitude should be number < 180, is ' .. (value or 'nil')})
 
return false
Main entry point for Lua function to replace {{coord}}
end
 
return true
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
end


function p.displaydec(latitude, longitude, format)
function coordinates.latitude(frame)  -- retourne nil quand il n'y a pas de latitude (nécessaire pour certains modèles)
if format == 'dec west' then
if frame.args[1] and frame.args[1] ~= ''then
local latsymbol = i18n.N
return frame.args[1]
longitude = - longitude
elseif frame.args['wikidata'] == 'true' then
if latitude < 0 then latsymbol = i18n.S end
return wikidatacoords('latitude')
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
end


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


--- fonctions principales
function coordinates.coord(frame)
function p._coord(args)
    globalFrame = frame
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
    local text = ''
return showerrors()
   
end
    local args = frame.args
local displayformat, inputformat = args.format, args.inputformat -- one of: 'dms', 'dms long', 'dec', 'dec east' and 'dec west'
    if args[1] == nil then
local displayplace = string.lower(args.display or 'inline') -- on of 'inline', 'title' or 'inline,title'
        local pFrame = frame:getParent();
local globe = args.globe -- planet see the globedata table for accepted values
        args = pFrame.args;
local objectname = args.name -- name of the title displayed in geohack
        for k,v in pairs( frame.args ) do
local notes = (' ' and args.notes) or '' -- notes à afficher après les coordonnées
            args[k] = v;
local wikidata = args.wikidata -- string set to true when
        end
local dmslatitude, dmslongitude -- type: table when created
    end
local extraparams = args.extraparams or '' -- chaîne destinée à geohack dernier paramètre avec argument numérique dans {{Coord}}
   
local wikidataquery = args.wikidataquery
    for i=1,10 do
local trackingstring = '' -- tracking cats except error cats (already in errorstring)
        if args[i] == nil then  
            args[i] = ""
if not latitude and args.latitude and args.latitude ~= '' then -- latitude was not a number
        else
dmslatitude, dmslongitude = parsedmsstring(args.latitude), parsedmsstring(args.longitude)
            args[i] = args[i]:match( '^%s*(.-)%s*$' )--remove whitespace
if (not validdms(dmslatitude)) or (not validdms(dmslongitude)) then
        end      
return showerrors()
    end
end
    args['format'] = args['format'] or '';
latitude, longitude = p._dms2dec(dmslatitude), p._dms2dec(dmslongitude)
   
end
    if args[2] == '' and args['wikidata'] == 'true' then
        local arggeo=args[1]
-- Wikidata
args[1] = wikidatacoords('latitude')
local wikidatalatitude, wikidatalongitude, wikidataglobe
args[2] = wikidatacoords('longitude')
if wikidata == 'true' then
wikidatalatitude, wikidatalongitude, wikidataglobe = wikidatacoords(wikidataquery)
end
if wikidatalatitude and latitude then
if p._distance({latitude = latitude, longitude= longitude}, {latitude = wikidatalatitude, longitude= wikidatalongitude}, wikidataglobe) <  wikidatathreshold 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
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({'latitude or lingitude missing', sortkey = 'A'})
return showerrors()
end
-- best guesses for missing parameters
--- globe
if not globe then -- cherche le globe dans l'extraparams destinée à geohack
globe = string.match(extraparams, 'globe\:%a+')
if globe then globe = string.sub(globe, 7) end
end
if not globe or 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
    local displayinline =  string.find(displayplace, 'inline')  
    local displaytitle = string.find(displayplace, 'title')
    if not displayinline and not displaytitle then
    makeerror({message = 'bad display format:' .. displayformat, sortkey = 'C'})
     end
     end
     if displaytitle and mw.title.getCurrentTitle().namespace == 0 then
     local latdms=mw.text.split( args[1], '/' )
    trackingstring = trackingstring .. makecat(globedata[globe].trackingcat)
    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
     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
    --définition de la planète
if not dmslatitude then
    local astre
dmslatitude, dmslongitude = p._dec2dms(latitude, 'latitude'), p._dec2dms(longitude, 'longitude')
    for _, l in ipairs(args) do
end
        for w in string.gmatch(l, "globe:(%a+)") do
extraparams = extraparams .. '_globe:' .. globe -- pas de problème si le globe est en double
            astre=w
            break
-- final output
        end
local mainstring = ''
    end


if latitude and longitude and dmslatitude and dmslongitude then  
    --par défaut, on format pour un affichage en ligne
mainstring = buildHTML(latitude, longitude, dmslatitude, dmslongitude, globe, displayformat, displayinline, displaytitle, objectname,extraparams )
    local contents = formatTest(args)
else
    local Notes = args.notes or ""
showerrors()
    local Display = string.lower(args.display or "inline")
end
    if Display == '' then
return mainstring .. notes .. trackingstring .. showerrors()
        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.coord(frame) -- parrses the strange parameters of Template:Coord before sending them to p.coord
function coordinates.Coord(frame)
local args = frame.args
    return coordinates.coord(frame)
local numericargs = {}
for i,j in ipairs(args) do
args[i] = mw.text.trim(j)
if args[i] == '' then
args[i] = nil
end
if type(i) == 'number' then
table.insert(numericargs, mw.text.trim(j))
end
end
if #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
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
return coordinates

Version du 14 février 2014 à 00:14

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