User:Jules/distuser

From XPUB & Lens-Based wiki

I've used the IP address of the user to get their coordinates.
Then, I convert the coordinates into spherical coordinates.
And I multiply by 6373 to convert into kilometers.
It is also possible to multiply by 3961 to convert in Miles but I am in favour of the metric system.



 
#!/usr/bin/python
import cgitb; cgitb.enable()
import cgi
import pygeoip
import math

#db
i = cgi.FieldStorage()
gi = pygeoip.GeoIP('path/to/db/GeoLiteCity.dat')
user = i.getvalue("ip","74.125.140.101")

#recuperation infos utilisateur
infos = gi.record_by_addr(user)
Latuser = infos.get('latitude')
Longuser = infos.get('longitude')

#My server's coordinates
Latserver = 34.0202
Longserver = -118.3928

def distance(Latuser, Longuser, Latserver, Longserver):
    # Let's pretend that the Earth's shape is spherical
    # Convert latitude and longitude to
    # spherical coordinates in radians.
    radians = math.pi/180.0
    # phi = 90 - latitude
    phi1 = (90.0 - Latuser)*radians
    phi2 = (90.0 - Latserver)*radians         
    # theta = longitude
    theta1 = Longuser*radians
    theta2 = Longserver*radians
         
    # Compute spherical distance from spherical coordinates.         
    # For two locations in spherical coordinates
    cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
           math.cos(phi1)*math.cos(phi2))
    arc = math.acos( cos )

    # Multiply arc by the radius of the earth in km
    arc = arc*6373
    arc = round(arc, 2)
    arc = str(arc) 

    print "Content-type:text/html"
    print
    print "<h1> Your request has been sent " + arc + " km away and back</h1>"


distance(Latuser, Longuser, Latserver, Longserver)