Replacing getCurrentPosition()

Web browsers have offered an in-built geolocation solution for a while, allowing you to get the latitude and longitude (but not place name) for the user's currently location, after prompting the user for permission. In a recent update to their Chrome browser Google have limited the use of this feature so that is only works on secure websites, served over HTTPS. If you try to use this functionality on a HTTP site it won't work for you.

In this guide we describe how you can use our API to replace the browser's geolocation API to get the user's coordinates, or in combination with it as a fallback for when it's not available. It works on HTTP sites, doesn't prompt the user for permission, and also includes city, region and country names.

We also recently enabled free access to the HTTPS version of our API, so you can use this on HTTP or HTTPS sites, free for up to 1,000 requests a day. If you need to make more than 1,000 requests then take a look at our paid plans.

Here's an example of the browser geolocation API in action:

navigator.geolocation.getCurrentPosition(function(position) { console.log(position); }); }
{ "coords": { "accuracy": 30, "altitude": null, "altitudeAccuracy": null, "heading": null, "latitude": 37.58611580000001, "longitude": -122.35850389999999, "speed": null } }

Our API only has the latitude and longitude fields from that API, but also includes some other details, such as place names:

{ "ip": "", "city": "San Leandro", "region": "California", "country": "US", "loc": "37.7083,-122.1282", "postal": "94578" }

Here's an example that uses jQuery to call our API, and constructs as coords object that has longitude and latitude fields, which can be used almost interchangeably with the getCurrentPosition position.coords object:

$.getJSON('', function(response) { var loc = response.loc.split(','); var coords = { latitude: loc[0], longitude: loc[1] }; });

Here's a more complete example that combines both our API and the getCurrentPosition call. It first tries to use the browser's built in geolocation API, and then calls our API if that fails due to it either not being available, or the user declining permission:

function do_something(coords) { // Do something with the coords here // eg. show the user on a map, or customize // the site contents somehow } navigator.geolocation.getCurrentPosition(function(position) { do_something(position.coords); }, function(failure) { $.getJSON('', function(response) { var loc = response.loc.split(','); var coords = { latitude: loc[0], longitude: loc[1] }; do_something(coords); }); }; });