While building Cross Platform Mobile apps, the developer community is often confused about the technology to use. For example, if Windows Phone apps are to be developed, then a developer must possess C#/VB.NET and XAML skillsets. Similarly for Android apps, JAVA must be a skillset. These languages do have the capability to make use of Mobile Native APIs, and Mobile devices are smart enough to run applications accessing these native APIs. But the challenge here is that, if one single application is to be developed across multiple devices (Windows Phone, Android etc.), then we need to think in terms of a framework that let’s us build cross-platform mobile apps without much efforts.
In a previous article, I had demonstrated how to use Icenium to Develop a Cross Platform Mobile App in Visual Studio using JavaScript & HTML5. Today to develop Cross-Platform mobile apps, we will make use of the free Apache Cordova Framework. This framework provides a set of device APIs that allows a mobile app developer to develop apps using native device functions like Sensor, Camera, Accelerometer etc. These apps can then be deployed on Windows Phone, Android etc.
In Visual Studio, you can get the Windows Phone Template for Cordova, using which we can write applications for Windows Phone using JavaScript and the same code can also be used for Android Development too. In this article, we will discuss the same. The code has been tested on Android Device and Windows Phone Emulator integrated with Visual Studio. The Android Application is developed using Icenium Visual Studio Extension. You can get the details for Windows Phone 8 Cordova template from Apache Cordova Documentation.
In the small example below, the Geolocation application is explained using Google Maps. The URL for referring Google Maps is http://maps.google.com/maps/api/js?sensor=true
Step 1: Open Visual Studio 2012 and create a new Windows Phone 8 Application using Windows Phone 8 Cordova Template as shown below:
The structure of project created will be as below:
In the project structure, the www folder is a repository for all the resources (.css, .html,.js) used for developing the application. The MainPage.xaml contains the CordovaView, which is a UserControl available in cordovalib folder. This user control contains the WebBrowser control. The Cordova.js in the www/js folder represents the Cordova JavaScript library.
Step 2: The index.js inside the www/js folder contains events for the application. It register the ‘deviceready’ event from where the execution starts. For the current application, instead of using the index.js file, we will write the code in index.html. Open index.html and add the following HTML tags in the <body>.
<p>Locate Me</p>
<div id="mapCanvas" style="width:500px;height:380px;"></div>
<input type="button" id="btngelocation" value="Find My Location" />
Step 3: Add the below script reference on the index.html
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
The above reference makes use of Google Map. We can make use of Geolocation API which provided the following asynchronous methods:
- getCurrentPosition - returns the current position of the device.
- watchPosition - watches for changes to the device current position.
- clearWatch – stops watching for the changes to the device location.
Here the position coordinates are received with the following properties:
- Latitude
- Longitude
- Altitude.
- Accuracy.
- AltitudeAccuracy.
- Heading
- Speed.
Step 4: Add the following code in the index.html in the <script> tag:
// Wait for device API libraries to load
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
function onDeviceReady() {
var btn = document.getElementById("btngelocation");
btn.addEventListener('click', getmylocation, false);
}
function getmylocation()
{
navigator.geolocation.watchPosition(onSuccess, onError);
}
// The onSuccess method for Geolocation
function onSuccess(position) {
//Create a Google MAP
var myLatLag = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
//Set option for map so that is use latlng center
var myoptions = { zoom: 14, center: myLatLag, mapTypeId: google.maps.MapTypeId.ROADMAP};
//google map instance
var map = new google.maps.Map(document.getElementById("mapCanvas"), myoptions);
//add marker for our location
var marker = new google.maps.Marker({ position: myLatLag, map: map });
}
// The Callback use to receive a PositionError object
function onError(error) {
alert('Error Code: ' + error.code + ' Error Message: ' + error.message);
}
The above code performs the following tasks:
· The ondeviceready event is fired which reads the button object.
· On the click event of the button, the getmylocation() method is executed.
· The getmylocation() method watches for changes for the device position using the watchPosition() method.
· On the cusses callback the Google MAP object is created based upon the Latitude and Longitude coordinates returned by the watchPosition() method.
· The code also sets the Zoom, Center position and MapTypeId.
· This Map instance is then passed to the <div> with the name ‘mapCanvas’.
· The code also sets the position marker.
Step 5: You need to set the application capabilities for Location. To do that, in the project > Properties click on ‘WMAppManifest.xml’. In the Capabilities Tab select ‘ID_CAP_Location’ and ‘ID_CAP_MAP’ as shown below:
Step 5: Run the application. The application in the Emulator will look similar to the following (You must have Internet configured for the Emulator.)
Note: Since the Emulator uses the fake GMS network, you may not get ththe exact location. To get the exact location, please deploy the application on an actual Windows Phone 8 Device.
I have deployed this app on an Android device using the .apk file. The result on Android is as shown here:
Conclusion: Using JavaScript Capabilities and a framework that supports Cross platform mobile development, it becomes very easy for a developer to build cross platform Mobile applications using Native APIs.
Download the entire source code of this article (Github)
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @
maheshdotnet or connect with him on
LinkedIn