codeofaninja
website

Working with Geolocation watchPosition() API

Photo of Mike Dalisay
Modified Tuesday, August 20, 2013
by - @ninjazhai
I'm going to share a working navigator.geolocation.watchPosition() code I used when I wanted the user to know his current location in real time (while he is walking or riding a vehicle) using his Android device or any device with a browser that supports the Geolocation API. We made this code with the help of Google Maps and jQuery.


Live Demo


Recommended to use a mobile device, you must allow it to get your current location, don't worry, I'm not tracking you.

Code Example


Now here's our index.html code.

<!DOCTYPE HTML>
<html>
<head>
    <title>Geolocation watchPosition() by The Code of a Ninja</title>
    
    <!-- for mobile view -->
    <meta content='width=device-width, initial-scale=1' name='viewport'/>
    
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"></script>
    <script type="text/javascript">

        // you can specify the default lat long
        var map,
            currentPositionMarker,
            mapCenter = new google.maps.LatLng(14.668626, 121.24295),
            map;

        // change the zoom if you want
        function initializeMap()
        {
            map = new google.maps.Map(document.getElementById('map_canvas'), {
               zoom: 18,
               center: mapCenter,
               mapTypeId: google.maps.MapTypeId.ROADMAP
             });
        }

        function locError(error) {
            // tell the user if the current position could not be located
            alert("The current position could not be found!");
        }

        // current position of the user
        function setCurrentPosition(pos) {
            currentPositionMarker = new google.maps.Marker({
                map: map,
                position: new google.maps.LatLng(
                    pos.coords.latitude,
                    pos.coords.longitude
                ),
                title: "Current Position"
            });
            map.panTo(new google.maps.LatLng(
                    pos.coords.latitude,
                    pos.coords.longitude
                ));
        }

        function displayAndWatch(position) {
        
            // set current position
            setCurrentPosition(position);
            
            // watch position
            watchCurrentPosition();
        }

        function watchCurrentPosition() {
            var positionTimer = navigator.geolocation.watchPosition(
                function (position) {
                    setMarkerPosition(
                        currentPositionMarker,
                        position
                    );
                });
        }

        function setMarkerPosition(marker, position) {
            marker.setPosition(
                new google.maps.LatLng(
                    position.coords.latitude,
                    position.coords.longitude)
            );
        }

        function initLocationProcedure() {
            initializeMap();
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
            } else {
                // tell the user if a browser doesn't support this amazing API
                alert("Your browser does not support the Geolocation API!");
            }
        }

        // initialize with a little help of jQuery
        $(document).ready(function() {
            initLocationProcedure();
        });
    </script>
</head>

<body style="margin:0; padding:0;">
    
    <!-- display the map here, you can changed the height or style -->
    <div id="map_canvas" style="height:25em; margin:0; padding:0;"></div>
</body>

</html>

In my case, I used this code with an Android WebView since it should be seen inside an app I'm working on, but as I said, this will work with any device with a browser. If you have the same case as mine, you can also use this piece of android WebView code.

Just add

webSettings.setGeolocationEnabled(true);

and inside your setWebChromeClient()...

@Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
    
    super.onGeolocationPermissionsShowPrompt(origin, callback);
    callback.invoke(origin, true, false);
}

Issues Encountered


If you were testing it with an Adroid Webview or Chrome Browser and seemed like it is not working, don't lose hope. There is always hope. :)

Here's the solution, uninstall the Chrome browser and then re-install it.

Further Reading


Geolocation API Specification
Geolocation.watchPosition() from Mozilla Developer Network

Don't hesitate to post your comments regarding this Geolocation watchPosition() API example code.
For FREE programming tutorials, click the red button below and subscribe! :)
Thanks for the comments!
 
 
Fundamentals
"First do it, then do it right, then do it better."
~ Addy Osmani
"Talk is cheap. Show me the code."
~ Linus Torvalds
Let's Stay Connected!
g+ r
Android app on Google Play
© 2011-2014 The Code Of A Ninja. All rights reserved. Proudly Powered by Google Blogger. Images, logos, marks or names mentioned herein are the property of their respective owners.