Working with Geolocation watchPosition() API

[adinserter block=”34″]

I’m going to share a Geolocation watchPosition() API example. This 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).

This works while the user is 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.

Working with Geolocation watchPosition() API

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);
}

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

[purchase_link id=”12468″ text=”Download Now” style=”button” color=”green”]

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.

Related Source Code

Google Maps Geocoding Example with PHP – This tutorial is about a Google Maps geocoding example with PHP. We used some Google Maps JavaScript to show the geo-coded data on the map as well.

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.


Comments

11 responses to “Working with Geolocation watchPosition() API”

  1. Have you done anything with tracking the user as they are walking, driving, etc with displaying a line as to where they have been?

    1. Hello @disqus_papItWMeR2, that is possible to do but I don’t have a code for that yet. Thanks for your comment, now I have more idea about what features I can add to this blog post. 😀

      1. Let me know if you get something up with that!

        1. Sure, I’ll comment it out here 🙂

  2. Ev. rodrigo Avatar
    Ev. rodrigo

    good afternoon friend I tested your code but when walking,
    test the code, but my place walks but the map not, the map should Center in my position while walking

    1. Hello @evrodrigo , thanks for the feedback! Unfortunately our code above does not have that feature yet. But we’ll keep your suggestion and try to update soon.

      1. Ev. rodrigo Avatar
        Ev. rodrigo

        I managed to solve, enter the set function make position after); map.setCenter (nee Google.maps.latlong (position.coords.latitude, position.coords.longitude));

        I really appreciate your code helped me improve my code

        Em 24 de ago de 2016 11:00 PM, “Disqus” escreveu:

      2. Ev. rodrigo Avatar
        Ev. rodrigo

        I managed to solve, enter the set function make position after); map.setCenter (nee Google.maps.latlong (position.coords.latitude, position.coords.longitude));

        I really appreciate your code helped me improve my code

        1. You’re welcome and thanks for sharing your solution @evrodrigo ! I’ll update the blog post soon.

  3. A new window opens with “page ok” and that’s it! 🙂

    1. Hi @GR, demo page is now fixed, thanks for the report!

Leave a Reply

Your email address will not be published. Required fields are marked *