Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

General Discussion

Dalton Patterson
Dalton Patterson
Full Stack JavaScript Techdegree Student 11,754 Points

Simple GEOlocation ????

I am looking for a simple way to swap a button based on my users location. For example if my user is from Canada show this button, or if from US show this button.

Is there a simple way to do this?

2 Answers

you could either do it with the user's coordinates or by locating the user based on his IP address. then you just switch the buttons with javascript.

Generally, working with user coordinates will be more precise than an IP lookup, but users will have to give their consent for sharing their coordinates and some devices may not be able to give an exact location, so you're best off combining both approaches: get the user's coordinates and use IP location as a fallback.

for the coordinate approach, use the getCurrentPosition() javascript method. if you get coordinates, you will need a reverse geocoding service (lke https://developers.google.com/maps/documentation/geocoding/ ) that will translate the latitude/longitude to an address, including the country.

for the IP approach, just use http://freegeoip.net/ and add /{format}/{ip} to the URL , where format is either csv, xml or json. this will return a field "country_code" that contains the info you're after.

once you have a country code, either by geolocation or IP, just use javascript to modify your content as desired.

also have a look at: