So, I want to be able to find the users location (even if it's only down to the city/town level), when they log onto the home page of my website. I figured this isn't impossible because Google seems to do it when you log on their main page, it se开发者_如何学Pythonems to gear your search results toward your area, etc.
What would I look into to be able to do this?
You can use GeoIP location services, who have various levels of accuracy. There may be other providers of IP-location databases too.
Another option is to try to use HTML5 location services, such as in http://html5demos.com/geo and http://dev.w3.org/geo/api/spec-source.html.
You need to use an IP geo/co-location API such as this one and many others. This one boasts a free service requiring only registration.
You can also download databases with geo code information. This will work to certain resolution but the db represents a static snapshot and reality may veer significantly over time. Here is a freely available CSV file that could get you started on the local db side of things. The CSV file (which is a bit old, was last updated August 2009) contains 59,000 entries.
YOu can either a) use an online service to look up the location - many have an api, or b) there are numerous databases floating around the web that you can download. Depending on the resolution you need, you may have to pay. But country resolution is certainly available for free. Try googling "geo ip" or similar.
I would like to add another solution because of some issues I faced. All the earlier answers work very well. But if you'll use HTML Geolocation API you'll have to ask for the location permission from the user. IPinfo works very well but some adblockers like ublock will block the API hit from the client side.
If it is possible for you to change your DNS manager to CLoudflare then you can use Cloudflare IP Geolocation. You can refer to Don's answer here
If you don't care about super-fine accuracy, and you don't want to annoy your user with an alert requesting their permission to access their location, then you can make use of something like FreeGeoIP. I've written a small jQuery plugin that makes use of this. See the Locaternator. Supports jsonp
requests too so you can use it from any website, including static html only webs.
you can use navigator.geolocation.getCurrentPosition
in HTML5.It would be reasonably cross-platform and you could build it into web pages that report back to your database.
See
http://html5demos.com/geo
http://www.w3.org/TR/geolocation-API/
http://diveintohtml5.info/geolocation.html
精彩评论