FiveM how to check where nearest player is

-- Step 1: Get the player's own server ID
local playerId = GetPlayerServerId(PlayerId())

-- Step 2: Get the list of all players on the server
local players = GetActivePlayers()

-- Step 3: Initialize variables for tracking the nearest player and their distance
local nearestPlayer = nil
local nearestDistance = -1

-- Step 4: Iterate through each player to find the nearest one
for _, targetPlayer in ipairs(players) do
    -- Exclude the current player from consideration
    if targetPlayer ~= playerId then
        -- Get the coordinates of the current player and the target player
        local playerCoords = GetEntityCoords(GetPlayerPed(-1))
        local targetCoords = GetEntityCoords(GetPlayerPed(targetPlayer))

        -- Calculate the distance between the two players
        local distance = Vdist(playerCoords.x, playerCoords.y, playerCoords.z, targetCoords.x, targetCoords.y, targetCoords.z)

        -- Check if the current target player is closer than the previous nearest player
        if nearestPlayer == nil or distance < nearestDistance then
            nearestPlayer = targetPlayer
            nearestDistance = distance

-- Step 5: Check if a nearest player was found and do something with the information
if nearestPlayer ~= nil then
    -- Do something with the nearest player's ID and distance (e.g., print to the console)
    print("Nearest Player ID: " .. nearestPlayer)
    print("Distance to Nearest Player: " .. nearestDistance)
    -- Handle the case where no other players are on the server
    print("No other players on the server.")