Modifications

Sauter à la navigation Sauter à la recherche
14 645 octets ajoutés ,  7 août 2020 à 18:21
Copier-coller de wikipedia
--[[This module is intended to replace the functionality of {{Coord}} and relatedtemplates. It provides several methods, includinglocal math_mod = require( "Module:Math" )
local p = {{#invoke:Coordinates | coord }} : General function formatting and displayingcoordinate values.
--Chargement de la liste En/Au/Aux/Alocal gdatalocal success, resultat = pcall (mw.loadData, "Module:Drapeau/Data" )if success then gdata = resultatelse -- Banque de données à minima en cas de bogue dans le Module:Langue/Data gdata={} gdata.data={#invoke:Coordinates | dec2dms }; gdata.data[142]={qid="Q142", label="France", genre="fs"} : Simple function for converting decimaldegree values to DMS format.end
local i18n = {{#invoke N = 'N', Nlong = 'nord', W = 'O', Wlong = 'ouest', E = 'E', Elong = 'est', S = 'S', Slong = 'sud', degrees = '° ', minutes = '′ ', seconds = '″ ', geohackurl = 'http:Coordinates | dms2dec }} : Simple function for converting DMS //tools.wmflabs.org/geohack/geohack.php?language=fr', tooltip = 'Cartes, vues aériennes, etc.', errorcat = 'Page 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', nowikidata = 'Page sans coordonnées Wikidata', 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',to decimal degree 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 : ', -- 'invalid globe:',}local coordParse = { NORTH = 'N', NORD = 'N', EAST = 'E', EST = 'E', WEST = 'W', O = 'W', OUEST = 'W', SOUTH = 'S', SUD = 'S',}
--Aide:Fonction_genrelocal 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 = {#invoke:Coordinates | link 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 "}} : Export the link used to reach the tools
local globedata = { --[[ notes: radius in kilometers (especially imprecise for non spheric bodies) defaultdisplay is currently disabled, activate it ? ]]-- ariel = {radius = 580, defaultdisplay = 'dec east', trackingcat = 'extraterrestre'}, callisto = {radius = 2410, defaultdisplay = 'dec west', trackingcat = 'extraterrestre'}, ceres = {radius = 470, defaultdisplay = 'dec east', trackingcat = 'extraterrestre'}, charon = {radius = 1214, defaultdisplay = 'dec east', trackingcat = 'extraterrestre'}, deimos = {radius = 7, defaultdisplay = 'dec west', trackingcat = 'extraterrestre'}, dione = {radius = 560, defaultdisplay = 'dec west', trackingcat = 'extraterrestre'}, enceladus = {radius = 255, defaultdisplay = 'dec west', trackingcat = 'extraterrestre'}, ganymede = {radius = 2634, defaultdisplay = 'dec west', trackingcat = 'sur Ganymède'}, earth = {radius = 6371, defaultdisplay = 'dms', trackingcat = 'sur Terre'}, europa = {radius = 1561, defaultdisplay = 'dec east', trackingcat = 'extraterrestre'}, hyperion = {radius = 140, defaultdisplay = 'dec west', trackingcat = 'extraterrestre'}, iapetus = {radius = 725, defaultdisplay = 'dec west', trackingcat = 'extraterrestre'}, ['io'] = {radius = 1322, defaultdisplay = 'dec west', trackingcat = 'extraterrestre'}, jupiter = {radius = 68911, defaultdisplay = 'dec east', trackingcat = 'extraterrestre'}, mars = {radius = 3389.5, defaultdisplay = 'dec east', trackingcat = 'sur Mars' }, mercury = {radius = 2439.7, defaultdisplay = 'dec west', trackingcat = 'sur Mercure'}, mimas = {radius = 197, defaultdisplay = 'dec west', trackingcat = 'extraterrestre'}, miranda = {radius = 335, defaultdisplay = 'dec east', trackingcat = 'extraterrestre'}, moon = {radius = 1736, defaultdisplay = 'dec', trackingcat = 'sur la Lune'}, neptune = {radius = 24553, defaultdisplay = 'dec east', trackingcat = 'extraterrestre'}, oberon = {radius = 761, defaultdisplay = 'dec east', trackingcat = 'extraterrestre'}, phoebe = {radius = 110, defaultdisplay = 'dec west', trackingcat = 'extraterrestre'}, phobos = {radius = 11, defaultdisplay = 'dec west', trackingcat = 'extraterrestre'}, pluto = {radius = 1185, defaultdisplay = 'dec east', trackingcat = 'extraterrestre'}, rhea = {radius = 765, defaultdisplay = 'dec west', trackingcat = 'extraterrestre'}, saturn = {radius = 58232, defaultdisplay = 'dec east', trackingcat = 'extraterrestre'}, titan = {radius = 2575.5, defaultdisplay = 'dec west', trackingcat = 'extraterrestre'}, tethys = {radius = 530, defaultdisplay = 'dec west', trackingcat = 'extraterrestre'}, titania = {radius = 394, defaultdisplay = 'dec east', trackingcat = 'extraterrestre'}, triton = {radius = 1353, defaultdisplay = 'dec east', trackingcat = 'extraterrestre'}, umbriel = {radius = 584, defaultdisplay = 'dec east', trackingcat = 'extraterrestre'}, uranus = {radius = 25266, defaultdisplay = 'dec east', trackingcat = 'extraterrestre'}, venus = {radius = 6051.8, defaultdisplay = 'dec east', trackingcat = 'sur Vénus'}, vesta = {radius = 260, defaultdisplay = 'dec east', trackingcat = 'extraterrestre'}}globedata[''] = globedata.earth
requirelocal wikidatathreshold = 10 -- si la distance entre coordonnées Wikipédia et Wikidata dépasse se seuil ('Module:No globals'en kilomètes), une catégorie de maintenance est ajoutéelocal lang = mw.language.getContentLanguage()local default_zoom = 13
local math_mod = requirefunction makecat("Module:Math"cat, sortkey)local coordinates if type( sortkey ) = {};= 'string' then return '[[Category:' .. cat .. '|' .. sortkey .. ']]' else return '[[Category:' .. cat .. ']]' endend
local current_page = mw.title.getCurrentTitle------------------------------------------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)local page_name = mw.uri.encode( current_page.prefixedText More minor errors do only add a category, so that readers are not bothered with error texts sortkeys: * A: invalid latitude, 'WIKI' );longitude or direction * B: invalid globe * C: something wrong with other parameters * D: more than one primary coordlocal coord_link = '//tools.wmflabs.org/geohack/geohack.php?pagename=' .. page_name .. '&params=' ]]--
--[[ Helper function, replacement for {{coord/display/title}} ]]local errorstring = '' local function displaytitlemakeerror(s, notesargs) local l errormessage = "[[Geographic coordinate system|Coordinates]]: " '' if args.. smessage then local co errormessage = '<span idstrong class="coordinateserror">Coordonnées : ' .. l .args. notes message .. '</spanstrong>'; return end local errorcat = ''<span style if mw.title.getCurrentTitle().namespace == 0 then errorcat ="font-size: small;">' makecat(i18n.errorcat, args. co sortkey) end errorstring = errormessage .. '</span>';errorcat -- reinitializes the string to avoid absurdly long messages return nil
end
--[[ Helper function, Replacement for {{coord/display/inline}} ]]local function displayinlineshowerrors(s, notes) return s .. noteserrorstring
end
--[[ Helper function, used in detecting DMS formatting ]]
local function dmsTest(first, second)
if type(first) ~= 'string' or type(second) ~= 'string' then
return nil
end
local s = (first .. second):upper()
return s:find('^[NS][EW]$') or s:find('^[EW][NS]$')
end
--Distance computationfunction p._distance(a, b, globe) -- calcule la [[ Wrapper function to grab args, see Module:Arguments for this function's documentation. distance orthodromique]]en kilomètres entre deux points du globe local function makeInvokeFunc globe = string.lower(funcNameglobe or 'earth') return function (frame) -- check arguments and converts degreees to radians local args latA, latB, longA, longB = requirea.latitude, b.latitude, a.longitude, b.longitude if (not latA) or (not latB) or ('Module:Arguments'not longA).getArgsor (frame, { wrappers = 'Template:Coord' }not longB)then return return error('coordinates[funcName](argsmissing, framecan\'t compute distance')
end
if type(latA) ~= 'number' or type(latB) ~= 'number' or type(longA) ~= 'number' or type(longB) ~= 'number' then
error('coordinates are not numeric, can\'t compute distance')
end
if not globe or not globedata[globe] then
return error('globe: ' .. globe .. 'is not supported')
end
-- calcul de la distance angulaire en radians
local convratio = math.pi / 180 -- convertit en radians
latA, latB, longA, longB = convratio * latA, convratio * latB, convratio * longA, convratio * longB
local cosangle = math.sin(latA) * math.sin(latB) + math.cos(latA) * math.cos(latB) * math.cos(longB - longA)
if cosangle >= 1 then -- may be above one because of rounding errors
return 0
end
local angle = math.acos(cosangle)
-- calcul de la distance en km
local radius = globedata[globe].radius
return radius * angle
end
--[[ Helper functionp.distance(frame) local args = frame.args return p._distance( {latitude = tonumber(args.latitude1), handle optional longitude = tonumber(args. ]]longitude1)}, local function optionalArg {latitude = tonumber(argargs.latitude2), supplementlongitude = tonumber(args.longitude2)}, return arg and arg args.. supplement or ''globe)
end
--[[Formats any error messages generated for display]]local function errorPrintergeoHackUrl(errorsdecLat, decLong, globe, displayformat, objectname, extraparams) extraparams = extraparams or '' local result = ""geohacklatitude, geohacklongitude -- format latitude and longitude for i,v in ipairsthe URL if tonumber(decLat) < 0 then geohacklatitude = tostring(-tonumber(errorsdecLat) do) .. '_S' else local errorHTML geohacklatitude = decLat .. '_N' end if tonumber(decLong) <strong class0 then geohacklongitude ="error">Coordinates: ' tostring(-tonumber(decLong)) .. v'_W' elseif globedata[2globe] .. defaultdisplay == '</strong>dec west'then result geohacklongitude = result decLong .. errorHTML '_W' else geohacklongitude = decLong .. "<br />"'_E'
end
-- prepares the 'paramss=' parameter local geohackparams = geohacklatitude .. '_' .. geohacklongitude .. '_' ..extraparams -- concatenate parameteres for geohack return resulti18n.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 linklocal function buildHTML(decLat, decLong, dmsLat, dmsLong, globe, displayformat, displayinline, displaytitle, objectname, extraparams)Determine the required CSS class to display -- geohack url local url = geoHackUrl(decLat, decLong, globe, displayformat, 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 Usually -- build coordinate in h-geo/ h-nondefault is hidden by CSS, unless a user has overridden this for himselfcard microformat local globeNode if globe and globe ~= 'earth' then globeNode = mw.html.create('data') :addClass('p-globe')default is the mode as specificied by the user when calling the :attr{{coordvalue = globe }} templatemode is the display mode :done(dec or dms) that we will need to determine the css class for]] end local function displayDefaultcoordNode = mw.html.create(default, mode'') if default == "" objectname then default coordNode = mw.html.create('span') :addClass('h-card') :tag('data') :addClass('p-name') :attr{ value = "dec"objectname } :done()
end
  if default == mode thencoordNode return ":tag('span') :addClass('h-geo') :addClass('geo-default' .. string.sub(displayformat,1,3)) :tag('data') :addClass('p-latitude') :attr{ value = decLat } :wikitext( displaycoords[1] ) :done() :wikitext(", ") :tag('data') :addClass('p-longitude') :attr{ value = decLong } :wikitext( displaycoords[2] ) :done() :node( globeNode ) :done() else -- buid GeoHack link local root = mw.html.create('span') :addClass('plainlinks nourlexpansion') :attr('title', i18n.tooltip) return :wikitext('[' .. url ) :node(coordNode) :wikitext("geo]") :done() --nondefaultformat result depending on args["display"] (nil, "inline", "title", "inline,title") local inlineText = displayinline and tostring(root) or '' local titleText = '' 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
end
--[[specPrinter Output formatter. Takes the structure generated by either parseDecor parseDMS and formats it for inclusion on Wikipedia.]]local function specPrinterzoom(args, coordinateSpecextraparams ) local uriComponents zoomParam = coordinateSpecextraparams:match( '%f["param"%w]zoom: ?(%d+)' ) if uriComponents == "" zoomParam then -- RETURN error, should never be empty or nilreturn zoomParam end local scale = extraparams:match( '%f[%w]scale: ?(%d+)' ) if scale then return "ERROR param was empty"math.floor(math.log10( 1 / tonumber( scale ) ) * 3 + 25)
end
if args local extraType = extraparams:match( '%f["name"%w] type: ?(%w+)' ) if extraType then uriComponents local zoomType = { country = 5, state = 6, adm1st = 7, adm2nd = uriComponents .. "&title8, city =" .. mw.uri.encode(coordinateSpec9, isle = 10, mountain = 10, waterbody = 10, airport = 12, landmark = 13, } return zoomType["name"extraType ])
end
end
--HTML builder for a geohack linklocal geodmshtml = '<span class="geo-dms" title="Mapsfunction buildMaplinkHTML( decLat, decLong, dmsLat, dmsLong, globe, displayformat, displayinline, displaytitle, aerial photosobjectname, and other data for this location">'extraparams ) .. '<span class="latitude">' .. coordinateSpec["dms -lat"] .. '</span> ' .. '<span class="longitude">' ..coordinateSpec["dms-long"] .. '</span>' .. '</span>'displayed coordinates local lat = tonumber( coordinateSpec["dec-lat"] ) or 0 local geodeclatdisplaycoords if lat < 0 string.sub(displayformat,1,3) == 'dec' then -- FIXME this breaks the pre-existing precision geodeclat displaycoords = tostringp.displaydec(coordinateSpec["dec-lat"]decLat, decLong, displayformat):sub(2) .. "°S"
else
geodeclat displaycoords = { p.displaydmsdimension(dmsLat, displayformat), p.displaydmsdimension(coordinateSpecdmsLong, 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"dec, } } if objectname then jsonParams.properties.title = objectname end -lat"- ajout de geoshape via externaldata local geoshape = extraparams:match( '%f[%w] or 0geoshape: ?(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. "°N"2 } } }
end
local long maplink = tonumbermw.getCurrentFrame():extensionTag{ name = 'maplink', content = mw.text.jsonEncode( coordinateSpecjsonParams ), args = { text = displaycoords[1] .. "dec, " .. displaycoords[2], zoom = zoom( extraparams ) or default_zoom, latitude = decLat, longitude = decLong, } } -long- format result depending on args["display"] (nil, "inline", "title", "inline,title") local inlineText = displayinline and maplink or 0'' local geodeclongtitleText = '' if long < 0 displaytitle then -- FIXME does not handle unicode minuslocal htmlTitle = mw.html.create('span') geodeclong :attr{ id = tostring'coordinates' } :addClass(coordinateSpec["dec-long"]displayinline and 'noprint' or nil ) :subwikitext(2maplink ) local frame = mw.. "°W" elsegetCurrentFrame() geodeclong titleText = frame:extensionTag( 'indicator', tostring(coordinateSpec["dec-long"] or 0htmlTitle), { name = 'coordinates' } ) .. "°E"
end
return inlineText .. titleText
end
local geodechtml = '<span class="geo-dec" title="Maps, aerial photos, and other data for this location">' .. geodeclat .. ' ' .. geodeclong .. '</span>'- dms specific funcions
local geonumhtml = '<span class="geo">' .. coordinateSpec["dec-lat"] .. '; ' .. coordinateSpec["dec-long"] .. '</span>'function twoDigit( value ) local inner = '<span class="' .. displayDefaultif (coordinateSpec["default"], "dms" ) .. '">' .. geodmshtml .. '</span>' .. '<span class="geo-multi-punct">&#xfeff; / &#xfeff;</span>' .. 'value <span class="' .. displayDefault(coordinateSpec["default"], "dec" 10 ) .. '">';  if not args["name"] then inner value = inner .. geodechtml .. '<span style="display:none">&#xfeff; / 0' .. geonumhtml .. '</span></span>'lang:formatNum( value )
else
inner value = inner .. '<span class="vcard">' .. geodechtml .. '<span style="displaylang:none">&#xfeff; / ' .. geonumhtml .. '</span>' .. '<span style="display:none">&#xfeff; formatNum(<span class="fn org">' .. args["name"] .. '</span>value )</span></span></span>'
end
  return '<span class="plainlinks nourlexpansion">' .. '[' .. coord_link .. uriComponents .. ' ' .. inner .. ']' .. '</span>'end --[[ Helper function, convert decimal to degrees ]]local function convert_dec2dms_d(coordinate) local d = math_mod._round( coordinate, 0 ) .. "°" return d .. ""value
end
--[[ Helper function, convert decimal to degrees and minutes ]]local function convert_dec2dms_dm(coordinate) coordinate = math_modp._rounddisplaydmsdimension( coordinate * 60valuetable, 0 format);-- formate en latitude ou une longitude dms local m str = coordinate % 60;'' coordinate local direction = mathvaluetable.floor( (coordinate - m) / 60 );direction local d degrees, minutes, seconds = coordinate % 360 .."°"'', '', '' local dimension
return d .. string.if format( "%02d′", m )end --[[ Helper function, convert decimal to degrees, minutes, and seconds ]]local function convert_dec2dms_dms(coordinate) coordinate = math_mod._round( coordinate * 60 * 60, 0 ); local s = coordinate % 60'dms long' then coordinate direction = math.floor( (coordinate - s) / 60 ); local m = coordinate % 60 coordinate = math.floor( (coordinate - m) / 60 ); local d = coordinate % 360 .."°"  return d .. string.format( "%02d′", m ) .i18n[direction . string.format( "%02d″", s )end --[[Helper function, convert decimal latitude or longitude todegrees, minutes, and seconds format based on the specified precision.]'long']local function convert_dec2dms(coordinate, firstPostfix, secondPostfix, precision) local coord = tonumber(coordinate) local postfix if coord >= 0 then postfix = firstPostfix
else
postfix direction = 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;i18n[direction]
end
end --[[Convert DMS format into a N or E decimal coordinate]]local function convert_dms2dec(direction, degrees_str, minutes_str, seconds_str) local degrees = tonumberlang:formatNum(degrees_strvaluetable.degrees ).. i18n.degrees local minutes = tonumber(minutes_str) or 0 local seconds = tonumber(seconds_str) or 0  local factor = 1 if direction == "S" or direction == "W" valuetable.minutes then factor minutes = -1twoDigit( valuetable.minutes ) .. i18n.minutes
end
  local precision = 0 if seconds_str valuetable.seconds then precision seconds = 5 + math.maxtwoDigit( math_modvaluetable._precision(seconds_strseconds ), 0 ); elseif minutes_str and minutes_str ~= '' then precision = 3 + math.max( math_mod._precision(minutes_str), 0 ); else precision = math.max( math_modi18n._precision(degrees_str), 0 );seconds
end
  local decimal = factor * (return degrees+(minutes+seconds/60)/60) return string.format( "%." minutes .. precision .seconds . "f", decimal ) -- not tonumber since this whole thing is string based.direction
end
--[[Checks input values to for out of range errors.]]local function validatevaliddms( lat_d, lat_m, lat_s, long_d, long_m, long_s, source, strong coordtable) local errors direction = {};coordtable.direction lat_d local degrees = tonumber( lat_d ) coordtable.degrees or 0; lat_m local minutes = tonumber( lat_m ) coordtable.minutes or 0; lat_s local seconds = tonumber( lat_s ) coordtable.seconds or 0; long_d local dimension = tonumber( long_d ) or 0;coordtable.dimension long_m if not dimension then if direction == tonumber( long_m ) 'N' or 0;direction == 'S' then dimension = 'latitude' long_s elseif direction == tonumber( long_s ) 'E' or 0;direction == 'W' then   if strong then dimension = 'longitude' if lat_d < 0 thenelse table.insertmakeerror(errors, {sourcemessage = i18n.invalidNSEW, "latitude degrees < 0 with hemisphere flag"sortkey = 'A'}) return false
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 type(degrees) ~= 'number' or type(minutes) ~= 'number' or type(seconds) ~= 'number' then table.insertmakeerror(errors, {sourcemessage = i18n.invalidFormat, "latitude degrees > 90"sortkey = 'A'}) return false
end
if lat_d < -90 dimension == 'latitude' and direction ~= 'N' and direction ~= 'S' then table.insertmakeerror(errors, {sourcemessage = i18n.invalidNS, "latitude degrees < -90"sortkey = 'A'}) return false
end
if lat_m >dimension = 60 = 'longitude' and direction ~= 'W' and direction ~= 'E' then table.insertmakeerror(errors, {sourcemessage = i18n.invalidEW, "latitude minutes >sortkey = 60"'A'}) return false
end
if lat_m < 0 dimension == 'latitude' and degrees > 90 then table.insertmakeerror(errors, {sourcemessage = i18n.latitude90, "latitude minutes < 0"sortkey = 'A'}) return false
end
if lat_s dimension == 'longitude' and degrees >= 60 360 then table.insertmakeerror(errors, {sourcemessage = i18n.longitude360, "latitude seconds >sortkey = 60"'A'}) return false
end
if lat_s degrees < 0 or minutes < 0 or seconds < 0 then table.insertmakeerror(errors, {sourcemessage = i18n.negativeCoode, "latitude seconds < 0"sortkey = 'A'}) return false
end
if long_d minutes >60 or seconds > 60 then makeerror({message = 360 i18n.minSec60, sortkey = 'A'}) return false end if (math.floor(degrees) ~= degrees and minutes ~= 0) or (math.floor(minutes) ~= minutes and seconds ~= 0) then table.insertmakeerror(errors, {sourcemessage = i18n.dmIntergers, "longitude degrees >sortkey = 360"'A'}) return false
end
return trueend local function builddmsdimension(degrees, minutes, seconds, direction, dimension) -- no error checking, done in function validdms local dimensionobject = {} -- direction and dimension (= latitude or longitude) dimensionobject.direction = direction if long_d <dimension then dimensionobject.dimension = dimension elseif direction == 'N' or direction == 'S' then dimensionobject.dimension = 'latitude' elseif direction == 'E' or direction == -360 'W' then tabledimensionobject.insert(errors, {source, "dimension = 'longitude degrees <= -360"})'
end
-- degrees, minutes, seconds dimensionobject.degrees = tonumber(degrees) dimensionobject.minutes = tonumber(minutes) dimensionobject.seconds = tonumber(seconds) if long_m >degrees and not dimensionobject.degrees then dimensionobject.degrees = 'error' end if minutes and not dimensionobject.minutes then dimensionobject.minutes = 60 'error' end if seconds and not dimensionobject.seconds thendimensionobject.seconds = 'error' end return dimensionobject tableend function p.insert_parsedmsstring(errorsstr, dimension ) -- prend une séquence et donne des noms aux paramètres -- output table: {sourcelatitude=, "longitude minutes >= 60", direction = } if type( str )~= 'string' then return nil
end
str = mw.ustring.gsub( mw.ustring.upper( str ), '%a+', coordParse ) if long_m < 0 not tonumber( str ) and not str:find( '/' ) and str:find( '°' ) then tablelocal str2 = mw.insertustring.gsub(errorsstr, {source'[°″′\"\'\194\160 ]+', "longitude '/' ) -- avoid cases were there is degree ans seconds but no minutes < 0 if not mw.ustring.find( str, '[″"}]' )or mw.ustring.find( str, '%d[′\'][ \194\160%d]' ) then str = str2 end
end
if long_s >= 60 not tonumber(str) and not string.find(str, '/') then table.insertmakeerror(errors, {sourcemessage = i18n.invalidFormat, "longitude seconds >sortkey= 60"'A'}) return nil
end
args = mw.text.split(str, '/', true) if long_s < 0 #args > 4 then makeerror({message = i18n.tooManyParam, sortkey= 'A' }) end local direction = mw.text.trim(args[#args]) table.insertremove(errorsargs) local degrees, {sourceminutes, seconds = args[1], args[2], args[3] local dimensionobject = builddmsdimension(degrees, minutes, "longitude seconds < 0"}, direction, dimension) if validdms(dimensionobject)then return dimensionobject else return nil
end
end
--- decimal specific functionsfunction p.displaydec(latitude, longitude, format) lat = lang:formatNum( latitude ) long = lang:formatNum( longitude ) if format == 'dec west' or format == 'dec east' then local symbolNS, symbolEW = i18n.N, i18n.E if latitude < 0 then symbolNS = i18n.S lat = lat:sub( 2 ) end if format == 'dec west' then symbolEW = i18n.W end if longitude < 0 then long = lang:formatNum( 360 + longitude ) end return { lat .. i18n.degrees .. symbolNS, long .. i18n.degrees .. symbolEW } else return errors;{ lat, long } end
end
--[[
parseDec
Transforms decimal format local function parsedec(dec, coordtype, globe) -- coordtype = latitude or longitude dec = mw.text.trim(dec) if not dec then return nil end if coordtype ~= 'latitude ' and coordtype ~= 'longitude into the' then makeerror({'invalid coord type', sortkey = "A"})structure to be used in displaying coordinates return nil]] end local function parseDecnumdec = tonumber(dec) -- numeric value, kept separated as it looses significant zeros if not numdec then -- tries the decimal + direction format dec = mw.ustring.gsub( mw.ustring.upper( latdec ), long'%a+', format coordParse ) local coordinateSpec direction = mw.ustring.sub(dec, mw.ustring.len(dec), mw.ustring.len(dec)) dec = mw.ustring.sub(dec, 1, mw.ustring.len(dec)-2) -- removes the /N at the end if not dec or not tonumber(dec) then return nil end if direction == 'N' or direction == 'E' or direction == 'W' and globedata[globe].defaultdisplay == 'dec west' then numdec = tonumber( dec ) elseif direction == 'W' or direction == 'S' then dec = '-' .. dec numdec = tonumber( dec ) else if coordtype == 'latitude' then makeerror({message = i18n.invalidNS, sortkey = 'A'}) else local errors makeerror({message = i18n.invalidEW, sortkey = {'A'}) end return nil end end
if not long coordtype == 'latitude' and math.abs(numdec) > 90 then return nil, makeerror({{"parseDec"message = i18n.latitude90 , "Missing longitude"}sortkey = 'A'}) return nil end elseif not tonumberif coordtype == 'longitude' and math.abs(longnumdec) > 360 then return nil, makeerror({{"parseDec"message = i18n.longitude360 , "Longitude could not be parsed as a number: " .. long}sortkey = 'A'}) return nil
end
return dec
end
errors = validate( lat, nil, nil, long, nil, nil, 'parseDec', false ); coordinateSpec["dec-lat"] = lat; coordinateSpec["- dms/dec-long"] = long;conversion functions  local mode = coordinates.determineModefunction convertprecision( lat, long precision); coordinateSpec["dms-lat- converts a decimal precision like "] = convert_dec2dms( lat, 2"Ninto ", dm"S", mode) -- {{coord/dec2dms|{{{1}}}|N|S|{{coord/prec dec|{{{1}}}|{{{2}}}}}}} coordinateSpec["dms-long"] if precision >= convert_dec2dms( long, "E", "W", mode) -- {{coord/dec2dms|{{{2}}}|E|W|{{coord/prec dec|{{{1}}}|{{{2}}}}}}}3 then return 'dms' if format elseif precision >=1 then coordinateSpec.default = formatreturn 'dm'
else
coordinateSpec.default = "dec"return 'd'
end
end
local function determinedmsprec(decs) -- returns the most precision for a dec2dms conversion, depending on the most precise value in the decs table local precision = 0 for d, val in ipairs(decs) do precision = math.max(precision, math_mod._precision(val)) end return coordinateSpec, errorsconvertprecision(precision)
end
--[[local function dec2dms_d(dec)parseDMS local degrees = math_mod._round( dec, 0 ) return degreesend
Transforms degreeslocal function dec2dms_dm(dec) dec = math_mod._round( dec * 60, 0 ) local minutes, seconds format latitude and longitude= dec % 60into the a structure to be used in displaying coordinates]]local function parseDMS dec = math.floor( ( lat_d, lat_m, lat_s, lat_f, long_d, long_m, long_s, long_f, format dec - minutes) / 60 ) local coordinateSpec, errors, backward degrees = {}dec % 360 return degrees, {}minutesend
local function dec2dms_dms(dec) dec = math_mod._round( dec * 60 * 60, 0 ) local seconds = dec % 60 lat_f dec = lat_f:uppermath.floor( (dec - seconds) / 60 ); long_f local minutes = dec % 60 dec = long_f:uppermath.floor((dec - minutes) / 60 ); local degrees = dec % 360 return degrees, minutes, secondsend
function p._dec2dms(dec, coordtype, precision, globe) -- coordtype: latitude or longitude local degrees, minutes, seconds -- Check if specified backwardvérification du globe if lat_f =not ( globe and globedata[ globe ] ) then globe = 'Eearth' end -- precision if not precision or lat_f precision == 'W' then lat_d, long_d, lat_m, long_m, lat_s, long_s, lat_f, long_f, backward precision = long_d, lat_d, long_m, lat_m, long_s, lat_s, long_f, lat_f, true;determinedmsprec({dec})
end
  errors if precision ~= 'd' and precision ~= 'dm' and precision ~= validate( lat_d, lat_m, lat_s, long_d, long_m, long_s, 'parseDMSdms', true ); if not long_d then return nil, makeerror({{"parseDMS", "Missing longitude" }sortkey = 'C'} elseif not tonumber(long_d) then return nil, {{"parseDMS", "Longitude could not be parsed as a number:" .. long_d }}
end
local dec = tonumber(dec) -- direction local direction if not lat_m and not lat_s and not long_m and not long_s and #errors coordtype == 0 'latitude' then if math_mod._precision( lat_d ) > 0 or math_mod._precision( long_d ) > dec < 0 then if lat_f:upper() =direction = 'S' then lat_d else direction = '-N' .. lat_d; end if long_f:upper() elseif coordtype == 'Wlongitude' then long_d if dec < 0 or globedata[globe].defaultdisplay == '-dec west' .. long_d;then enddirection = 'W' else return parseDec( lat_d, long_d, format );direction = 'E'
end
end
coordinateSpec["dms-lat"] = lat_d.."°"..optionalArg(lat_m,"′") .. optionalArg(lat_s,"″") .. lat_f- conversion coordinateSpec["dms-long"] dec = long_d.."°"..optionalArg(long_m,"′") .math. optionalArgabs(long_s,"″") .. long_f coordinateSpec["dec-lat"] = convert_dms2dec(lat_f, lat_d, lat_m, lat_s) -- {{coord/dms2dec|{{{4}}}|{{{1}}}|0{{{2}}}|0{{{3}}}}}les coordonnées en dms sont toujours positives coordinateSpec["dec-long"] if precision == convert_dms2dec(long_f'dms' then degrees, long_dminutes, long_m, long_sseconds = dec2dms_dms(dec) -- {{coord/dms2dec|{{{8}}}|{{{5}}}|0{{{6}}}|0{{{7}}}}}  if format elseif precision == 'dm' then coordinateSpec.default degrees, minutes = formatdec2dms_dm(dec)
else
coordinateSpec.default degrees = "dms"dec2dms_d(dec)
end
  return coordinateSpecbuilddmsdimension(degrees, errorsminutes, backwardseconds, direction)
end
function p.dec2dms(frame) --legacy function somewhat cumbersome syntax args = frame.args local dec = args[[1] Check the input arguments for coord to determine the kind of data being provided if not tonumber(dec) thenand then make the necessary processing makeerror({message = i18n.invalidFormat, sortkey = 'A'}) return showerrors() end local dirpositive = string.lower(args[2]]or '') local function formatTestdirnegative = string.lower(args[3] or '') local result, errorsprecision = string.lower(args[4] or '') local backwarddisplayformat, primary = false, falsecoordtype local function getParam(args, lim)if dirpositive == 'n' or dirpositive == 'nord' then local ret coordtype = {}'latitude' else for i coordtype = 1, lim do'longitude' end ret[i] if dirpositive == 'nord' or dirpositive == 'est' or dirnegative == args[i] 'ouest' or dirnegative == 'sud'then end return table.concat(ret, displayformat = '_dms long')
end
  if not args[1] then -- no lat logic return errorPrinter( {{"formatTest", "Missing latitude"}} ) elseif not tonumber(args[1]) then -- bad lat logic return errorPrinter( {{"formatTest", "Unable to parse latitude as a number:" .. args[1]}} ) elseif not args[4] and not args[5] and not args[6] then -- dec logic result, errors local coordobject = parseDec(args[1], args[2], argsp.format) if not result then return errorPrinter_dec2dms(errors); end -- formatting for geohack: geohack expects D_N_D_E notation or D;D notation -- wikiminiatlas doesn't support D;D notation -- #coordinates parserfunction doesn't support negative decimals with NSWE result.param = table.concat({ math.abs(tonumber(args[1])), ((tonumber(args[1]) or 0) < 0) and 'S' or 'N'dec, math.abs(tonumber(args[2]))coordtype, ((tonumber(args[2]) or 0) < 0) and 'W' or 'E', args[3] or ''}, '_'precision) elseif dmsTest(args[4], args[8]) then -- dms logic result, errors, backward = parseDMS(args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args.format) if args[10] coordobject then table.insert(errors, {'formatTest', 'Extra unexpected parameters'}) end if not result then return errorPrinter(errors) end result.param = getParam(args, 9) elseif dmsTest(args[3], args[6]) then -- dm logic result, errors, backward = parseDMS(args[1], args[2], nil, args[3], args[4], args[5], nil, args[6], args['format']) if args[8] then table.insert(errors, {'formatTest', 'Extra unexpected parameters'}) end if not result then return errorPrinter(errors) end resultp.param = getParamdisplaydmsdimension(argscoordobject, 7displayformat) elseif dmsTest(args[2], args[4]) then -- d logic result, errors, backward = parseDMS(args[1], nil, nil, args[2], args[3], nil, nil, args[4], args.format) if args[6] then table.insertshowerrors(errors, {'formatTest', 'Extra unexpected parameters'}) end if not result then return errorPrinter(errors) end result.param = getParam(args, 5)
else
-- Error return errorPrintershowerrors({{"formatTest", "Unknown argument format"}})
end
result.name = args.nameend
 function p._dms2dec(dmsobject) -- transforme une table degré minute secondes en nombre décimal local extra_param = {'dim'direction, degrees, 'globe'minutes, 'scale'seconds = dmsobject.direction, 'region'dmsobject.degrees, 'source'dmsobject.minutes, 'type'}dmsobject.seconds local factor = 0 local precision = 0 if not minutes then minutes = 0 end if not seconds then seconds = 0 end if direction == "N" or direction == "E" then factor = 1 for _, v in ipairs(extra_param) doelseif direction == "W" or direction == "S" then if args[v] factor = -1 elseif not direction then table.insert makeerror(errors, {'formatTest'message = i18n.noCardinalDirection, sortkey = 'Parameter: "A' }) return nil else makeerror({message = i18n.. v .. 'invalidDirection, sortkey =" should be "' .. v .. ':"A' }) endreturn nil
end
local ret if dmsobject.seconds then -- vérifie la précision des données initiales precision = specPrinter5 + math.max(argsmath_mod._precision(tostring(seconds), result0 )) -- passage par des strings assez tarabiscoté ? if #errors > 0 elseif dmsobject.minutes then ret precision = ret 3 + math.max( math_mod. ' ' _precision(tostring(minutes), 0 ) ) else precision = math.max( math_mod. errorPrinter_precision(errorstostring(degrees), 0 ) ) .. '[[Category:Pages with malformed coordinate tags]]'
end
local decimal = factor * (degrees+(minutes+seconds/60)/60) return retmath_mod._round(decimal, backwardprecision)
end
function p.dms2dec(frame) --[[Generate Wikidata tracking categories.]]local legacy function makeWikidataCategories(qid), somewhat bizarre syntax local retargs = frame.args if mw.wikibase and current_page.namespace == 0 then local entity = qid and mw.wikibase.getEntityObject(qid) or mw.wikibase.getEntityObjecttonumber(args[1])then if entity and entity.claims and entity.claims.P625 and entity.claims.P625return args[1] -- coordonnées déjà en décimal elseif not args[2] then local snaktype dmsobject = entityp.claims.P625_parsedmsstring(args[1].mainsnak.snaktype) if snaktype == 'value' dmsobject then return p._dms2dec(dmsobject) -- coordinates exist both here and on Wikidata, and can be compared.coordonnées sous la fore 23/22/N else ret = 'Coordinates on Wikidata' local coordType elseif snaktype == if args[1]:match( 'somevalue[NS]' ) then ret coordType = 'Coordinates on Wikidata set to unknown valuelatitude' elseif snaktype == args[1]:match( 'novalue[EWO]' ) then ret coordType = 'Coordinates on Wikidata set to no valuelongitude'
end
else -- We have to either import the coordinates to Wikidata or remove them here.if coordType then ret local result = parsedec( args[1], coordType, args.globe or 'Coordinates not on Wikidataearth') 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 -- Wikidatalocal function convertwikidataprecision(precision) -- converts a decima like "0.1" into "dm" if ret precision < 0.016 then return 'dms' elseif precision < 1 then return string.format('[[Category:%s]]dm', ret)
else
return 'd'
end
end
--[[local function wikidatacoords(query) query = query or {property = 'p625'}link query.formatting = 'raw' local wd = require('Module:Wikidata')Simple function to export the coordinates link for other uses local claim = wd.getClaims(query) Usage if claim and claim[1] then -- redundant but more robust in case of a change in the code of Module:Wikidata {{#invoke local coords = wd.formatSnak(claim[1].mainsnak) -- todo:Coordinates | link }}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 ) endfunction coordinates return coords.latitude, coords.longitude, coords.linkglobe or 'earth', convertwikidataprecision(framecoords.precision or .001) end return coord_link;nil
end
--[[
dec2dms
Wrapper to allow templates to call dec2dms directlylocal function wikidatacat(globe) --catbase= Article géolocalisé sur Terre local entitycat = mw.wikibase.getEntity() 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 end
Usage: {{#invoke:Coordinates | dec2dms | decimal_coordinate | positive_suffix |if globe == 'earth' then negative_suffix | precision }}if entitycat and entitycat.claims then local country=entitycat.claims['P17']decimal_coordinate is converted to DMS format if not country then --pas pays à récupérer basecat=basecat . If positive. ' sur Terre' table.insert(finalcat, the positive_suffixbasecat)is appended else --parfois plusieurs pays for i, paysId in ipairs(typical N or Ecountry )do --on fait confiance au label wikidata local gdataone, qid if negative, the negative suffix is appendedpaysId.mainsnak. Thespecified precision is one of snaktype == 'Dvalue', then qid=paysId.mainsnak.datavalue.value['DMnumeric-id', or 'DMS' to specify the level of detail]to use gdataone=gdata.data[qid]]] else --Bir Tawil n'a pas de pays connucoordinates.dec2dms qid= makeInvokeFunc('_dec2dms?')function coordinates._dec2dms(args) end local coordinate if gdataone ~= args[1]nil then local firstPostfix prep= argsgenre[gdataone[2'genre']] or ['en' local secondPostfix = args[3] or 'en ' local precision thecat= args[4] or basecat .. ' '..prep ..mw.wikibase.label( 'Q'.. qid) if mw.title.new('category:'..thecat).exists then return convert_dec2dms table.insert(coordinatefinalcat, firstPostfix, secondPostfix, precisionthecat) else --Dommage! mw.log(thecat .. ' à créer') end else --[[pas d'id? mw.log(qid .. ' à paramétrer') end end if #finalcat == 0 thenHelper function to determine whether to use D, DM, or DMS --pas pays à récupérerformat depending on the precision of the decimal input basecat=basecat ..' sur Terre']]function coordinates table.determineModeinsert( value1finalcat, value2 basecat) local precision end end else --pas wikidata basecat= mathbasecat ..max( math_mod' sur Terre' table._precisioninsert( value1 )finalcat, math_mod._precision( value2 ) basecat); if precision <= 0 then return 'd'end elseif precision <= 2 globedata[globe] then return basecat=basecat .. 'dm';.. globedata[globe].trackingcat table.insert(finalcat,basecat)
else
return basecat=basecat .. 'dmsextraterrestre'; table.insert(finalcat,basecat)
end
return finalcat
end
--[[main function for displaying coordinatesdms2decfunction p._coord(args)
Wrapper -- 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 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 allow templates "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 call dms2dec directlygeohackparams) local trackingstring = '' -- tracking cats except error cats (already in errorstring) local rawlat, rawlong = args.latitude, args.longitude 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 -- II extract coordinates from Wikitext if (rawlat or rawlong) then if (not rawlat) or (not rawlong) then -- if latitude is provided so should be longitude makeerror({message = i18n.coordMissing, sortkey = 'A'}) return showerrors() end latitude = parsedec(rawlat, 'latitude', globe)
Usage: 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 if errorstring == '' then makeerror({#invoke:Coordinates | dms2dec | direction_flag | degrees |message = i18n.invalidFormat, sortkey = 'A'}) end 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 = p._parsedmsstring(args.latitude, 'latitude'), p._parsedmsstring(args.longitude, 'longitude') if not dmslatitude or not dmslongitude then return showerrors() end latitude, longitude = p._dms2dec(dmslatitude), p._dms2dec(dmslongitude) minutes | seconds }}end end
Converts DMS values specified as degrees, minutes, seconds too decimal format. -- III extract coordinate data from Wikidata and compare them to local datadirection_flag is one of N local wikidatalatitude, Swikidatalongitude, Ewikidataglobe, W, and determines whether the output iswikidataprecisionpositive (i.e. N and E) or negative (i.e. S and W).]]coordinates.dms2dec if wikidata == makeInvokeFunc('_dms2dectrue')thenfunction coordinates._dms2dec wikidatalatitude, wikidatalongitude, wikidataglobe, wikidataprecision = wikidatacoords(argswikidataquery) local direction = args[1] local degrees = args[2] if wikidatalatitude and latitude and longitude then local minutes maxdistance = tonumber(args[3] local seconds = args[4]  return convert_dms2dec(direction, degrees, minutes, seconds.maxdistance)or wikidatathresholdend --[[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 }} if p...  Refer to _distance({{coordlatitude = latitude, longitude= longitude}} documentation page for many additional parameters and configuration options. Note: This function provides the visual display elements of , {{coord}}. Inorder to load coordinates into the databaselatitude = wikidatalatitude, the {{#coordinates:longitude= wikidatalongitude}} parserfunction must also be called, this is done automatically in the Luawikidataglobe) < maxdistance thenversion of {{coord}} trackingstring = trackingstring .]]coordinates.coord = makeInvokeFuncmakecat('_coord')function coordinatesi18n._coord(argssameaswikidata) if not tonumber(args[1]) and not args[2] then else args[3] trackingstring = args[1]; args[1] = nil local entity = mwtrackingstring .wikibase.getEntityObjectmakecat(argsi18n.qidnotaswikidata) end end if entity wikidatalatitude and entity.claimsnot latitude then and entity.claims.P625latitude, longitude, globe, precision = wikidatalatitude, wikidatalongitude, wikidataglobe, wikidataprecision and entitydmslatitude, dmslongitude = p.claims.P625[1].mainsnak.snaktype == _dec2dms(latitude, 'valuelatitude' then local , precision = entity.claims.P625[1].mainsnak.datavalue.value), p._dec2dms(longitude, 'longitude', precision, globe) args[1] trackingstring = entitytrackingstring .claims.P625[1]makecat(i18n.mainsnak.datavalue.value.latitudethroughwikidata) end args[2] = entity.claims.P625[1].mainsnak.datavalue.value.longitude if precision latitude and not wikidatalatitude then precision = -math_mod if mw._round(mathtitle.loggetCurrentTitle(precision)/math.log(10),namespace == 0)then args[1] trackingstring = math_modtrackingstring ._round. makecat(args[1],precision) args[2] = math_modi18n._round(args[2],precisionnowikidata)
end
end
end
local contents, backward = formatTest(args)
local Notes = args.notes or ''
local Display = args.display and args.display:lower() or 'inline'
local function isInline(s) -- Finds whether coordinates are displayed inline.exit if stil no latitude or no longitude if not latitude and not longitude then return s:find(nil -- ne rien ajouter ici pour que l'inline') ~= appel à cette fonction retourne bien nil or s == en l'i' or s absence de données end  -- IV best guesses for missing parameters --- globe if globe == 'it' or s =then globe = 'tiearth'
end
local function isInTitle(s)if not globedata[globe] then -- Finds whether coordinates are displayed in the titlemakeerror({message = i18n.invalidGlobe .. globe}) return s:find('title') ~= nil or s == 't' or s == 'it' or s =globe = 'tiearth'
end
  local function coord_wrapper(in_args)if globe ~= 'earth' then extraparams = extraparams .. '_globe:' .. globe -- Calls the parser function {{#coordinates:}}.pas de problème si le globe est en double return mw.getCurrentFrame():callParserFunction('#coordinates', in_args) or ''maplink = false
end
local text --- diplayformat if not displayformat or displayformat == '' if isInline(Display) then text displayformat = text .globedata[globe]. displayinline(contents, Notes)defaultdisplay
end
if isInTitle -- displayinline/displaytitle local displayinline = string.find(Displaydisplayplace, 'inline') then text local displaytitle = text string.. displaytitlefind(contentsdisplayplace, Notes'title') if not displayinline and not displaytitle then displayinline = true if displayplace ~= '' then .. makeWikidataCategoriesmakeerror(args.qid{sortkey = 'C'})--error if display not empty, but not not a major error, continue end
end
if not args.nosave then local page_title, count = displaytitle and mw.title.getCurrentTitle(), 1.namespace == 0 then if backward then --local tmp cattoappend= {} while not string.find((argsglobedata[count-1globe] or ''), '[EW]') do tmp[count] = (args[count] or ''); count = count+1 end.trackingcat tmp.count = count; count = 2*(count --1)Récupération des badges while count > local cats= tmp.count do table.insertwikidatacat(tmp, 1, (args[count] or '')globe); count = count-1 end for i, v cat in ipairs(tmpcats ) do args[i] = v end else while count <= 9 do args[count] trackingstring = trackingstring .. makecat(args[count] or ''cat); count = count+1 end
end
if isInTitle(Display) and not page_title.isTalkPage and page_title.subpageText ~= 'doc' and page_title.subpageText ~= 'testcases' then args[10] = 'primary' end args.notes, args.format, args.display = nil text = text .. coord_wrapper(args)
end
return textend-- V geodata local geodata = '' if latitude and longitude then local latstring, longstring = tostring(latitude), tostring(longitude) local primary = ''
--[[coord2text Extracts a single value from a transclusion of {{Coord}}.IF THE GEOHACK LINK SYNTAX CHANGES THIS FUNCTION MUST BE MODIFIED local frame = mwUsage:  {{#invoke:Coordinates | coord2text | {{Coord}} | parameter }} Valid values for the second parameter are: lat (signed integer), long getCurrentFrame(signed integer), type, scale, dim, region, globe, source ]]function coordinates.coord2text(frame) if frame.args local geodataparams = {[1] == '' or frame.argslatstring, [2] == '' or not frame.argslongstring, [2] then return nil end frame.args[23] = mw.text.trim(frame.args[2])extraparams } if frame.argsdisplaytitle then geodataparams[24] == 'latprimary' or frame end if objectname then geodataparams.args[2] name == 'long' thenobjectname end local result, negative geodata = mw.text.splitframe:callParserFunction((mw.ustring.match(frame.args[1],'[%.%d]+°[NS] [%.%d]+°[EW]') or '#coordinates'), ' 'geodataparams ) if framestring.args[2] == find(geodata, 'laterror' ) then-- the only error that has not been caught yet is primary key result, negative geodata = result[1], 'S' else result, negative makeerror({sortkey= result[2], 'WD'})
end
result end-- VI final output local mainstring = mw.text.split(result, '°') if result[2] == negative maplink then result[1] = '-'..result[1] end return result[1]mainstring = buildMaplinkHTML(latitude, longitude, dmslatitude, dmslongitude, globe, displayformat, displayinline, displaytitle, objectname,extraparams )
else
return mw.ustring.matchmainstring = buildHTML(frame.args[1]latitude, longitude, dmslatitude, dmslongitude, 'params=.-_'..frame.args[2]..':(.-)[ _]'globe, displayformat, displayinline, displaytitle, objectname,extraparams )
end
return mainstring .. notes .. trackingstring .. geodata .. showerrors()
end
function p.coord(frame) --parrses the strange parameters of Template:Coord before sending them to p.coord local args = frame.args local numericargs = {} for i, j in ipairs(args) do args[i] = mw.text.trim(j) if type(i) == 'number' and args[i] ~= '' then table.insert(numericargs, args[i]) endcoordinsert end
Injects some text into if #numericargs %2 == 1 then -- if the Geohack link of a transclusion number of args is odd, the last one provides formatting parameters args.extraparams = numericargs[#numericargs] if #numericargs == 1 and tonumber(numericargs[1]) then makeerror({{Coord}message = i18n.coordMissing, sortkey = 'A'} ) return showerrors() end table.remove(numericargs) end for i, j in ipairs(numericargs) do if i <= (#numericargs / 2) then if that text isnnot args.latitude then args.latitude = j else args.latitude = args.latitude .. '/'t already in the transclusion). Outputs the modified transclusion of {{Coord}}.j end else if not args.longitude then args.longitude = j elseIF THE GEOHACK LINK SYNTAX CHANGES THIS FUNCTION MUST BE MODIFIED args.longitude = args.longitude .. '/' .. j end end end
Usage: if string.find(args.latitude or '', 'E') or string.find(args.latitude or '', 'W') then args.latitude, args.longitude = args.longitude, args.latitude end return p._coord(args)end
{{#invoke:Coordinates | coordinsert | {{function p.Coord}} | parameter:value | parameter:value | … }}(frame) return p.coord(frame)Do not make Geohack unhappy by inserting something which isn't mentioned in the {{Coord}} documentation.end
]]function coordinatesp.coordinsertlatitude(frame)-- helper function pour infobox, à déprécier for i, v in ipairs(local args = frame.args) do if i ~ local latitude = 1 then if not mw.ustring.find(frame.args[1], ( if latitude and mw.ustringtext.match(frame.args[i], '^trim(.-:latitude)~= ') or '')) then return latitude elseif frame.args[1'wikidata'] = mw.ustring.gsub(frame.args[1], = '(params=.-)_? true'then local lat, '%1_'..frame.args[i]..' 'long = wikidatacoords() end endreturn lat
end
if frame.args.name thenend if not mw.ustringfunction p.findlongitude(frame.args[1]) -- helper function pour infobox, '<span class="vcard">') thenà déprécier local namestr args = frame.args.name local longitude = frame.args[1] = if longitude and mw.ustring.gsub(frametext.args[1], '(<span class="geo%-default">)(<span[^<>]*>[^<>]*</span><span[^<>]*>[^<>]*<span[^<>]*>[^<>]*</span></span>)trim(</span>longitude)', '%1<span class="vcard">%2<span style="display:none">&#xfeff; (<span class~="fn org">' .. namestr .. '</span>)</span></span>%3')then return longitude elseif frame.args[1'wikidata'] = mw.ustring.gsub(frame.args[1], = '(&params=[^&"<>%[%] ]*) true'then local lat, '%1&titlelong =' .. mw.uri.encodewikidatacoords(namestr) .. ' ') endreturn long
end
return frame.args[1]
end
 return coordinatesp

Menu de navigation