Ouvrir le menu principal

Modifications

14 645 octets supprimés ,  2 juillet 2020 à 19:43
Recopie du code de https://en.wikipedia.org/w/index.php?title=Module:Coordinates&action=edit
local math_mod = require( "Module:Math" )--[[This module is intended to replace the functionality of {{Coord}} and relatedtemplates. It provides several methods, including
local p = {{#invoke:Coordinates | coord }}: General function formatting and displayingcoordinate values.
--Chargement de la liste En/Au/Aux/Alocal gdata{{#invoke:Coordinates | dec2dms }} : Simple function for converting decimallocal success, resultat = pcall (mwdegree values to DMS format.loadData, "Module:Drapeau/Data" )if success then gdata = resultat{{#invoke:Coordinates | dms2dec }} : Simple function for converting DMS formatelseto decimal degree format. -- Banque de données à minima en cas de bogue dans le Module:Langue/Data gdata={{#invoke:Coordinates | link }} : Export the link used to reach the tools gdata.data={}; gdata.data[142]={qid="Q142", label="France", genre="fs"}] endrequire('Module:No globals')
local i18n math_mod = { N = 'N', Nlong = 'nord', W = 'O', Wlong = 'ouest', E = 'E', Elong = 'est', S = 'S', Slong = 'sud', degrees = '° ', minutes = '′ ', seconds = '″ ', geohackurl = 'http://tools.wmflabs.org/geohack/geohack.php?language=fr', tooltip = 'Cartes, vues aériennes, 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 require(should be N or S)', invalidEW = 'orientation de longitude invalide, devrait être "E" ou "WModule:Math"', -- '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 local 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 current_page = {mw.title.getCurrentTitle() ms = {le="le ", du="du ", de="du ", au="au ", en="au "}, msa = {le="l'", dulocal page_name ="de l'"mw.uri.encode( current_page.prefixedText, de="d'", au="à lWIKI'", 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'", delocal coord_link ="d'", au//tools.wmflabs.org/geohack/geohack.php?pagename="à l'", en="en "}, fsi = {le="", du="de ", de="de ", au="à ", en="à "}, fsia = {le="", du="d.. page_name .. '", de&params="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 "}}
local globedata = { --[[ notes: radius in kilometers (especially imprecise Helper function, replacement 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'coord/display/title}, ceres = {radius = 470, defaultdisplay = 'dec east', trackingcat = 'extraterrestre'},]] charon = {radius = 1214, defaultdisplay = 'dec east', trackingcat = 'extraterrestre'}local function displaytitle(s,notes) deimos local l = {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'Geographic coordinate system|Coordinates]] = {radius = 1322, defaultdisplay = 'dec west', trackingcat = 'extraterrestre'},: " .. s jupiter local co = {radius = 68911, defaultdisplay = 'dec east', trackingcat <span id= "coordinates">'extraterrestre'}, mars = {radius = 3389.5, defaultdisplay = 'dec east', trackingcat = 'sur Mars' }, mercury = {radius = 2439.7, defaultdisplay = 'dec west', trackingcat = l .. notes .. 'sur Mercure</span>'},; mimas = {radius = 197, defaultdisplay = return 'dec west', trackingcat <span style= "font-size: small;">'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 = co .. 'dec east</span>', trackingcat = 'sur Vénus'},; vesta = {radius = 260, defaultdisplay = 'dec east', trackingcat = 'extraterrestre'}}globedata[''] = globedata.earthend
local wikidatathreshold = 10 -- si la distance entre coordonnées Wikipédia et Wikidata dépasse se seuil [[ Helper function, Replacement for {{coord/display/inline}} ]]local function displayinline(en kilomètess, notes), une catégorie de maintenance est ajoutéelocal lang = mw return s .language.getContentLanguage()noteslocal default_zoom = 13end
--[[ Helper function, used in detecting DMS formatting ]]local function makecatdmsTest(catfirst, sortkeysecond) if type( sortkey first) ~='string' or type(second) ~= 'string' then return '[[Category:' .. cat .. '|' .. sortkey .. ']]' else return '[[Category:' .. cat .. ']]'nil
end
local s = (first .. second):upper()
return s:find('^[NS][EW]$') or s:find('^[EW][NS]$')
end
----------------------------------------
--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
* D: more than one primary coord
]]--
 
local errorstring = ''
--[[ Wrapper function to grab args, see Module:Arguments for this function's documentation. ]]local function makeerrormakeInvokeFunc(argsfuncName) return function (frame) local errormessage = '' if args.message then errormessage = require('<strong class="error"> Coordonnées Module: Arguments' ).. args.message .. '</strong>' endgetArgs(frame, { local errorcat wrappers = 'Template:Coord' if mw.title.getCurrentTitle( }).namespace == 0 then errorcat = makecatreturn coordinates[funcName](i18n.errorcatargs, args.sortkeyframe)
end
errorstring = errormessage .. errorcat -- reinitializes the string to avoid absurdly long messages
return nil
end
--[[ Helper function, handle optional args. ]]local function showerrorsoptionalArg(arg, supplement) return errorstringarg and arg .. supplement or ''
end
--[[
Formats any error messages generated for display
]]
local function errorPrinter(errors)
local result = ""
for i,v in ipairs(errors) do
local errorHTML = '<strong class="error">Coordinates: ' .. v[2] .. '</strong>'
result = result .. errorHTML .. "<br />"
end
return result
end
--[[
Determine the required CSS class to display coordinates
Usually geo-- Distance computationnondefault is hidden by CSS, unless a user has overridden this for himselfdefault is the mode as specificied by the user when calling the {{coord}} templatemode is the display mode (dec or dms) that we will need to determine the css class for]]local function p._distancedisplayDefault(adefault, b, globemode) -- calcule la [[distance orthodromique]] en kilomètres entre deux points du globe if default == "" then default = "dec" end
globe if default = string.lower(globe or 'earth')= mode then return "geo-- check arguments and converts degreees to radiansdefault" local latA, latB, longA, longB = a.latitude, b.latitude, a.longitude, b.longitudeelse if (not latA) or (not latB) or (not longA) or (not longB) then return error('coordinates missing, can\'t compute distance')"geo-nondefault"
end
if type(latA) ~= 'number' end --[[specPrinter Output formatter. Takes the structure generated by either parseDecor typeparseDMS and formats it for inclusion on Wikipedia.]]local function specPrinter(latBargs, coordinateSpec) ~ local uriComponents = 'number' or type(longA) ~coordinateSpec["param"] if uriComponents = 'number' or type(longB) ~= 'number' "" then -- RETURN error('coordinates are not numeric, can\'t compute distance') end if not globe should never be empty or not globedata[globe] thennil return error('globe: ' .. globe .. 'is not supported')"ERROR param was empty"
end
if args["name"] then -- calcul de la distance angulaire en radians local convratio uriComponents = mathuriComponents .pi / 180 -- convertit en radians latA, latB, longA, longB = convratio * latA, convratio * latB, convratio * longA, convratio * longB local cosangle . "&title= math" .sin(latA) * math.sin(latB) + mathmw.cos(latA) * math.cos(latB) * mathuri.cosencode(longB - longAcoordinateSpec["name"]) 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
function p.distance(frame) local args geodmshtml = '<span class="geo-dms" title= frame"Maps, aerial photos, and other data for this location">' .args return p._distance( {'<span class="latitude = tonumber(args">' .. coordinateSpec["dms-lat"] .latitude1), longitude = tonumber(args.longitude1)}, '</span> ' {latitude .. '<span class= tonumber(args"longitude">' ..coordinateSpec["dms-long"] .latitude2), longitude = tonumber(args.longitude2)},'</span>' args .globe)end. '</span>'
local function geoHackUrllat = tonumber(decLat, decLong, globe, displayformat, objectname, extraparamscoordinateSpec["dec-lat"] ) extraparams = extraparams or ''0 local geohacklatitude, geohacklongitude -- format latitude and longitude for the URLgeodeclat if tonumber(decLat) lat < 0 then geohacklatitude -- FIXME this breaks the pre-existing precision geodeclat = tostring(coordinateSpec["dec-tonumberlat"]):sub(decLat)2) .. '_S'"°S" else geohacklatitude geodeclat = decLat (coordinateSpec["dec-lat"] or 0) .. '_N'"°N"
end
  if local long = tonumber(decLongcoordinateSpec["dec-long"] ) or 0 local geodeclong if long < 0 then geohacklongitude -- FIXME does not handle unicode minus geodeclong = tostring(coordinateSpec["dec-tonumberlong"]):sub(decLong2)) .. '_W' elseif globedata[globe].defaultdisplay == 'dec west' then geohacklongitude = decLong .. '_W'"°W"
else
geohacklongitude geodeclong = decLong (coordinateSpec["dec-long"] or 0) .. '_E'"°E"
end
-- prepares the 'paramss=' parameter
local geohackparams = geohacklatitude .. '_' .. geohacklongitude .. '_' ..extraparams
-- concatenate parameteres for geohack
return i18n.geohackurl ..
"&pagename=" .. mw.uri.encode(mw.title.getCurrentTitle().prefixedText, "WIKI") ..
"&params=" .. geohackparams ..
(objectname and ("&title=" .. mw.uri.encode(objectname)) or "")
end
local geodechtml = '<span class="geo--HTML builder dec" title="Maps, aerial photos, and other data for a geohack linkthis location">' .. geodeclat .. ' ' .. geodeclong .. '</span>'  local function buildHTML(decLat, decLong, dmsLat, dmsLong, globe, displayformat, displayinline, displaytitle, objectname, extraparams)geonumhtml = '<span class="geo">' .. coordinateSpec["dec-lat"] .. '; ' .. coordinateSpec["dec- geohack urllong"] .. '</span>'  local url inner = '<span class= geoHackUrl"' .. displayDefault(decLat, decLong, globe, displayformat, objectnamecoordinateSpec["default"], extraparams"dms" ).. '">' .. geodmshtml .. '</span>' .. '<span class="geo-multi- displayed coordinatespunct">&#xfeff; / &#xfeff;</span>' local displaycoords if string .. '<span class="' ..subdisplayDefault(displayformatcoordinateSpec["default"],1,3"dec" ) == .. 'dec">' ;  if not args["name"] then displaycoords inner = pinner ..displaydec(decLat, decLong, displayformat)geodechtml .. '<span style="display:none">&#xfeff; / ' .. geonumhtml .. '</span></span>'
else
displaycoords inner = {inner .. '<span class="vcard">' .. geodechtml .. '<span style="display:none">&#xfeff; / ' .. geonumhtml .. '</span>' p ..displaydmsdimension'<span style="display:none">&#xfeff; (dmsLat, displayformat),<span class="fn org">' p .displaydmsdimension(dmsLong, displayformat. args["name"] .. '</span>), }</span></span></span>'
end
-- build coordinate in h-geo / h-card microformat local globeNode if globe and globe ~return '<span class= "plainlinks nourlexpansion">'earth' then.. globeNode = mw'[' .. coord_link .. uriComponents .html.create('data') :addClass('p-globe') :attr{ value = globe } :done() end local coordNode = mw.html.create(inner .. ']') if objectname then coordNode = mw.html.create('</span>') :addClass('h-card') :tag('data') :addClass('p-name') :attr{ value = objectname } :done() end coordNode :tag('span') :addClass('h-geo') :addClass('geo-' .. string.sub(displayformat,1[[ Helper function,3)) :tag('data') :addClass('p-latitude') :attr{ value = decLat } :wikitext( displaycoords[1convert decimal to degrees ] ) :done() :wikitext(", ") :tag('data') :addClass('p-longitude') :attr{ value = decLong } :wikitext( displaycoords[2] ) :donelocal function convert_dec2dms_d(coordinate) :node( globeNode ) :done() -- buid GeoHack link local root d = mwmath_mod.html.create_round('span'coordinate, 0 ) :addClass('plainlinks nourlexpansion') :attr('title', i18n.tooltip). "°" :wikitext('[' return d .. url ) :node(coordNode) :wikitext("]") :done()end -- format result depending on args["display"[ Helper function, convert decimal to degrees and minutes ]] local function convert_dec2dms_dm(nil, "inline", "title", "inline,title"coordinate) local inlineText coordinate = displayinline and tostringmath_mod._round(rootcoordinate * 60, 0 ) or ''; local titleText m = ''coordinate % 60; if displaytitle then local htmlTitle coordinate = mw.htmlmath.createfloor('span') :attr{ id = 'coordinates' } :addClass( displayinline and 'noprint' or nil coordinate - m) :node( root / 60 ); local frame d = mwcoordinate % 360 .getCurrentFrame() titleText = frame:extensionTag( 'indicator', tostring(htmlTitle), { name = 'coordinates' } )."°" end return inlineText d .. titleTextstring.format( "%02d′", m )
end
--[[ Helper function, convert decimal to degrees, minutes, and seconds ]]local function zoomconvert_dec2dms_dms( extraparams coordinate) local zoomParam coordinate = extraparams:matchmath_mod._round( '%f[%w]zoom: ?(%d+)' coordinate * 60 * 60, 0 ) if zoomParam then return zoomParam end ; local scale s = extraparams:match( '%f[%w]scale: ?(coordinate %d+)' )60 if scale then return coordinate = math.floor(math.log10( 1 coordinate - s) / tonumber( scale ) ) * 3 + 2560 ); end local m = coordinate % 60 local extraType coordinate = extraparams:matchmath.floor( '%f[%w]type: ?(%w+coordinate - m)' / 60 ); if extraType then local zoomType d = {coordinate % 360 .."°" country = 5, state = 6 return d .. string.format( "%02d′", adm1st = 7m ) .. string.format( "%02d″", adm2nd = 8, city = 9, isle = 10, mountain = 10, waterbody = 10, airport = 12, landmark = 13, } return zoomType[ extraType ] ends )
end
--HTML builder for a geohack link[[local Helper function buildMaplinkHTML( decLat, decLongconvert decimal latitude or longitude todegrees, dmsLatminutes, dmsLong, globeand seconds format based on the specified precision.]]local function convert_dec2dms(coordinate, displayformatfirstPostfix, displayinlinesecondPostfix, displaytitle, objectname, extraparams precision) -- displayed coordinateslocal coord = tonumber(coordinate) local displaycoordspostfix if string.sub(displayformat,1,3) coord >== 'dec' 0 then displaycoords postfix = p.displaydec(decLat, decLong, displayformat)firstPostfix
else
displaycoords postfix = { 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 } } }secondPostfix
end
local maplink precision = mw.getCurrentFrameprecision:lower():extensionTag{; name if precision == 'maplink',"dms" then content = mwreturn convert_dec2dms_dms( math.text.jsonEncodeabs( jsonParams coord ) ), args = { text = displaycoords[1] .. ", " .. displaycoords[2],postfix; zoom elseif precision = zoom( extraparams ) or default_zoom, latitude = decLat, longitude = decLong, } } -- format result depending on args["display"] (nil, "inline", "title", dm"inline,title") local inlineText = displayinline and maplink or '' local titleText = '' if displaytitle then local htmlTitle = mwreturn convert_dec2dms_dm( math.html.createabs('span'coord ) ).. postfix; :attr{ id elseif precision = 'coordinates' } :addClass( displayinline and 'noprint' or nil ) :wikitext( maplink ) local frame = mw.getCurrentFrame()"d" then titleText = frame:extensionTagreturn convert_dec2dms_d( 'indicator', tostringmath.abs(htmlTitlecoord ), { name = 'coordinates' } ).. postfix;
end
return inlineText .. titleText
end
-- dms specific funcions[[Convert DMS format into a N or E decimal coordinate]]local function convert_dms2dec(direction, degrees_str, minutes_str, seconds_str) local degrees = tonumber(degrees_str) local minutes = tonumber(minutes_str) or 0 local seconds = tonumber(seconds_str) or 0  local factor = 1 if direction == "S" or direction == "W" then factor = -1 end
local function twoDigit( value )precision = 0 if seconds_str then precision = 5 + math.max( math_mod._precision( value < 10 seconds_str) , 0 ); elseif minutes_str and minutes_str ~= '' then value precision = '0' 3 + math.max( math_mod. lang:formatNum_precision( value minutes_str), 0 );
else
value precision = lang:formatNummath.max( value math_mod._precision(degrees_str), 0 );
end
  local decimal = factor * (degrees+(minutes+seconds/60)/60) return valuestring.format( "%." .. precision .. "f", decimal ) -- not tonumber since this whole thing is string based.
end
--[[Checks input values to for out of range errors.]]local function p.displaydmsdimensionvalidate(valuetablelat_d, lat_m, lat_s, formatlong_d, long_m, long_s, source, strong ) -- formate en latitude ou une longitude dms local str errors = {}; lat_d = tonumber( lat_d ) or 0; lat_m = tonumber( lat_m ) or 0; lat_s = ''tonumber( lat_s ) or 0; local direction long_d = valuetable.directiontonumber( long_d ) or 0; local degrees, minutes, seconds long_m = '', '', ''tonumber( long_m ) or 0; local dimensionlong_s = tonumber( long_s ) or 0;
if format == 'dms long' strong then direction = i18n[direction .if lat_d < 0 then table. 'long'] else direction = i18n[direction] end degrees = lang:formatNuminsert( valuetable.errors, {source, "latitude degrees < 0 with hemisphere flag"}) .. i18n.degrees end if valuetable.minutes long_d < 0 then minutes = twoDigit table.insert( valuetable.minutes errors, {source, "longitude degrees < 0 with hemisphere flag"}) .. i18n.minutes end if valuetable --[[ #coordinates is inconsistent about whether this is an error.seconds then If globe: is seconds = twoDigit( valuetablespecified, it won't error on this condition, but otherwise it will.seconds ) .. i18n.seconds end return degrees .. minutes . For not simply disable this check. seconds .. directionend
local function validdms(coordtable) local direction = coordtable.direction local degrees = coordtable.degrees or 0 local minutes = coordtable.minutes or 0 local seconds = coordtable.seconds or 0 local dimension = coordtable.dimension if not dimension then if direction == 'N' or direction == 'S' long_d > 180 then dimension = 'latitude' elseif direction == 'E' or direction == 'W' then dimension = 'longitude' else makeerrortable.insert(errors, {message = i18n.invalidNSEWsource, sortkey = 'A'"longitude degrees > 180 with hemisphere flag"}) return false
end
]]
end
if type(degrees) ~= 'number' or type(minutes) ~= 'number' or type(seconds) ~= 'number' lat_d > 90 then makeerrortable.insert(errors, {message = i18n.invalidFormatsource, sortkey = 'A'"latitude degrees > 90"}) return false
end
if dimension == 'latitude' and direction ~= 'N' and direction ~= 'S' lat_d < -90 then makeerrortable.insert(errors, {message = i18n.invalidNSsource, sortkey = 'A'"latitude degrees < -90"}) return false
end
if dimension lat_m >== 'longitude' and direction ~= 'W' and direction ~= 'E' 60 then makeerrortable.insert(errors, {message = i18n.invalidEWsource, sortkey "latitude minutes >= 'A'60"}) return false
end
if dimension == 'latitude' and degrees > 90 lat_m < 0 then makeerrortable.insert(errors, {message = i18n.latitude90source, sortkey = 'A'"latitude minutes < 0"}) return false
end
if dimension =lat_s >= 'longitude' and degrees > 360 60 then makeerrortable.insert(errors, {message = i18n.longitude360source, sortkey "latitude seconds >= 'A'60"}) return false
end
if degrees < 0 or minutes < 0 or seconds lat_s < 0 then makeerrortable.insert(errors, {message = i18n.negativeCoodesource, sortkey = 'A'"latitude seconds < 0"}) return false
end
if minutes long_d > 60 or seconds > 60 = 360 then makeerrortable.insert(errors, {message = i18n.minSec60source, sortkey = 'A'}) return false end if (math.floor("longitude degrees) ~>= degrees and minutes ~= 0) or (math.floor(minutes) ~= minutes and seconds ~= 0) then makeerror({message = i18n.dmIntergers, sortkey = 'A'360"}) return false
end
return trueif long_d <= -360 thenend local function builddmsdimension table.insert(degreeserrors, minutes{source, seconds, direction, dimension) -"longitude degrees <= - no error checking, done in function validdms local dimensionobject = {360"} -- direction and dimension (= latitude or longitude) dimensionobject.direction = direction if dimension then dimensionobject.dimension = dimension elseif direction == 'N' or direction == 'S' then dimensionobject.dimension = 'latitude' elseif direction == 'E' or direction == 'W' then dimensionobject.dimension = 'longitude'
end
-- degrees, minutes, seconds dimensionobject.degrees = tonumber(degrees) dimensionobject.minutes = tonumber(minutes) dimensionobject.seconds = tonumber(seconds) if degrees and not dimensionobject.degrees then dimensionobject.degrees = 'error' end if minutes and not dimensionobject.minutes then dimensionobject.minutes long_m >= 'error' end if seconds and not dimensionobject.seconds 60 then dimensionobject.seconds = 'error' end return dimensionobjectend function p table._parsedmsstringinsert( strerrors, dimension ) -- prend une séquence et donne des noms aux paramètres -- output table: { latitude=source, "longitude minutes >= , direction = 60"} if type( str ) ~= 'string' then return nil
end
str = mw.ustring.gsub( mw.ustring.upper( str ), '%a+', coordParse ) if not tonumber( str ) and not str:find( '/' ) and str:find( '°' ) long_m < 0 then local str2 = mwtable.ustring.gsubinsert( strerrors, {source, '[°″′\"\'\194\160 ]+', '/' ) -- avoid cases were there is degree ans seconds but no longitude minutes if not mw.ustring.find( str, '[″< 0"]' }) or mw.ustring.find( str, '%d[′\'][ \194\160%d]' ) then str = str2 end
end
if not tonumber(str) and not string.find(str, '/') long_s >= 60 then makeerrortable.insert(errors, {message = i18n.invalidFormatsource, sortkey"longitude seconds >= 'A'60"}) return nil
end
args = mw.text.split(str, '/', true) if #args > 4 long_s < 0 then makeerror({message = i18n.tooManyParam, sortkey= 'A' }) end local direction = mw.text.trim(args[#args]) table.removeinsert(args) local degreeserrors, minutes{source, "longitude seconds = args[1], args[2], args[3] local dimensionobject = builddmsdimension(degrees, minutes, seconds, direction, dimension< 0"}) if validdms(dimensionobject) then return dimensionobject else return nil
end
 
return errors;
end
--- [[parseDec Transforms decimal specific functionsformat latitude and longitude into thestructure to be used in displaying coordinates]]local function p.displaydecparseDec(latitudelat, longitudelong, format) lat local coordinateSpec = lang:formatNum( latitude ){} long local errors = lang:formatNum( longitude ){} if format == 'dec west' or format == 'dec east' not long then local symbolNSreturn nil, symbolEW = i18n.N{{"parseDec", i18n.E"Missing longitude"}} if latitude < 0 elseif not tonumber(long) then symbolNS = i18n return nil, {{"parseDec", "Longitude could not be parsed as a number: " ..Slong}} lat = lat:sub( 2 ) end end if format = errors = validate( lat, nil, nil, long, nil, nil, 'dec westparseDec' then, false ); symbolEW coordinateSpec["dec-lat"] = i18n.Wlat; end coordinateSpec["dec-long"] = long; if longitude < 0 then long local mode = lang:formatNumcoordinates.determineMode( 360 + longitude lat, long ); end return { coordinateSpec["dms-lat"] = convert_dec2dms( lat .. i18n.degrees .. symbolNS, "N", "S", mode) -- {{coord/dec2dms|{{{1}}}|N|S|{{coord/prec dec|{{{1}}}|{{{2}}}}}}} coordinateSpec["dms-long .. "] = convert_dec2dms( long, "E", "W", mode) i18n.degrees .. symbolEW -- {{coord/dec2dms|{{{2}}}|E|W|{{coord/prec dec|{{{1}}}|{{{2}}}}}} if format then coordinateSpec.default = format else return { lat, long }coordinateSpec.default = "dec"
end
 
return coordinateSpec, errors
end
--[[
parseDMS
 
Transforms degrees, minutes, seconds format latitude and longitude
into the a structure to be used in displaying coordinates
]]
local function parseDMS( lat_d, lat_m, lat_s, lat_f, long_d, long_m, long_s, long_f, format )
local coordinateSpec, errors, backward = {}, {}
 
lat_f = lat_f:upper();
long_f = long_f:upper();
local function parsedec(dec, coordtype, globe) -- coordtype Check if specified backward if lat_f == latitude 'E' or longitude dec lat_f == mw.text.trim(dec) if not dec 'W' then return nillat_d, long_d, lat_m, long_m, lat_s, long_s, lat_f, long_f, backward = long_d, lat_d, long_m, lat_m, long_s, lat_s, long_f, lat_f, true;
end
  if coordtype ~errors = validate( lat_d, lat_m, lat_s, long_d, long_m, long_s, 'latitude' and coordtype ~= 'longitudeparseDMS' , true ); if not long_d then makeerror(return nil, {{'invalid coord type'"parseDMS", sortkey = "AMissing longitude"}} elseif not tonumber(long_d)then return nil, {{"parseDMS", "Longitude could not be parsed as a number:" .. long_d }}
end
local numdec = tonumber(dec) -- numeric value, kept separated as it looses significant zeros if not numdec then -- tries the decimal + direction format dec lat_m and not lat_s and not long_m and not long_s and #errors = mw.ustring.gsub( mw.ustring.upper( dec ), '%a+', coordParse ) local direction = mw.ustring.sub(dec, mw.ustring.len(dec), mw.ustring.len(dec))0 then dec = mw.ustring.sub(dec, 1, mw.ustringif math_mod.len_precision(dec)-2lat_d ) -- removes the /N at the end if not dec > 0 or not tonumbermath_mod._precision(declong_d ) > 0 then return nil end if direction == 'N' or direction == 'E' or direction == 'W' and globedata[globe].defaultdisplay == 'dec west' then numdec = tonumberlat_f:upper( dec ) elseif direction == 'W' or direction == 'S' then dec lat_d = '-' .. declat_d; numdec = tonumber( dec ) elseend if coordtype long_f:upper() == 'latitudeW' then makeerror({message = i18n.invalidNS, sortkey long_d = 'A-'}) else makeerror({message = i18n.invalidEW, sortkey = 'A'}). long_d;
end
  return nilparseDec( lat_d, long_d, format );
end
end
if coordtype coordinateSpec["dms-lat"] == 'latitude' and mathlat_d.."°"..absoptionalArg(numdeclat_m,"′") > 90 then makeerror.. optionalArg({message = i18n.latitude90 lat_s, sortkey = 'A'}"″") return nil.. lat_f end if coordtype coordinateSpec["dms-long"] == 'longitude' and mathlong_d.."°"..absoptionalArg(numdeclong_m,"′") > 360 then makeerror.. optionalArg({message = i18n.longitude360 long_s, sortkey = 'A'}"″") return nil.. long_f endcoordinateSpec["dec-lat"] = convert_dms2dec(lat_f, lat_d, lat_m, lat_s) -- {{coord/dms2dec|{{{4}}}|{{{1}}}|0{{{2}}}|0{{{3}}}}} return coordinateSpec["decend-long"] = convert_dms2dec(long_f, long_d, long_m, long_s) -- {{coord/dms2dec|{{{8}}}|{{{5}}}|0{{{6}}}|0{{{7}}}}}
-- dms/dec conversion functionslocal function convertprecision(precision) -- converts a decimal precision like "2" into "dm" if precision >= 3 format then return 'dms' elseif precision >coordinateSpec.default =1 then return 'dm'format
else
return 'd' endend 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 coordinateSpec.default = math.max(precision, math_mod._precision(val))"dms"
end
return convertprecision(precision)
end
local function dec2dms_d(dec) local degrees = math_mod._round( decreturn coordinateSpec, errors, 0 ) return degreesbackward
end
--[[Check the input arguments for coord to determine the kind of data being providedand then make the necessary processing.]]local function dec2dms_dmformatTest(decargs) dec = math_mod._round( dec * 60local result, 0 )errors local minutes backward, primary = dec % 60 dec = math.floor( (dec - minutes) / 60 ) local degrees = dec % 360 return degreesfalse, minutesend false
local function dec2dms_dms(dec) dec = math_mod._roundgetParam( dec * 60 * 60args, 0 lim) local seconds ret = dec % 60{} dec for i = math.floor( (dec - seconds) / 60 )1, lim do local minutes ret[i] = dec % 60args[i] or '' end dec = math return table.floorconcat( (dec - minutes) / 60 ret, '_') local degrees = dec % 360 return degrees, minutes, secondsend
function p._dec2dms if not args[1] then -- no lat logic return errorPrinter(dec{{"formatTest", coordtype, precision, globe"Missing latitude"}} ) elseif not tonumber(args[1]) then -- coordtype: latitude or longitudebad lat logic local degrees return errorPrinter( {{"formatTest", minutes, seconds"Unable to parse latitude as a number:" .. args[1]}} ) elseif not args[4] and not args[5] and not args[6] then -- vérification du globedec logic if not result, errors = parseDec( globe and globedataargs[1], args[ globe 2] , args.format) if not result then return errorPrinter(errors); globe = 'earth' end -- formatting for geohack: geohack expects D_N_D_E notation or D;D notation -- precisionwikiminiatlas doesn't support D;D notation if not precision or precision == -- #coordinates parserfunction doesn'' thent support negative decimals with NSWE precision result.param = determinedmsprectable.concat({dec} math.abs(tonumber(args[1])), ((tonumber(args[1]) or 0) < 0)and 'S' or 'N', end math.abs(tonumber(args[2])), if precision ~= ((tonumber(args[2]) or 0) < 0) and 'W' or 'dE' and precision ~= , args[3] or 'dm' and precision ~= }, 'dms_' ) elseif dmsTest(args[4], args[8]) then return makeerror-- 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] then table.insert(errors, {sortkey = 'CformatTest', 'Extra unexpected parameters'}) end if not result then return errorPrinter(errors) end local dec result.param = tonumbergetParam(decargs, 9) elseif dmsTest(args[3], args[6]) then -- direction dm logic local direction result, errors, backward = parseDMS(args[1], args[2], nil, args[3], if coordtype == args[4], args[5], nil, args[6], args['latitudeformat' then ]) if dec < 0 args[8] then direction = table.insert(errors, {'formatTest', 'SExtra unexpected parameters'}) else end if not result then direction return errorPrinter(errors) end result.param = getParam(args, 7) 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.insert(errors, {'NformatTest', 'Extra unexpected parameters'})
end
elseif coordtype == 'longitude' then if dec < 0 or globedata[globe].defaultdisplay == 'dec west' not result then direction = 'W' else direction = 'E'return errorPrinter(errors)
end
end -- conversion dec = math result.abs(dec) -- les coordonnées en dms sont toujours positives if precision param == 'dms' then degrees, minutes, seconds = dec2dms_dmsgetParam(dec) elseif precision == 'dm' then degreesargs, minutes = dec2dms_dm(dec5)
else
degrees = dec2dms_d-- Error return errorPrinter(dec{{"formatTest", "Unknown argument format"}})
end
return builddmsdimension(degrees, minutes, seconds, direction)endresult.name = args.name
function p.dec2dms(frame) -- legacy function somewhat cumbersome syntax args local extra_param = frame.args{'dim', 'globe', 'scale', 'region', 'source', 'type'} local dec = for _, v in ipairs(extra_param) do if args[1v] if not tonumber(dec) then makeerror table.insert(errors, {message 'formatTest', 'Parameter: "' .. v .. '= i18n" should be "' .. v ..invalidFormat, sortkey = 'A:"'}) return showerrors()end
end
local dirpositive = string.lower(args[2] or '') local dirnegative ret = string.lowerspecPrinter(args[3] or '', result) local precision = string.lower(args[4] or '') local displayformat, coordtype if dirpositive == 'n' or dirpositive == 'nord' #errors > 0 then coordtype ret = ret .. 'latitude' else coordtype = .. errorPrinter(errors) .. 'longitude[[Category:Pages with malformed coordinate tags]]'
end
return ret, backwardend --[[Generate Wikidata tracking categories.]]local function makeWikidataCategories(qid) local ret if mw.wikibase and current_page.namespace == 0 then local entity = qid and mw.wikibase.getEntityObject(qid) or mw.wikibase.getEntityObject() if entity and entity.claims and entity.claims.P625 and entity.claims.P625[1] then local snaktype = entity.claims.P625[1].mainsnak.snaktype if dirpositive snaktype == 'nordvalue' or dirpositive then -- coordinates exist both here and on Wikidata, and can be compared. ret = 'Coordinates on Wikidata' elseif snaktype == 'estsomevalue' or dirnegative =then ret = 'ouestCoordinates on Wikidata set to unknown value' or dirnegative elseif snaktype == 'sudnovalue' then ret = 'Coordinates on Wikidata set to no value' end displayformat else -- We have to either import the coordinates to Wikidata or remove them here. ret = 'dms longCoordinates not on Wikidata' end
end
local coordobject = p._dec2dms(dec, coordtype, precision) if coordobject ret then return pstring.displaydmsdimensionformat(coordobject'[[Category:%s]]', displayformat) .. showerrors(ret)
else
return showerrors()''
end
end
--[[
link
 
Simple function to export the coordinates link for other uses.
 
Usage:
{{#invoke:Coordinates | link }}
]]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, dmsobjectcoordinates.seconds local factor = 0 local precision = 0 if not minutes then minutes = 0 end if not seconds then seconds = 0 end if direction == "N" or direction == "E" then factor = 1 elseif direction == "W" or direction == "S" then factor = -1 elseif not direction then makeerrorlink({message = i18n.noCardinalDirection, sortkey = 'A'}frame) return nil else makeerror({message = i18n.invalidDirection, sortkey = 'A'}) return nil end if dmsobject.seconds then -- vérifie la précision des données initiales precision = 5 + math.max( math_mod._precision(tostring(seconds), 0 ) ) -- passage par des strings assez tarabiscoté ? elseif dmsobject.minutes then precision = 3 + math.max( math_mod._precision(tostring(minutes), 0 ) ) else precision = math.max( math_mod._precision(tostring(degrees), 0 ) ) end local decimal = factor * (degrees+(minutes+seconds/60)/60) return math_mod._round(decimal, precision)coord_link;
end
function p.dms2dec(frame) -- legacy function, somewhat bizarre syntax[[dec2dms  local args = frameWrapper to allow templates to call dec2dms directly.args if tonumber(args[1]) then return args[1] -- coordonnées déjà en décimalUsage: elseif not args[2] then{{#invoke:Coordinates | dec2dms | decimal_coordinate | positive_suffix | local dmsobject = p._parsedmsstring(args[1])negative_suffix | precision }} if dmsobject then return pdecimal_coordinate is converted to DMS format._dms2dec If positive, the positive_suffixis appended (dmsobjecttypical N or E) -- coordonnées sous la fore 23/22/N else local coordType , if args[1]:match( '[NS]' ) thennegative, the negative suffix is appended. The coordType = specified precision is one of 'latitudeD' elseif args[1]:match( , '[EWO]DM') then coordType = , or 'longitudeDMS'to specify the level of detail endto use. if coordType then]] local result coordinates.dec2dms = parsedecmakeInvokeFunc( args[1], coordType, args.globe or 'earth_dec2dms' ) if result then return result end end return showerrorsfunction coordinates._dec2dms(args) end else return p._dms2dec({direction local coordinate = args[1], degrees local firstPostfix = tonumber(args[2]), minutes or '' local secondPostfix = tonumber(args[3]), seconds or '' local precision = tonumber(args[4])})or ''  endreturn convert_dec2dms(coordinate, firstPostfix, secondPostfix, precision)
end
-- Wikidata[[Helper function to determine whether to use D, DM, or DMSformat depending on the precision of the decimal input.]]local function convertwikidataprecisioncoordinates.determineMode(value1, value2 ) local precision= math.max( math_mod._precision( value1 ) -- converts a decima like "0, math_mod.1" into "dm"_precision( value2 ) ); if precision < = 0.016 then return 'dmsd' elseif precision < 1 = 2 then return 'dm';
else
return 'ddms';
end
end
local function wikidatacoords(query) query = query or {property = 'p625'} query.formatting = 'raw' local wd = require('Module:Wikidata') local claim = wd.getClaims(query) if claim and claim[1] then -- redundant but more robust in case of a change in the code of Module:Wikidata local coords = wd.formatSnak(claim[1].mainsnak) -- todo: check for special values -- 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 )dms2dec end return coordsWrapper to allow templates to call dms2dec directly.latitude, coords.longitude, coords.globe or 'earth', convertwikidataprecision(coords.precision or .001) end return nilend
Usage:
{{#invoke:Coordinates | dms2dec | direction_flag | degrees |
minutes | seconds }}
local function wikidatacat(globe)Converts DMS values specified as degrees, minutes, seconds too decimal format. --catbase= Article géolocalisé sur Terredirection_flag is one of N, S, E, W, and determines whether the output is local entitycat = mwpositive (i.wikibasee.getEntityN and E) or negative (i.e. S and W). ]] local basecat coordinates.dms2dec = 'Article géolocalisé' local finalcat = {} --BADGES if entitycat then --BADGES for i, badgeId in ipairsmakeInvokeFunc( entitycat.sitelinks['frwiki_dms2dec'].badges ) do if badgeId == 'Q17437796' then basecat=stringfunction coordinates.gsub_dms2dec(basecat, "Article géolocalisé", "Article de qualité géolocalisé"args) end local direction = args[1] if badgeId local degrees == 'Q17437798' thenargs[2] basecat local minutes =string.gsub(basecat, "Article géolocalisé", "Bon article géolocalisé") end endargs[3] endlocal seconds = args[4]
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.insertreturn convert_dms2dec(finalcatdirection,basecat) else --parfois plusieurs pays for idegrees, 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.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 ' local thecat=basecat .. ' '..prep ..mw.wikibase.label( 'Q'.. qid) if mw.title.new('category:'..thecat).exists then table.insert(finalcatminutes,thecatseconds) else --Dommage! mw.log(thecat .. ' à créer') end else --pas d'id? mw.log(qid .. ' à paramétrer') end end 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] then basecat=basecat .. ' ' .. globedata[globe].trackingcat table.insert(finalcat,basecat) else basecat=basecat .. ' extraterrestre' table.insert(finalcat,basecat) end return finalcat
end
-- main function for displaying coordinates[[function p._coord(args)coord
-- I declare variable Main entry point for Lua function to replace {{coord}} local displayformat = args.format -- string: one of: 'dms', 'dms long', 'dec', 'dec east' and 'dec west' local displayplace = string.lower(args.display or 'inline') --stringUsage: one of 'inline', 'title' or 'inline,title' local objectname = (args.name ~= '') and args.name -- string{{#invoke: name of the title displayed in geohackCoordinates | coord }} local notes = (' ' and args.notes) or '' -- string{{#invoke: notes to de displayed after coordinatesCoordinates | coord | lat | long }} local wikidata = args.wikidata -- string{{#invoke: set to "true" if neededCoordinates | coord | lat | lat_flag | long | long_flag }} 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) 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)
if latitude then -- if latitude is decimal longitude = parsedec(rawlong, 'longitude', globe) -- so should be longitude precision = determinedmsprec( Refer to {{latitude, longitudecoord}) -- before conversion from string to number } documentation page for trailing zerosmany additional parameters and if not latitude or not longitude then if errorstring == '' then makeerror({message = i18n configuration options.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) end end
-- III extract coordinate data from Wikidata and compare them Note: This function provides the visual display elements of {{coord}}. Inorder to local dataload coordinates into the database, the {{#coordinates:}} parser local wikidatalatitudefunction must also be called, wikidatalongitude, wikidataglobe, wikidataprecisionthis is done automatically in the Luaversion of {{coord}}.]] if wikidata =coordinates.coord = makeInvokeFunc('true_coord' then) wikidatalatitude, wikidatalongitude, wikidataglobe, wikidataprecision = wikidatacoordsfunction coordinates._coord(wikidataqueryargs) if wikidatalatitude and latitude and longitude then local maxdistance = not tonumber(args.maxdistance[1]) or wikidatathresholdand not args[2] then if p._distance({latitude args[3] = latitude, longitude= longitude}, {latitude = wikidatalatitude, longitudeargs[1]; args[1] = wikidatalongitude}, wikidataglobe) < maxdistance thennil trackingstring local entity = trackingstring mw.wikibase. makecatgetEntityObject(i18nargs.sameaswikidataqid) else if entity trackingstring = trackingstring and entity.claims and entity. makecat(i18nclaims.notaswikidata)P625 end endand entity.claims.P625[1].mainsnak.snaktype == 'value' if wikidatalatitude and not latitude then latitude, longitude, globe, local precision = wikidatalatitude, wikidatalongitude, wikidataglobe, wikidataprecisionentity.claims.P625[1].mainsnak.datavalue.value.precision dmslatitude, dmslongitude args[1] = pentity.claims.P625[1].mainsnak.datavalue.value._dec2dms(latitude, 'latitude', precision), p._dec2dms(longitude, 'longitude', precision, globe) trackingstring args[2] = trackingstring entity.claims. makecat(i18nP625[1].mainsnak.datavalue.value.throughwikidata)longitude end if latitude and not wikidatalatitude precision then if mw precision = -math_mod.title_round(math.getCurrentTitlelog(precision)/math.namespace == log(10),0 then) trackingstring args[1] = trackingstring math_mod._round(args[1],precision) args[2] = math_mod. makecat_round(i18n.nowikidataargs[2],precision)
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) -- exit if stil no latitude Finds whether coordinates are displayed inline. return s:find('inline') ~= nil or s == 'i' or s == 'it' or no longitudes == 'ti' end if not latitude and not longitude thenlocal function isInTitle(s) return nil -- ne rien ajouter ici pour que lFinds whether coordinates are displayed in the title. return s:find('title'appel à cette fonction retourne bien ) ~= nil en lor s == 't' or s == 'it' or s == 'ti'absence de données
end
-- IV best guesses for missing parameterslocal function coord_wrapper(in_args) - -- globeCalls the parser function {{#coordinates:}}. if globe == return mw.getCurrentFrame():callParserFunction('#coordinates' then globe = , in_args) or 'earth'
end
  local text = '' if not globedata[globe] isInline(Display) then makeerror({message text = i18ntext .invalidGlobe .. globe}displayinline(contents, Notes) globe = 'earth'
end
if globe ~= 'earth' isInTitle(Display) then extraparams text = extraparams text ..displaytitle(contents, Notes) . '_globe:' .makeWikidataCategories(args. globe -- pas de problème si le globe est en double maplink = falseqid)
end
--- diplayformat if not displayformat or displayformat == '' args.nosave then displayformat local page_title, count = globedata[globe]mw.title.defaultdisplaygetCurrentTitle(), 1 end if backward then -- displayinline/displaytitle local displayinline tmp = {} while not string.find(displayplace(args[count-1] or ''), 'inline[EW]') do tmp[count] = (args[count] or ''); count = count+1 end local displaytitle tmp.count = count; count = 2*(count-1) while count >= stringtmp.count do table.findinsert(displayplacetmp, 1, (args[count] or 'title') ); count = count-1 end if not displayinline and not displaytitle then displayinline for i, v in ipairs(tmp) do args[i] = truev end if displayplace ~= '' then else makeerrorwhile count <= 9 do args[count] = ({sortkey = args[count] or 'C'}) --error if display not empty, but not not a major error, continue; 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
if displaytitle and mw.title.getCurrentTitle().namespace == 0 thenreturn textend  --local cattoappend=globedata[globe].trackingcat[ --Récupération des badgescoord2text local cats=wikidatacat(globe) for i, cat in ipairs( cats ) doExtracts a single value from a transclusion of {{Coord}}. trackingstring = trackingstring IF THE GEOHACK LINK SYNTAX CHANGES THIS FUNCTION MUST BE MODIFIED.. makecat(cat) end endUsage: -- V geodata {{#invoke:Coordinates | coord2text | {{Coord}} | parameter }} local geodata = '' if latitude and longitude then local latstring, longstring = tostringValid values for the second parameter are: lat (latitudesigned integer), tostringlong (longitudesigned integer) local primary = '', type, scale, dim, region, globe, source
local ]]function coordinates.coord2text(frame) if frame.args[1] == '' or frame.args[2] == '' or not frame.args[2] then return nil end frame .args[2] = mw.getCurrentFrametext.trim(frame.args[2]) if frame.args[2] == 'lat' or frame.args[2] == 'long' then local geodataparams result, negative = {mw.text.split((mw.ustring.match(frame.args[1] = latstring, '[%.%d]+°[NS] [2%.%d] = longstring, [3EW] = extraparams }') or ''), ' ') if displaytitle frame.args[2] == 'lat' then geodataparamsresult, negative = result[41] = , 'primaryS' end if objectname thenelse geodataparams.name result, negative = objectnameresult[2], 'W'
end
geodata result = frame:callParserFunctionmw.text.split(result, '#coordinates°', geodataparams ) if string.find(geodata, 'error') result[2] == negative then -- the only error that has not been caught yet is primary key geodata result[1] = '-' makeerror({sortkey='D'}) end ..result[1] end-- VI final output local mainstring = '' if maplink then mainstring = buildMaplinkHTML(latitude, longitude, dmslatitude, dmslongitude, globe, displayformat, displayinline, displaytitle, objectname,extraparams )return result[1]
else
mainstring return mw.ustring.match(frame.args[1], 'params= buildHTML.-_'..frame.args[2]..':(latitude, longitude, dmslatitude, dmslongitude, globe, displayformat, displayinline, displaytitle, objectname,extraparams .-)[ _]')
end
return mainstring .. notes .. trackingstring .. geodata .. showerrors()
end
function p.coord(frame) -- parrses [[coordinsert Injects some text into the strange parameters Geohack link of a transclusion of Template:{{Coord before sending them to p.coord local args = frame.args local numericargs = {} for i, j } (if that text isn't already in ipairs(argsthe transclusion) do args[i] = mw.textOutputs the modified transclusion of {{Coord}}.trim(j) if type(i) == 'number' and args[i] ~= '' then tableIF THE GEOHACK LINK SYNTAX CHANGES THIS FUNCTION MUST BE MODIFIED.insert(numericargs, args[i]) end end
if #numericargs %2 == 1 then -- if the number of args is odd, the last one provides formatting parameters args.extraparams = numericargs[#numericargs] if #numericargs == 1 and tonumber(numericargs[1]) then makeerror({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 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 endUsage:
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 | {{Coord}} | parameter:value | parameter:value | … }}
function p.Do not make Geohack unhappy by inserting something which isn't mentioned in the {{Coord(frame) return p}} documentation.coord(frame)end
]]function pcoordinates.latitudecoordinsert(frame) -- helper function pour infobox, à déprécier local args = for i, v in ipairs(frame.args) do local latitude if i ~= 1 then if not mw.ustring.find(frame.args[1] if latitude and , (mw.textustring.trimmatch(frame.args[i], '^(latitude.-:) ~= ') or '' )) then return latitude elseif frame.args[1] = mw.ustring.gsub(frame.args[1], 'wikidata(params=.-)_? ', '%1_'..frame.args[i] == ..'true' then) local lat, long = wikidatacoords() end return latend
end
end if frame.args.name thenfunction p if not mw.ustring.longitudefind(frame.args[1], '<span class="vcard">') -- helper function pour infobox, à déprécierthen local args namestr = frame.args.name local longitude = frame.args[1] if longitude and = mw.textustring.gsub(frame.trimargs[1], '(<span class="geo%-default">)(<span[^<>]*>[^<>]*</span><span[^<>]*>[^<>]*<span[^<>]*>[^<>]*</span></span>)(longitude</span>) ~', '%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['wikidata'1] =mw.ustring.gsub(frame.args[1], '(&params= [^&"<>%[%] ]*) 'true, ' then local lat, long %1&title= wikidatacoords' .. mw.uri.encode(namestr) .. ' ') return longend
end
return frame.args[1]
end
 return pcoordinates