Easy Code Share > Cordova > How Cordova Geolocation Locate Google Map in APP

How Cordova Geolocation Locate Google Map in APP


Cordova Geolocation gets latitude, longitude, and even altitude. It is enough to locate you on Google Maps. Cordova let you use JavaScript to reach the goal in mobile phones, instead of native codes on Android or iOS. The article guide you to go through Cordova project building process for an example about GPS locating and Google Maps.

All codes here are not complicated, so you can easily understand even though you are still students in school. To benefit your learning, we will provide you download link to a zip file thus you can get all source codes for future usage.

Estimated reading time: 6 minutes

 

 

BONUS
Source Code Download

We have released it under the MIT license, so feel free to use it in your own project or your school homework.

 

Download Guideline

  • Prepare HTTP server such as XAMPP or WAMP in your windows environment.
  • Download and unzip into a folder that http server can access.
 DOWNLOAD SOURCE

 

SECTION 1
Cordova Geolocation Plugin

Apart from standard HTML and Javascript, Cordova needs interfaces to connect to native components such as batteries, network, and especially geographical data. Cordova Plugins play the role. Also, we show how to install Cordova Geolocation Plugin here.

 

Cordova Plugin

Our previous article has talked about this topic. What is Cordova Plugin? Through plugins, Cordova communicates with native components including hardware devices.

Cordova Geolocation Plugin gets GPS coordinates of mobile phone, representing as latitude and longitude. When using the information on Google Maps, you will find where you are in the real world. The result received from GPS even indicates altitude and speed if you are moving.

 

Install Geolocation Plugin

When you create a Cordova project, in Cordova project folder such as c:\geoloc in this article, issue Cordova CLI command lines to add Android platform, and then install Geolocation Plugin as the following,

c:\>cordova create geoloc com.easycodeshare.geoloc GeoLocation
c:\>cd geoloc
c:\geoloc>cordova platform add android
c:\geoloc>cordova plugin add corodva-plugin-geolocation

Where geoloc indicates PATH, com.easycodeshare.geoloc represents Android ID, and GeoLocation is human-readable NAME. You can find all these arguments in geoloc/config.xml. Refer to procedure of building Cordova APPs for more details.

 

SECTION 2
Cordova APPs Get Geo Location

Do you know why you can get global position of mobile phones? The GPS chip inside phones receives data from satellites. Cordova-created APPs get these information by using the Geolocation Plugin, and then put a marker on Google Maps.

 

Cordova Plugin Access GPS Chip

GPS is a radio navigation system. It uses radio waves between satellites and a receiver inside your phone to provide location and time information to any software that needs to use it. You don’t have to send any actual data back into space for GPS to work; you only need to be able to receive data from four or more of the 28 satellites in orbit that are dedicated for geolocation use.

Let’s see how Cordova Geolocation Plugin read information from receiver chip. First, put example source codes into geoloc/www folder as below.

Put GeoLocation Project Files into www folder

When Android starts up and triggers onDeviceReady(), the navigator.geolocation.getCurrentPosition() is called with callback functions for success and failure as parameters.

index.js
function onDeviceReady() {
    console.log('Running cordova-' + cordova.platformId + '@' + cordova.version);
    navigator.geolocation.getCurrentPosition(onSuccess, onError);
}

Success callback function shows dialog box with GPS coordinates and relevant data, which will be drawn on Google Maps in this example.

Information from Cordova Geolocation

index.js
var YOUR_KEY = "";
var onSuccess = function(pos) {
	latitude = pos.coords.latitude;
	longitude = pos.coords.longitude;
	alert('Latitude: '          + pos.coords.latitude          + '\n' +
		  'Longitude: '         + pos.coords.longitude         + '\n' +
		  'Altitude: '          + pos.coords.altitude          + '\n' +
		  'Accuracy: '          + pos.coords.accuracy          + '\n' +
		  'Altitude Accuracy: ' + pos.coords.altitudeAccuracy  + '\n' +
		  'Heading: '           + pos.coords.heading           + '\n' +
		  'Speed: '             + pos.coords.speed             + '\n' +
		  'Timestamp: '         + pos.timestamp                + '\n');
    $.getScript("https://maps.googleapis.com/maps/api/js?key="+YOUR_KEY+"&callback=gMap");
};

 

From GPS to Google Maps

Left screen indicates Google Maps API key YOUR_KEY is null. Even though you didn’t apply to API key, you can use Google Maps in development mode. Right screen combines Cordova Geolocation and Google Maps to show where you are. Zoom in to see more accurate position.

Cordova Geolocation Plus Google Maps

The jQuery $.getScript() in success callback function invoke Google Maps with another callback callback=gMap. The function gMap() retrieves global variables representing latitude and longitude in which previous callback function has set value, and then center you in the map. Finally, a JavaScript object with {position: mapProp.center} marks your position for visibility.

index.js
var latitude = 0;
var longitude = 0;
...
function gMap() {
	//show map
	var mapProp= {
	  center:new google.maps.LatLng(latitude, longitude),
	  zoom:5,
	};
	var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
	//mark position
	var marker = new google.maps.Marker({position: mapProp.center});
	marker.setMap(map);
}

Let’s go back to HTML which is based on jQuery Mobile. Remind that you should download jQuery and jQuery Mobile files, and not use jQuery CDN.

index.html
<link rel="stylesheet" href="css/1.4.5/jquery.mobile.min.css">
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/1.4.5/jquery.mobile.min.js"></script>
.....
<div data-role="page" style="background:teal;">
    <div data-role="header">
        <h1>GEO LOCATION</h1>
    </div>
    <div data-role="content">
        <div class="user-data">
        <p>Your Location is shown.</p>
        <div id="googleMap" style="width:100%;height:400px;"></div>
        </div>
    </div>
    <div data-role="footer" data-position="fixed">
        <p style="text-align:center;">Cordova GeoLocation Plugin Test</p>
    </div>
</div>

 

Build Cordova APPs

Finally, Cordova allows you to build a APP, Once done, it indicates the long path for resulting APK file like the following.

c:\geoloc>cordova build android
Checking Java JDK and Android SDK versions
ANDROID_SDK_ROOT=undefined (recommended setting)
ANDROID_HOME=undefined (DEPRECATED)
Using Android SDK: C:\Users\user\AppData\Local\Android\sdk
Subproject Path: CordovaLib
Subproject Path: app
Starting a Gradle Daemon (subsequent builds will be faster)
> IDLE
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.5/userguide/command_line_interface.html#sec:command_line_warnings
BUILD SUCCESSFUL in 26s
40 actionable tasks: 40 up-to-date
Built the following apk(s):
        c:\geoloc\platforms\android\app\build\outputs\apk\debug\app-debug.apk

 

FINAL
Conclusion

Cordova projects for geographical locating have a few platform-dependent settings for iOS especially. According to official documents, adding some settings in config.xml will make the APP real hybrid.

The given Geo GPS positions indeed help in a lot of useful applications, such as the APP of How MQTT Plus Cordova GPS APP Track My Family in our articles.

Thank you for reading, and we have suggested more helpful articles here. If you want to share anything, please feel free to comment below. Good luck and happy coding!

 

Suggested Reading

 

TRY IT
Quick Experience

That is all for this project, and here is the link that let you experience the program. Please kindly leave your comments for our enhancement.

 

Try It Yourself

Click here to execute the source code, thus before studying the downloaded codes, you can check whether it is worthy.

2 thoughts on “How Cordova Geolocation Locate Google Map in APP”

Leave a Comment