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

Contenu supprimé Contenu ajouté
m géoloc sur Venus
performances : exécution de la parser function #coordinates seulement si c'est une géolocalisation affichée à côté du titre (et si namespace article, catégorie ou portail) ; overridable avec un paramètre "geodata" ; refs discussion ; props Zebulon84 en mars et avril 2022 sur le bac à sable
 
(36 versions intermédiaires par 7 utilisateurs non affichées)
Ligne 1 :
local math_mod = require( "Module:Math" )
 
local p = {}
 
local NBSP = '\194\160' -- espace insécable (code UTF-8 sur deux octets)
--Chargement de la liste En/Au/Aux/A
local gdata
local success, resultat = pcall (mw.loadData, "Module:Drapeau/Data" )
if success then
gdata = resultat
else
-- Banque de données à minima en cas de bogue dans le Module:Langue/Data
gdata={}
gdata.data={};
gdata.data[142]={qid="Q142", label="France", genre="fs"}
end
 
local i18n = {
N = 'N',
Nlong = 'Nordnord',
W = 'O',
Wlong = 'Ouestouest',
E = 'E',
Elong = 'Estest',
S = 'S',
Slong = 'Sudsud',
degrees = '° ' .. NBSP,
minutes = '′ ' .. NBSP,
seconds = '″ ' .. NBSP,
geohackurl = 'http://tools.wmflabs.org/geohack/geohack.php?language=fr',
tooltip = 'Cartes, vues aériennes, etc.',
Ligne 34 ⟶ 25 :
throughwikidata = 'Page géolocalisée par Wikidata',
invalidFormat = 'format invalide', -- 'invalid coordinate format',
invalidNSEW = 'orientation invalide, devrait être "N", "S", "E" or "W"', -- 'invalid direction should be "N", "S", "E" or "W"',
invalidNS = 'orientation de latitude invalide, devrait être "N" ou "S"', -- 'could not find latitude direction (should be N or S)',
invalidEW = 'orientation de longitude invalide, devrait être "E" ou "W"', -- 'could not find longitude direction (should be W or E) ',
noCardinalDirection = 'orientation cardinale non trouvée', -- 'no cardinal direction found in coordinates',
invalidDirection = 'direction invalide', -- 'invalid direction',
latitude90 = 'latitude > 90',
longitude360 = 'longitude > 360',
minSec60 = 'minutes ou secondes > 60',
negativeCoode = 'en format dms les degrés doivent être positifs', -- 'dms coordinates should be positive',
dmIntergers = 'degrés et minutes doivent être des nombres entiers', -- 'degrees and minutes should be integers',
tooManyParam = 'trop de paramètres pour la latitude ou la longitude', -- 'too many parameters for coordinates',
coordMissing = 'latitude ou longitude absente', -- 'latitude or longitude missing',
invalidGlobe = 'globe invalide : ', .. NBSP .. ': ', -- 'invalid globe:',
}
local coordParse = {
Ligne 58 ⟶ 49 :
SOUTH = 'S',
SUD = 'S',
}
 
--Aide:Fonction_genre
local genre = {
ms = {le="le ", du="du ", de="du ", au="au ", en="au "},
msa = {le="l'", du="de l'", de="d'", au="à l'", en="en "},
msi = {le="", du="de ", de="de ", au="à ", en="à "},
msia = {le="", du="d'", de="d'", au="à ", en="à "},
msiae = {le="", du="d'", de="d'", au="à ", en="en "},
fs = {le="la ", du="de la ", de="de ", au="à la ",en="en "},
fsa = {le="l'", du="de l'", de="d'", au="à l'", en="en "},
fsi = {le="", du="de ", de="de ", au="à ", en="à "},
fsia = {le="", du="d'", de="d'", au="à ", en="à "},
mp = {le="les ", du="des ", de="des ", au="aux ", en="aux "},
fp = {le="les ", du="des ", de="des ", au="aux ", en="aux "}
}
 
Ligne 79 ⟶ 55 :
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 eastwest', trackingcat = 'Article géolocalisé extraterrestre'},
ceres = {radius = 470, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
deimoscharon = {radius = 71214, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
dionedeimos = {radius = 5607, defaultdisplay = 'dec eastwest', trackingcat = 'Article géolocalisé extraterrestre'},
enceladusdione = {radius = 255560, defaultdisplay = 'dec eastwest', trackingcat = 'Article géolocalisé extraterrestre'},
ganymedeenceladus = {radius = 2634255, defaultdisplay = 'dec west', trackingcat = 'Article géolocalisé extraterrestre'},
earthganymede = {radius = 63712634, defaultdisplay = 'dmsdec west', trackingcat = 'Article géolocalisé sur TerreGanymède'},
europaearth = {radius = 15616371, defaultdisplay = 'dec eastdms', trackingcat = 'Article géolocalisésur extraterrestreTerre'},
hyperioneuropa = {radius = 1401561, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
iapetushyperion = {radius = 725140, defaultdisplay = 'dec eastwest', trackingcat = 'Article géolocalisé extraterrestre'},
['io']iapetus = {radius = 1322725, defaultdisplay = 'dec eastwest', trackingcat = 'Article géolocalisé extraterrestre'},
jupiter['io'] = {radius = 689111322, defaultdisplay = 'dec eastwest', trackingcat = 'Article géolocalisé extraterrestre'},
marsjupiter = {radius = 3389.568911, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé sur Marsextraterrestre' },
mercurymars = {radius = 24393389.75, defaultdisplay = 'dec east', trackingcat = 'Articlesur géolocalisé extraterrestreMars'},
mimasmercury = {radius = 1972439.7, defaultdisplay = 'dec eastwest', trackingcat = 'Articlesur géolocalisé extraterrestreMercure'},
mirandamimas = {radius = 335197, defaultdisplay = 'dec eastwest', trackingcat = 'Article géolocalisé extraterrestre'},
moonmiranda = {radius = 1736335, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé sur la Luneextraterrestre'},
neptunemoon = {radius = 245531736, defaultdisplay = 'dec east', trackingcat = 'Articlesur géolocaliséla extraterrestreLune'},
oberonneptune = {radius = 76124553, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
phoebeoberon = {radius = 110761, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
phobosphoebe = {radius = 11110, defaultdisplay = 'dec eastwest', trackingcat = 'Article géolocalisé extraterrestre'},
rheaphobos = {radius = 76511, defaultdisplay = 'dec eastwest', trackingcat = 'Article géolocalisé extraterrestre'},
saturnpluto = {radius = 582321185, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
titanrhea = {radius = 2575.5765, defaultdisplay = 'dec west', trackingcat = 'Article géolocalisé extraterrestre'},
tethyssaturn = {radius = 53058232, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
titaniatitan = {radius = 3942575.5, defaultdisplay = 'dec eastwest', trackingcat = 'Article géolocalisé extraterrestre'},
tritontethys = {radius = 1353530, defaultdisplay = 'dec west', trackingcat = 'Article géolocalisé extraterrestre'},
umbrieltitania = {radius = 584394, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
uranustriton = {radius = 252661353, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
venusumbriel = {radius = 6051.8584, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé sur Vénusextraterrestre'},
vestauranus = {radius = 26025266, defaultdisplay = 'dec east', trackingcat = 'Article géolocalisé extraterrestre'},
venus = {radius = 6051.8, defaultdisplay = 'dec east', trackingcat = 'sur Vénus'},
vesta = {radius = 260, defaultdisplay = 'dec east', trackingcat = 'extraterrestre'}
}
globedata[''] = globedata.earth
 
local wikidatathreshold = 10 -- si la distance entre coordonnées Wikipédia et Wikidata dépasse sece seuil (en kilomèteskilomètres), une catégorie de maintenance est ajoutée
local lang = mw.language.getContentLanguage()
local default_zoom = 13
 
local function makecat(cat, sortkey)
Ligne 143 ⟶ 123 :
local function makeerror(args)
local errormessage = ''
if args.message then
errormessage = ' <strong class="error"> Coordonnées' .. NBSP .. ': ' .. args.message .. '</strong>'
end
local errorcat = ''
if mw.title.getCurrentTitle().namespace == 0 then
errorcat = makecat(i18n.errorcat, args.sortkey)
end
Ligne 164 ⟶ 144 :
 
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
Ligne 176 ⟶ 156 :
return error('globe: ' .. globe .. 'is not supported')
end
 
-- calcul de la distance angulaire en radians
local convratio = math.pi / 180 -- convertit en radians
Ligne 193 ⟶ 173 :
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
 
local function geoHackUrl(decLat, decLong, globe, displayformat, objectname, extraparams)
 
 
--HTML builder for a geohack link
local function buildHTML(decLat, decLong, dmsLat, dmsLong, globe, displayformat, displayinline, displaytitle, objectname, extraparams)
local root, text, url, noprint
extraparams = extraparams or ''
local geohacklatitude, geohacklongitude
-- geohack url and parameters
-- format latitude and longitude for the URL
local decimalcoords = p.displaydec(decLat, decLong, displayformat)
if tonumber(decLat) < 0 then
local geohacklatitude, geohacklongitude
geohacklatitude = tostring(-tonumber(decLat)) .. '_S'
 
else
-- format latitude and longitude for the URL
geohacklatitude = decLat .. '_N'
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'
elseif globedata[globe].defaultdisplay == 'dec west' then
else
geohacklongitude = decLong .. '_E_W'
else
geohacklongitude = decLong .. '_E'
end
-- prepares the 'paramss=' parameter
local geohackparams = geohacklatitude .. '_' .. geohacklongitude .. '_' ..extraparams
-- concatenate parameteres for geohack
local url =return i18n.geohackurl ..
"&pagename=" .. mw.uri.encode(mw.title.getCurrentTitle().prefixedText, "WIKI") ..
"&params=" .. geohackparams ..
(objectname and ("&title=" .. mw.uri.encode(objectname)) or "")
end
 
--HTML builder for a geohack link
root = mw.html.create('')
local function buildHTML(decLat, decLong, dmsLat, dmsLong, globe, displayformat, displayinline, displaytitle, objectname, extraparams)
root
-- geohack url
:tag("span")
local url = geoHackUrl(decLat, decLong, globe, displayformat, objectname, extraparams)
:addClass("plainlinks nourlexpansion")
 
:attr('title', i18n.tooltip)
-- displayed coordinates
:wikitext("[" .. url)
local displaycoords
:tag("span")
if :addClass(string.sub(displayformat, 1, 3) == "'dec" and "geo-nondefault" or "geo-default")' then
displaycoords = p.displaydec(decLat, decLong, displayformat)
:tag("span")
else
:addClass("geo-dms")
displaycoords = {
:tag("span")
p.displaydmsdimension(dmsLat, displayformat),
:addClass("latitude")
:wikitext(p.displaydmsdimension(dmsLatdmsLong, displayformat)),
}
:done()
end
:wikitext(" ")
 
:tag("span")
-- build coordinate in h-geo / h-card microformat
:addClass("longitude")
local globeNode
:wikitext(p.displaydmsdimension(dmsLong, displayformat))
if globe and globe ~= 'earth' then
:done()
globeNode = mw.html.create('data')
:done()
:addClass('p-globe')
:attr{ value = globe }
:done()
end
 
local coordNode = mw.html.create('')
if objectname then
coordNode = mw.html.create('span')
:addClass('h-card')
:tag('data')
:addClass('p-name')
:attr{ value = objectname }
:done()
end
:tag("span")
coordNode
:addClass("geo-multi-punct")
:tag('span')
:wikitext("&ensp;/&ensp;")
:addClass('h-geo')
:addClass('geo-' .. string.sub(displayformat, 1, 3))
:tag('data')
:addClass('p-latitude')
:attr{ value = decLat }
:wikitext( displaycoords[1] )
:done()
:tagwikitext("span, ")
:tag('data')
:addClass(string.sub(displayformat,1,3) == 'dec' and "geo-default" or "geo-nondefault")
:addClass('p-longitude')
:wikitext(objectname and "<span class=\"vcard\">" or "")
:attr{ value = decLong }
:tag("span")
:addClasswikitext("geo-dec" displaycoords[2] )
:wikitext(decimalcoords)
:done()
:wikitext(objectname and ("<span style=\"display:none\"> (<span class=\"fn org\">" ..
objectname .. "</span>)</span></span>") or "")
:done()
:wikitextnode("]" globeNode )
:done()
 
-- buid GeoHack link
-- formatta il risultato a seconda di args["display"] (nil, "inline", "title", "inline,title")
local root = mw.html.create('span')
text = tostring(root)
:addClass('plainlinks nourlexpansion')
:attr('title', i18n.tooltip)
:wikitext('[' .. url )
:node(coordNode)
:wikitext("]")
:done()
 
-- format result depending on args["display"] (nil, "inline", "title", "inline,title")
noprint = displayinline and 'class="noprint" ' or ''
local inlineText = displayinline and tostring(root) or ''
htmlTitle = '<span ' .. noprint .. 'id="coordinates">' .. text .. '</span>'
local frametitleText = mw.getCurrentFrame()''
if displaytitle then
local htmlTitle = mw.html.create('span')
:attr{ id = 'coordinates' }
:addClass( displayinline and 'noprint' or nil )
:node( root )
local frame = mw.getCurrentFrame()
titleText = frame:extensionTag( 'indicator', tostring(htmlTitle), { name = 'coordinates' } )
end
 
return inlineText .. titleText
return (displayinline and text or '') ..
(displaytitle and frame:extensionTag( 'indicator', htmlTitle, { name = 'coordinates' } ) or '')
end
 
local function zoom( extraparams )
local zoomParam = extraparams:match( '%f[%w]zoom: ?(%d+)' )
if zoomParam then
return zoomParam
end
 
local scale = extraparams:match( '%f[%w]scale: ?(%d+)' )
if scale then
return math.floor(math.log10( 1 / tonumber( scale ) ) * 3 + 25)
end
 
local extraType = extraparams:match( '%f[%w]type: ?(%w+)' )
if extraType then
local zoomType = {
country = 5,
state = 6,
adm1st = 7,
adm2nd = 8,
city = 9,
isle = 10,
mountain = 10,
waterbody = 10,
airport = 12,
landmark = 13,
}
return zoomType[ extraType ]
end
end
 
--HTML builder for a geohack link
local function buildMaplinkHTML( decLat, decLong, dmsLat, dmsLong, globe, displayformat, displayinline, displaytitle, objectname, extraparams )
-- displayed coordinates
local displaycoords
if string.sub(displayformat, 1, 3) == 'dec' then
displaycoords = p.displaydec(decLat, decLong, displayformat)
else
displaycoords = {
p.displaydmsdimension(dmsLat, displayformat),
p.displaydmsdimension(dmsLong, displayformat),
}
end
 
-- JSON for maplink
local jsonParams = {
type = 'Feature',
geometry = {
type ='Point',
coordinates = {
math_mod._round( decLong, 6 ), -- max precision in GeoJSON format
math_mod._round( decLat, 6 )
}
},
properties = {
['marker-color'] = "228b22",
}
}
if objectname then
jsonParams.properties.title = objectname
end
-- ajout de geoshape via externaldata
local geoshape = extraparams:match( '%f[%w]geoshape: ?(Q%d+)' )
if not geoshape and displaytitle and mw.wikibase.getEntity() then
geoshape = mw.wikibase.getEntity().id
end
if geoshape then
jsonParams = {
jsonParams,
{
type = 'ExternalData',
service = 'geoshape',
ids = geoshape,
properties = {
['fill-opacity'] = 0.2
}
}
}
end
 
local maplink = mw.getCurrentFrame():extensionTag{
name = 'maplink',
content = mw.text.jsonEncode( jsonParams ),
args = {
text = displaycoords[1] .. ", " .. displaycoords[2],
zoom = zoom( extraparams ) or default_zoom,
latitude = decLat,
longitude = decLong,
}
}
 
-- format result depending on args["display"] (nil, "inline", "title", "inline,title")
local inlineText = displayinline and maplink or ''
local titleText = ''
if displaytitle then
local htmlTitle = mw.html.create('span')
:attr{ id = 'coordinates' }
:addClass( displayinline and 'noprint' or nil )
:wikitext( maplink )
local frame = mw.getCurrentFrame()
titleText = frame:extensionTag( 'indicator', tostring(htmlTitle), { name = 'coordinates' } )
end
 
return inlineText .. titleText
end
 
-- dms specific funcions
 
local function twoDigit( value )
if ( value < 10 ) then
value = '0' .. lang:formatNum( value )
else
value = lang:formatNum( value )
end
return value
end
 
function p.displaydmsdimension(valuetable, format) -- formate en latitude ou une longitude dms
Ligne 290 ⟶ 405 :
direction = i18n[direction]
end
degrees = lang:formatNum( valuetable.degrees ) .. i18n.degrees
 
if valuetable.minutes then
minutes = twoDigit( valuetable.minutes ) .. i18n.minutes
if (valuetable.minutes < 10) then
minutes = '0' .. minutes
end
end
if valuetable.seconds then
seconds = twoDigit( valuetable.seconds ) .. i18n.seconds
if (valuetable.seconds < 10) then
seconds = '0' .. seconds
end
end
return degrees .. minutes .. seconds .. direction
Ligne 316 ⟶ 425 :
if direction == 'N' or direction == 'S' then
dimension = 'latitude'
elseif direction == 'E' or direction == 'W' then
dimension = 'longitude'
else
Ligne 328 ⟶ 437 :
return false
end
 
if dimension == 'latitude' and direction ~= 'N' and direction ~= 'S' then
makeerror({message = i18n.invalidNS, sortkey = 'A'})
Ligne 337 ⟶ 446 :
return false
end
 
if dimension == 'latitude' and degrees > 90 then
makeerror({message = i18n.latitude90, sortkey = 'A'})
return false
end
 
if dimension == 'longitude' and degrees > 360 then
makeerror({message = i18n.longitude360, sortkey = 'A'})
return false
end
 
if degrees < 0 or minutes < 0 or seconds < 0 then
makeerror({message = i18n.negativeCoode, sortkey = 'A'})
return false
end
 
if minutes > 60 or seconds > 60 then
makeerror({message = i18n.minSec60, sortkey = 'A'})
return false
end
if (math.floor(degrees) ~= degrees and minutes ~= 0) or (math.floor(minutes) ~= minutes and seconds ~= 0) then
makeerror({message = i18n.dmIntergers, sortkey = 'A'})
Ligne 368 ⟶ 477 :
local dimensionobject = {}
 
-- direction and dimension (= latitude or longitude)
dimensionobject.direction = direction
Ligne 378 ⟶ 486 :
dimensionobject.dimension = 'longitude'
end
 
-- degrees, minutes, seconds
dimensionobject.degrees = tonumber(degrees)
Ligne 389 ⟶ 497 :
end
 
local function parsedmsstringp._parsedmsstring( str, dimension ) -- prend une séquence et donne des noms aux paramètres
-- output table: { latitude=, longitude = , direction = }
if type( str ) ~= 'string' then
return nil
Ligne 396 ⟶ 504 :
str = mw.ustring.gsub( mw.ustring.upper( str ), '%a+', coordParse )
if not tonumber( str ) and not str:find( '/' ) and str:find( '°' ) then
local str2, nb = mw.ustring.gsub( str, '[°″′\"\'\194\160 ]+', '/' )
-- avoid cases were there is degree ans seconds but no minutes
if nbnot ~=mw.ustring.find( 2str, '[″"]' ) or str:mw.ustring.find( str, '%d[′\'][ \194\160%d]' ) then
str = str2
end
end
if not tonumber(str) and not string.find(str, '/') then
makeerror({message = i18n.invalidFormat, sortkey = 'A'})
return nil
end
local args = mw.text.split(str, '/', true)
if #args > 4 then
makeerror({message = i18n.tooManyParam, sortkey = 'A' })
end
local direction = mw.text.trim(args[#args])
table.remove(args)
Ligne 423 ⟶ 531 :
--- decimal specific functions
function p.displaydec(latitude, longitude, format)
local lat = lang:formatNum( latitude )
if format == 'dec west' then
local long = lang:formatNum( longitude )
local latsymbol = i18n.N
 
longitude = - longitude
if format == 'dec west' or format == 'dec east' then
if latitude < 0 then latsymbol = i18n.S end
local symbolNS, symbolEW = i18n.N, i18n.E
if longitude < 0 then
if latitude < 0 then
longitude = 360 + longitude
symbolNS = i18n.S
lat = lang:formatNum( -latitude )
end
if format == 'dec west' then
return latitude .. i18n.degrees .. latsymbol .. ', ' .. longitude .. i18n.degrees .. i18n.W
symbolEW = i18n.W
elseif format == 'dec east' then
local latsymbol = i18n.N
if latitude < 0 then latsymbol = i18n.S end
if longitude < 0 then
longitude = 360 + longitude
end
if longitude < 0 then
return latitude .. i18n.degrees .. latsymbol .. ', ' .. longitude .. i18n.degrees .. i18n.E
long = lang:formatNum( 360 + longitude )
end
else
 
return latitude .. ', ' .. longitude
return { lat .. i18n.degrees .. symbolNS, long .. i18n.degrees .. symbolEW }
 
else
return { lat, long }
end
end
 
 
local function parsedec(dec, coordtype, globe) -- coordtype = latitude or longitude
dec = mw.text.trim(dec)
if not dec then
if coordtype ~= 'latitude' and coordtype ~= 'longitude' then
makeerror({'invalid coord type', sortkey = "A"})
return nil
end
if coordtype ~= 'latitude' and coordtype ~= 'longitude' then
if not dec then
makeerror({'invalid coord type', sortkey = "A"})
return nil
end
Ligne 463 ⟶ 572 :
return nil
end
if direction == 'N' or direction == 'E' or direction == 'W' and globedata[globe].defaultdisplay == 'dec west' then
returnnumdec = tonumber( dec )
elseif direction == 'W' or direction == 'S' then
returndec = '-' .. dec
numdec = tonumber( dec )
else
if coordtype == 'latitude' then
Ligne 487 ⟶ 597 :
return dec
end
 
p.parsedec = parsedec
 
-- dms/dec conversion functions
Ligne 520 ⟶ 628 :
local degrees = dec % 360
return degrees, minutes
end
 
local function dec2dms_dms(dec)
Ligne 532 ⟶ 640 :
end
 
function p._dec2dms(dec, coordtype, precision, globe) -- typecoordtype: latitude or longitude
 
local degrees, minutes, seconds
 
-- vérification du globe
if not ( globe and globedata[ globe ] ) then
globe = 'earth'
end
 
-- precision
if not precision or precision == '' then
Ligne 544 ⟶ 656 :
end
local dec = tonumber(dec)
 
-- direction
-- direction
if coordtype == 'latitude' then
local direction
if coordtype == 'latitude' then
if dec < 0 then
direction = 'S'
else
direction = 'N'
end
elseif coordtype == 'longitude' then
if dec < 0 or globedata[globe].defaultdisplay == 'dec west' 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
degrees, minutes, seconds = dec2dms_dms(dec)
elseif precision == 'dm' then
Ligne 572 ⟶ 686 :
 
function p.dec2dms(frame) -- legacy function somewhat cumbersome syntax
local args = frame.args
local dec = args[1]
if not tonumber(dec) then
makeerror({message = i18n.invalidFormat, sortkey = 'A'})
return showerrors()
end
local dirpositive = string.lower(args[2] or '')
local dirnegative = string.lower(args[3] or '')
local precision = string.lower(args[4] or '')
local displayformat, coordtype
 
if args[2]dirpositive == 'Nn' or args[2]dirpositive == 'Nordnord' then
coordtype = 'latitude'
else
coordtype = 'longitude'
end
if args[2]dirpositive == 'Nordnord' or args[2]dirpositive == 'Estest' or args[3]dirnegative == 'Ouestouest' or args[3]dirnegative == 'Sudsud' then
displayformat = 'dms long'
end
Ligne 604 ⟶ 720 :
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 = i18n.noCardinalDirection, sortkey = 'A'})
return nil
Ligne 616 ⟶ 732 :
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é ?
Ligne 624 ⟶ 740 :
precision = math.max( math_mod._precision(tostring(degrees), 0 ) )
end
 
local decimal = factor * (degrees+(minutes+seconds/60)/60)
return math_mod._round(decimal, precision)
Ligne 631 ⟶ 747 :
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
local dmsobject = parsedmsstringp._parsedmsstring(args[1])
if dmsobject then
return p._dms2dec(dmsobject) -- coordonnées sous la fore 23/22/N
else
local coordType
if args[1]:match( '[NS]' ) then
coordType = 'latitude'
elseif args[1]:match( '[EWO]') then
coordType = 'longitude'
end
if coordType then
local result = parsedec( args[1], coordType, args.globe or 'earth' )
if result then
return result
end
end
return showerrors()
end
else
return p._dms2dec({direction = args[1], degrees = tonumber(args[2]), minutes = tonumber(args[3]), seconds = tonumber(args[4])})
end
end
Ligne 663 ⟶ 791 :
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
-- Wikidata does not handle correctly +West longitudes
if globedata[ coords.globe ] and globedata[ coords.globe ].defaultdisplay == 'dec west' then
coords.longitude = math.abs( coords.longitude )
end
return coords.latitude, coords.longitude, coords.globe or 'earth', convertwikidataprecision(coords.precision or .001)
end
Ligne 671 ⟶ 803 :
local function wikidatacat(globe)
--catbase= Article géolocalisé sur Terre
local entitycat = mw.wikibase.getEntityObjectgetEntity()
 
local basecat = 'Article géolocalisé'
local finalcat = {}
--BADGES
if entitycat then
--BADGES
for i, badgeId in ipairs( entitycat.sitelinks['frwiki'].badges ) do
if badgeId == 'Q17437796' then
basecat = string.gsub(basecat, "Article géolocalisé", "Article de qualité géolocalisé")
end
if badgeId == 'Q17437798' then
basecat = string.gsub(basecat, "Article géolocalisé", "Bon article géolocalisé")
end
end
Ligne 690 ⟶ 822 :
if globe == 'earth' then
if entitycat and entitycat.claims then
local country = entitycat.claims['P17']
if not country then
--pas pays à récupérer
basecat = basecat .. ' sur Terre'
table.insert(finalcat, basecat)
else
--parfois plusieurs pays
for i, paysId in ipairs( country ) do
--on fait confiance au label wikidata
local gdataone, qid
 
if paysId.mainsnak.snaktype == 'value' then
qid = paysId.mainsnak.datavalue.value['numeric-id']
gdataone =gdata mw.loadData("Module:Drapeau/Data").data[qid]
else
--Bir Tawil n'a pas de pays connu
qid = '?'
end
if gdataone ~= nil then
local prep=genre[gdataone['genre']]['en'] or= 'en 'mw.loadData("Module:Drapeau/Domaine").genre
local thecatprep =basecat .. genre[gdataone[' genre'..prep]]['en'] ..mw.wikibase.label(or 'Q'..en qid)'
local thecat = basecat .. ' '..prep ..mw.wikibase.label('Q'.. qid)
if mw.title.new('category:'..thecat).exists then
table.insert(finalcat, thecat)
else
--Dommage!
Ligne 724 ⟶ 857 :
if #finalcat == 0 then
--pas pays à récupérer
basecat = basecat .. ' sur Terre'
table.insert(finalcat, basecat)
end
end
else
--pas wikidata
basecat = basecat .. ' sur Terre'
table.insert(finalcat, basecat)
end
elseif globedata[globe == 'moon' ] then
basecat = basecat .. ' sur' la.. Lune'globedata[globe].trackingcat
table.insert(finalcat, basecat)
elseif globe == 'mars' then
basecat=basecat .. ' sur Mars'
table.insert(finalcat,basecat)
else
basecat = basecat .. ' extraterrestre'
table.insert(finalcat, basecat)
end
return finalcat
Ligne 749 ⟶ 879 :
function p._coord(args)
 
-- I declare variable
local displayformat = args.format -- string: one of: 'dms', 'dms long', 'dec', 'dec east' and 'dec west'
local displayplace = string.lower(args.display or 'inline') --string: one of 'inline', 'title' or 'inline,title'
local displayinline = string.find(displayplace, 'inline') and true or false
local displaytitle = string.find(displayplace, 'title') and true or false
local objectname = (args.name ~= '') and args.name -- string: name of the title displayed in geohack
local notes = (' ' and args.notes) or '' -- string: notes to de displayed after coordinates
local wikidata = args.wikidata -- string: set to "true" if needed
local wikidataquery = args.wikidataquery -- table: see [[Module:Wikidata]] see function wikidatacoords
local dmslatitude, dmslongitude -- table (when created)
local extraparams = args.extraparams or '' -- string (legacy, corresponds to geohackparams)
local trackingstring = '' -- tracking cats except error cats (already in errorstring)
Ligne 762 ⟶ 894 :
if rawlat == '' then rawlat = nil end
if rawlong == '' then rawlong = nil end
local globe = string.lower( args.globe or extraparams:match('globe:(%a+)') or '' ) -- string: see the globedata table for accepted values
local latitude, longitude, precision, dmslatitude, dmslongitude -- latitude and longitude in decimal / dmslatitude and dmslongitude: tables withdms coords
local maplink = true -- use maplink whenever it is possible
local savegeodata = nil
if args.geodata ~= nil and args.geodata ~= '' then
savegeodata = require('Module:Yesno')(args.geodata)
end
if savegeodata == nil then -- args.geodata non renseigné ou valeur non reconnue
savegeodata = (displaytitle and mw.title.getCurrentTitle():inNamespaces(0, 14, 100))
end
 
-- II extract coordinates from Wikitext
if (rawlat or rawlong) then
Ligne 771 ⟶ 911 :
return showerrors()
end
latitude = parsedec(rawlat, 'latitude', globe)
 
if latitude then -- if latitude is decimal
longitude = parsedec(rawlong, 'longitude', globe) -- so should be longitude
precision = determinedmsprec({latitude, longitude}) -- before conversion from string to number for trailing zeros
if not latitude or not longitude then
Ligne 782 ⟶ 922 :
return showerrors()
end
dmslatitude, dmslongitude = p._dec2dms(latitude, 'latitude', precision), p._dec2dms(longitude, 'longitude', precision, globe)
latitude, longitude = tonumber(latitude), tonumber(longitude)
else -- if latitude is not decimal try to parse it as a dms string
dmslatitude, dmslongitude = parsedmsstringp._parsedmsstring(args.latitude, 'latitude'), parsedmsstringp._parsedmsstring(args.longitude, 'longitude')
if not dmslatitude or not dmslongitude then
return showerrors()
Ligne 794 ⟶ 934 :
 
-- III extract coordinate data from Wikidata and compare them to local data
local wikidatalatitude, wikidatalongitude, wikidataglobe, wikidataprecision
if wikidata == 'true' then
wikidatalatitude, wikidatalongitude, wikidataglobe, wikidataprecision = wikidatacoords(wikidataquery)
 
if wikidatalatitude and latitude and longitude 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
Ligne 808 ⟶ 948 :
if wikidatalatitude and not latitude then
latitude, longitude, globe, precision = wikidatalatitude, wikidatalongitude, wikidataglobe, wikidataprecision
dmslatitude, dmslongitude = p._dec2dms(latitude, 'latitude', precision), p._dec2dms(longitude, 'longitude', precision, globe)
trackingstring = trackingstring .. makecat(i18n.throughwikidata)
end
 
if latitude and not wikidatalatitude then
if mw.title.getCurrentTitle().namespace == 0 then
Ligne 826 ⟶ 966 :
 
-- IV best guesses for missing parameters
 
--- globe
if globe == '' then -- cherche le globe dans l'extraparams destinée à geohack
globe = 'earth'
local globe2 = string.match(extraparams:lower(), 'globe\:%a+')
if globe2 then
globe = string.sub(globe2, 7)
end
if globe == '' then
globe = 'earth'
end
end
if not globedata[globe] then
Ligne 841 ⟶ 975 :
globe = 'earth'
end
if globe ~= 'earth' then
extraparams = extraparams .. '_globe:' .. globe -- pas de problème si le globe est en double
maplink = false
end
 
--- diplayformat
if not displayformat or displayformat == '' then
displayformat = globedata[globe].defaultdisplay
end
 
-- displayinline/displaytitle
if localnot displayinline = and string.find(displayplace,not 'inline')displaytitle then
displayinline = true
local displaytitle = string.find(displayplace, 'title')
if displayplace ~= '' then
if not displayinline and not displaytitle then
makeerror({sortkey = 'C'}) --error if display not empty, but not a major error, continue
displayinline = true
end
if displayplace ~= '' then
end
makeerror({sortkey = 'C'}) --error if display not empty, but not not a major error, continue
if displaytitle and mw.title.getCurrentTitle().namespace == 0 then
end
--local cattoappend = globedata[globe].trackingcat
end
--Récupération des badges
if displaytitle and mw.title.getCurrentTitle().namespace == 0 then
-- local cattoappendcats =globedata[ wikidatacat(globe].trackingcat)
for i, cat in ipairs( cats ) do
--Récupération des badges
trackingstring = trackingstring .. makecat(cat)
local cats=wikidatacat(globe)
end
for i, cat in ipairs( cats ) do
 
trackingstring = trackingstring .. makecat(cat)
end
 
end
-- V geodata
local geodata = ''
if savegeodata and latitude and longitude then
local latstring, longstring = tostring(latitude), tostring(longitude)
local primary = ''
 
local frame = mw.getCurrentFrame()
local geodataparams = {[1] = latstring, [2] = longstring, [3] = extraparams }
if displaytitle then
geodataparams[4] = 'primary'
Ligne 880 ⟶ 1 016 :
geodataparams.name = objectname
end
geodata = frame:callParserFunction('#coordinates', geodataparams )
if string.find(geodata, 'error') then -- the only error that has not been caught yet is primary key
geodata = ''
makeerror({sortkey='D'})
end
end
-- VI final output
if globe ~= 'earth' then
extraparams = extraparams .. '_globe:' .. globe -- pas de problème si le globe est en double
end
-- VI final output
 
local mainstring = ''
if args.formatitlemaplink then
mainstring = buildMaplinkHTML(latitude, longitude, dmslatitude, dmslongitude, globe, displayformat, displayinline, displaytitle, objectname, extraparams)
if displaytitle then
mainstring = mainstring .. buildHTML(latitude, longitude, dmslatitude, dmslongitude, globe, args.formatitle, false, true, objectname,extraparams )
end
if displayinline then
mainstring = mainstring .. buildHTML(latitude, longitude, dmslatitude, dmslongitude, globe, displayformat, true, false, objectname,extraparams )
end
else
mainstring = buildHTML(latitude, longitude, dmslatitude, dmslongitude, globe, displayformat, displayinline, displaytitle, objectname,extraparams extraparams)
end
 
return mainstring .. notes .. trackingstring .. geodata .. showerrors()
end
 
function p.coord(frame) -- parrsesparses 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
Ligne 949 ⟶ 1 076 :
return p.coord(frame)
end
 
 
function p.latitude(frame) -- helper function pour infobox, à déprécier
Ce document provient de « https://fr.wikipedia.org/wiki/Module:Coordinates ».