How do I pass an IP address to Google geolocation api?

748 Views Asked by At

I have a Django web app that deploys on Heroku, so I'm trying to get the actual user's IP, not the heroku server. Everything works fine when I run the project locally. When I deploy it to Heroku, it gives me the Heroku server location, even though I get the correct IP from x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR'). Am I passing it incorrectly to google?

def get_latitude_longitude(request):
   # Get the user's IP address
   x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
   if x_forwarded_for:
       ip_address = x_forwarded_for
    
   else:
       ip_address = request.META.get('REMOTE_ADDR')

   url = f"https://www.googleapis.com/geolocation/v1/geolocate?key={settings.GOOGLE_API_KEY}&considerIp=true&ipAddress={ip_address}"
   # Make the request
   response = requests.post(url)

   # Check the response status code
   if response.status_code != 200:
       print(response)
   # Parse the response data
   data = response.json()
   latitude = data['location']['lat']
   longitude = data['location']['lng']
   accuracy = data['accuracy']
   return latitude, longitude, data, ip_address
0

There are 0 best solutions below