QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads Intel XDK Geolocation Tutorial

Intel XDK Geolocation Tutorial

geolocation

This post is a part 43 of Intel XDK Complete Tutorial post series.

In this tutorial I will show you how to find user’s current location using JavaScript in Intel XDK app. Applications like Facebook messenger, Google Maps APP etc use some sort of Geolocation APIs to detect user location and display it on embedded Google Maps.

Including Cordova Geolocation Plugin

We will be using Cordova geolocation plugin to implement geolocation functionality in our app.

Capture

This plugin is supported in Cordova hybrid and legacy hybrid apps.

Find User’s Current Position

Here is the code to find user’s current latitude and longitude position

        document.addEventListener("deviceready", function(){
            navigator.geolocation.getCurrentPosition(function(position){
                alert('Latitude: '          + position.coords.latitude          + '\n' +
                      'Longitude: '         + position.coords.longitude         + '\n' +
                      'Altitude: '          + position.coords.altitude          + '\n' +
                      'Accuracy: '          + position.coords.accuracy          + '\n' +
                      'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
                      'Heading: '           + position.coords.heading           + '\n' +
                      'Speed: '             + position.coords.speed             + '\n' +
                      'Timestamp: '         + position.timestamp                + '\n');
            }, function(error){
                if(error.code == PositionError.PERMISSION_DENIED)
                {
                    alert("App doesn't have permission to use GPS");
                }
                else if(error.code == PositionError.POSITION_UNAVAILABLE)
                {
                    alert("No GPS device found");
                }
                else if(error.code == PositionError.TIMEOUT)
                {
                    alert("Its taking too long find user location");
                }
                else
                {
                    alert("An unknown error occured");
                }
            }, { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true });
        }, false);

getCurrentPosition is a asynchronous function and takes three parameters: success callback, error callback and options.

  1. Inside success callback you can find latitude, longitude, altitude, accuracy, altitude accuracy, heading, speed and timestamp of the device.

    altitude represents the height of the position in meters above the ellipsoid.

    accuracy represents the accuracy level of the latitude and longitude coordinates in meters.

    altitudeAccuracy represents Accuracy level of the altitude coordinate in meters.

    heading represents the direction of travel, specified in degrees counting clockwise relative to the true north.

    speed represents the current ground speed of the device, specified in meters per second.

  2. Inside error callback you find the reason why an error occurred while finding the position of the device.
  3. timeout represents the number of milliseconds to wait for the device to find the location, if the time crosses an error callback is fired.

    maximumAge represents the number of milliseconds the last retrieved position should be cached for.

    If enableHighAccuracy is set to true then this api uses GPS device to find the position otherwise it uses Internet. GPS provides more accurate position than Internet.

Now you can use Google Maps JavaScript API to display a map and mark the user on the map.

Displaying Google Map and Marking User Position

Here is the complete source code to display google maps and mark user position.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">

    <style>
        @-ms-viewport { width: 100vw ; zoom: 100% ; }                          
        @viewport { width: 100vw ; zoom: 100% ; }
        @-ms-viewport { user-zoom: fixed ; }                                    
        @viewport { user-zoom: fixed ; }
    </style>

    <script src="https://cdn.rawgit.com/ftlabs/fastclick/master/lib/fastclick.js"></script>
    <link rel="stylesheet" href="css/app.css">
</head>
<body>
   
    <div id="googleMap" style="width:300px;height:300px;"></div>
   
    <script src="intelxdk.js"></script>        
    <script src="cordova.js"></script>          
    <script src="xhr.js"></script>              

    <script src="js/app.js"></script>
    <script src="js/init-app.js"></script>
    <script src="js/init-dev.js"></script>
   
    <script src="http://maps.googleapis.com/maps/api/js"></script>
   
    <script>
        document.addEventListener("deviceready", function(){
            navigator.geolocation.getCurrentPosition(function(position){
               
            var mapProp = {center:new google.maps.LatLng(position.coords.latitude,position.coords.longitude), zoom:5, mapTypeId:google.maps.MapTypeId.ROADMAP};
            var map=new google.maps.Map(document.getElementById("googleMap"), mapProp);
            var marker=new google.maps.Marker({position:new google.maps.LatLng(position.coords.latitude,position.coords.longitude)});
            marker.setMap(map);
            }, function(error){
                if(error.code == PositionError.PERMISSION_DENIED)
                {
                    alert("App doesn't have permission to use GPS");
                }
                else if(error.code == PositionError.POSITION_UNAVAILABLE)
                {
                    alert("No GPS device found");
                }
                else if(error.code == PositionError.TIMEOUT)
                {
                    alert("Its taking too long find user location");
                }
                else
                {
                    alert("An unknown error occured");
                }
            }, { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true });
        }, false);
    </script>
</body>
</html>

Screen Shot 2015-01-16 at 5.36.21 pm

Watching User’s Position Continuously

Sometimes its necessary to watch user’s current position continuously. This can be useful if you are creating a Cab app, distance traveled measuring app etc.

Here is the code to watch the user’s position continuously

        var watchID = null;
       
        document.addEventListener("deviceready", function(){
            watchID = navigator.geolocation.watchPosition(function(position){
                console.log('Latitude: '          + position.coords.latitude          + '\n' +
                      'Longitude: '         + position.coords.longitude         + '\n' +
                      'Altitude: '          + position.coords.altitude          + '\n' +
                      'Accuracy: '          + position.coords.accuracy          + '\n' +
                      'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
                      'Heading: '           + position.coords.heading           + '\n' +
                      'Speed: '             + position.coords.speed             + '\n' +
                      'Timestamp: '         + position.timestamp                + '\n');
            }, function(error){
                if(error.code == PositionError.PERMISSION_DENIED)
                {
                    alert("App doesn't have permission to use GPS");
                }
                else if(error.code == PositionError.POSITION_UNAVAILABLE)
                {
                    alert("No GPS device found");
                }
                else if(error.code == PositionError.TIMEOUT)
                {
                    alert("Its taking to find user location");
                }
                else
                {
                    alert("An unknown error occured");
                }
            }, { maximumAge: 3000, timeout: 30000, enableHighAccuracy: true });
        }, false);

Here we used watchPosition instead of getCurrentPosition. watchPosition executes success callback whenever a change in position is detected. watchPosition is also a asynchronous function.

You can stop watching the position anytime using the below code

navigator.geolocation.clearWatch(watchID);

This is all about integrating Geolocation in an Intel XDK app. Thanks for reading.

Jan 7, 2015Narayan Prusty
Local Database Storage using Intel XDKWordPress Freelance Plugin Widget
Comments: 15
  1. Simon
    5 years ago

    Hi, this does not work.

    ReplyCancel
  2. Malak
    5 years ago

    Hi Mr.Narayan,
    How can I display full map with 100% width and height ?
    i tried change the style attribute to 100% width and 100% height but it didn’t work !!!!!! can u help

    ReplyCancel
  3. agir
    5 years ago

    is it possible for me to upload Grace data map in intel XDK?

    ReplyCancel
  4. Josue
    5 years ago

    Hi! is It possible do this without GPS is on? Thanks

    ReplyCancel
    • Peter
      5 years ago

      How are you supposed to get GPS Position, when GPS System is turned off ..?

      ReplyCancel
      • Josue
        5 years ago

        Exactly!

        ReplyCancel
  5. Vaishnavi
    6 years ago

    Is it possible to give voice directions over the app to get to the desired gps loaction?

    ReplyCancel
  6. bayu
    6 years ago

    is there any maps turtorial direction using gps?

    ReplyCancel
  7. Anil Kumar GN
    6 years ago

    Hi Narayan, is it possible to get longitude and latitude without internet connection. Thanks in advance.

    ReplyCancel
    • Narayan Prusty
      6 years ago

      Yes, GPS works without Internet.

      ReplyCancel
  8. Robson Curvello
    7 years ago

    I need track 5 vehicles of my work and I need share these information in the other app or web. This is possible?

    ReplyCancel
  9. henry
    7 years ago

    Hello,
    Sorry but this code doesn’t work on XDK…

    ReplyCancel
    • Asiya
      7 years ago

      I agree. Sadly, it doesn’t work for me either. Could you please advise further? :(

      ReplyCancel
      • Mariha
        5 years ago
        ReplyCancel
  10. Vinayak
    7 years ago

    If you don’t mind please provide a link to download project (ZIP file)…

    ReplyCancel

Leave a Reply to agir Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

Image7 years ago 15 Comments Cordova
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
  • Including Cordova Geolocation Plugin
  • Find User’s Current Position
  • Displaying Google Map and Marking User Position
  • Watching User’s Position Continuously
Related Articles
  • Share Button for Intel XDK APP
  • Integrate Google Analytics in Intel XDK APP
  • Create a Chat App using Intel XDK and XMPP
  • Record Microphone Audio using Intel XDK
  • Record Video using Intel XDK
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license