HTML5 Geolocation






<!--
main_leaderboard, all: [728,90][970,90][320,50][468,60]
-->




HTML5 Geolocation



❮ Previous
Next ❯



The HTML Geolocation API is used to locate a user's position.





var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition,showError);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}

function showPosition(position)
{
var lat=position.coords.latitude;
var lon=position.coords.longitude;
var latlon=new google.maps.LatLng(lat, lon)
var mapholder=document.getElementById('mapholder')
mapholder.style.height='250px';
mapholder.style.width='100%';

var myOptions={
center:latlon,zoom:14,
mapTypeId:google.maps.MapTypeId.ROADMAP,
mapTypeControl:false,
navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}
};
var map=new google.maps.Map(document.getElementById("mapholder"),myOptions);
var marker=new google.maps.Marker({position:latlon,map:map,title:"You are here!"});
}

function showError(error)
{
switch(error.code)
{
case error.PERMISSION_DENIED:
x.innerHTML="User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML="Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML="The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML="An unknown error occurred."
break;
}
}


Locate the User's Position


The HTML Geolocation API is used to get the geographical position of a user.


Since this can compromise privacy, the position is not available unless the user approves it.



Note: Geolocation is most accurate for devices with GPS, like iPhone.





Browser Support


The numbers in the table specify the first browser version that fully supports
Geolocation.



















API
Geolocation 5.0 - 49.0 (http)
50.0 (https)
9.0 3.5 5.0 16.0


Note: As of Chrome 50, the Geolocation API will only work on secure contexts such
as HTTPS. If your site is hosted on an non-secure origin (such as HTTP) the
requests to get the users location will no longer function.





Using HTML Geolocation


The getCurrentPosition() method is used to return the user's position.


The example below returns the latitude and longitude of the user's position:



Example



<script>
var x = document.getElementById("demo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
}
</script>

Try it Yourself »

Example explained:



  • Check if Geolocation is supported

  • If supported, run the getCurrentPosition() method. If not, display a message to the user

  • If the getCurrentPosition() method is successful, it returns a coordinates object to the function specified in the parameter (showPosition)

  • The showPosition() function outputs the Latitude and Longitude


The example above is a very basic Geolocation script, with no error handling.







<!--
mid_content, all: [300,250][336,280][728,90][970,250][970,90][320,50][468,60]
-->





Handling Errors and Rejections


The second parameter of the getCurrentPosition() method is used to handle
errors. It specifies a function to run if it fails to get the user's location:



Example



function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."
            break;
    }
}

Try it Yourself »



Displaying the Result in a Map


To display the result in a map, you need access to a map service, like Google
Maps.


In the example below, the returned latitude and longitude is used to show the location in a Google
Map (using a static image):



Example



function showPosition(position) {
    var latlon = position.coords.latitude + "," + position.coords.longitude;

    var img_url = "https://maps.googleapis.com/maps/api/staticmap?center=
    "+latlon+"&zoom=14&size=400x300&sensor=false&key=YOUR_:KEY";

   
document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}

Try it Yourself »

Google Map Script
How to show an interactive Google Map with a marker, zoom and drag options.




Location-specific Information


This page has demonstrated how to show a user's position on a map.


Geolocation is also very useful for location-specific information, like:



  • Up-to-date local information

  • Showing Points-of-interest near the user

  • Turn-by-turn navigation (GPS)




The getCurrentPosition() Method - Return Data


The getCurrentPosition() method returns an object on success. The latitude,
longitude and accuracy properties are always returned. The other properties are returned
if available:








































PropertyReturns
coords.latitudeThe latitude as a decimal number (always returned)
coords.longitudeThe longitude as a decimal number (always returned)
coords.accuracyThe accuracy of position (always returned)
coords.altitudeThe altitude in meters above the mean sea level (returned if available)
coords.altitudeAccuracyThe altitude accuracy of position (returned if available)
coords.headingThe heading as degrees clockwise from North (returned if available)
coords.speedThe speed in meters per second (returned if available)
timestampThe date/time of the response (returned if available)



Geolocation Object - Other interesting Methods


The Geolocation object also has other interesting methods:




  • watchPosition() - Returns the current position of the user and continues to
    return updated position as the user moves (like the GPS in a car).


  • clearWatch() - Stops the watchPosition() method.


The example below shows the watchPosition() method. You need an accurate GPS device to test this (like iPhone):



Example



<script>
var x = document.getElementById("demo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.watchPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
}
</script>

Try it Yourself »



❮ Previous
Next ❯

Popular posts from this blog

Colors HSL

Google Hardware Icons

SVG Filters