0

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
JimmyFl0
  • 96
  • 1
  • 8
  • Google Geolocation API doesn't have an `ipAddress` argument. Did you make that up? https://developers.google.com/maps/documentation/geolocation/overview – Selcuk Dec 28 '22 at 17:12
  • Yes, good ol chatGPT. How do I get it to use a specific IP Address then? Because if I don't it will only return the REMOTE_ADDR which will be the Heroku server. – JimmyFl0 Dec 28 '22 at 17:38
  • 1
    It does not look like you can be sure that the ip address in that header, https://stackoverflow.com/a/37061471/6383431 – ErikR Dec 28 '22 at 18:20
  • That helped me understand, thank you! – JimmyFl0 Dec 28 '22 at 18:33
  • 1
    Google API does not do that. Try MaxMind. – Selcuk Dec 29 '22 at 04:45
  • 1
    Google geolocation API does not accept IP address. You need to use IP geolocation API such as ip2location.io to get results. Sign up their free key to test. – Michael C. Dec 29 '22 at 06:20

0 Answers0