Geolocation API Demo: Local Weather
Nearly all modern browsers support geolocation. This way web applications are able to work with the user’s location. As an example application I made a small website, that shows the name of the city you are in right now, and current weather conditions.
→ Demo Page ←
And this is how it works:
- First we ask the browser for the position. Nearly all browsers ask the user for permission. Geolocation itself is done by the browser and the operating system. On a mobile device, maybe GPS can be used to determine the user’s location, on a normal PC we get the position by nearby WiFi networks or simply by the IP address. The position is accessed via JavaScript. I didn’t implement Google Gears as fallback for older browsers.
- Using Google Maps API the coordinates retrieved by the Geolocation API are translated into a city name. This also happens using JavaScript.
- The Weather Data is from the inofficial Google Weather API. First, the API is called using coordinates. This does not always work well, in this case the API is called using the retrieved city name.
The API call finds place in a PHP script using cURL – this script then is read using AJAX.
Known Issues
- The error message „Couldn’t find your location.“ mostly occurs, when the geolocation permission request is answered too late. Reload the site and give the permission faster.
- There is a bug in Safari, which occurs when the Geolocation API is called repeatedly. Restart Safari.
- Internet Explorer is not supported. Geolocation API works best with Chrome.
- The error „Sorry, your browser doesn’t support geolocation.“ (in a modern browser) indicates, that geolocating or JavaScript is disabled. Enable it in your browser settings and you should be fine.
- Currently, temperature is always shown in Celsius, because it is used world wide and not only in the US like Fahrenheit.
Other issues? Just head on to the comment section (if possible, post the output of the JavaScript console).