Build a real-time location tracker using Wia
Stream location data to the Wia Cloud Platform and subsequently display real-time location in an iPhone Application using the Wia iOS SDK. The project also comes with some simple project files to get you started.
Project Requirements- Node.js and NPM must be installed. How to install Node.js on a Raspberry Pi.
- A Wia account. You can create one for free here.
- First thing you will want to do is to create a folder on your location device. Let's call it
wia-location-device
.
- Go into the folder and initialise the project by creating a package.json file using the command "
npm init
" (use defaults for everything).
- Install the Wia SDK using the command "
npm install --save wia
".
- Your
package.json
file should look something like the code below.
{
"name": "wia-location-device",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Your Name Here",
"license": "ISC",
"dependencies": {
"wia": "^1.3.3"
}
}
Creating your Location Tracking Device- Go to the Wia dashboard and select Devices.
- From here, click on the + symbol and the Add New Device modal will appear.
- Enter '
Location Device
' as the name and click Add Device.
- Click on View device to go to the device's overview page.
Take a note of the device's secret key, we'll need this later.
Write code for the location tracking device- We need to create a file for our program, let's call it
index.js
- Copy the code from the example below add to the
index.js
file.
- Replace the
device-secret-key
on line 3 with your device's secret key that you made a note of earlier.
- Now to test that you have done your setup correctly, simply run
node index.js
- Your device should have updated in the dashboard under the Location tab, with your sensor readings. You can also view in in real-time in the Debugger tab.
'use strict'
var wia = require('wia')('device secret key');
// collection of cities
var cities = [{"city":"Dublin","lat":53.349805,"lng":-6.260310},
{"city":"London","lat":51.5013673,"lng":-0.1440787},
{"city":"Paris","lat":48.8922431,"lng":2.2380753},
{"city":"Toronto","lat":43.6426731,"lng":-79.3928402}];
// Using the MQTT stream
wia.stream.on('connect', function() {
console.log('Stream connected!');
// randomly choosing city location to publish
var random = Math.floor(Math.random() * 4);
var randomcity = cities[random];
// value to increment position
var diff = 0.0005;
// setting the interval at which to publish location i.e. every second
setInterval(function() {
// function to publish location data
wia.locations.publish(
{
"latitude": randomcity.lat + diff,
"longitude": randomcity.lng + diff,
"altitude": 2
},
function(err, published) {
if (err) console.log(err);
if (published) console.log("Location published.");
}
);
diff += 0.0005;
}, 3500);
});
wia.stream.connect();
NOTE: You can replace the values of the 'randomcity' variable with values from a GPS module or any other location tracking modules.
Creating our iOS appBefore we get started, make sure you have the latest version of Xcode.
- Open Xcode and go to File > New > Project.
- Choose iOS > Single Page Application and click Next.
- Give it the product name "
location-tracker-app
".
- Make sure that the language selected is Objective-C and the devices is set to iPhone.
- Uncheck Use Core Data, Include Unit Tests, and Include UI Tests checkboxes and click Next.
- Choose the repository where you want to create the project (Remember this repository location for later) and click Create.
- If you don't already have the CocoaPods tool, install it on macOS by running the command "sudo gem install cocoapods" from the terminal. For details, see the CocoaPods Getting Started guide.
- Next, navigate to your project directory in your terminal and run the command "nano Podfile".
- Insert code from the attached Podfile, and save the file.
- Next, run the command "pod install".
- Go to the Google API Console.
- Create or select a project.
- Click Continue to enable the Google Maps SDK for iOS.
- On the Credentials page, get an API key. Note: If you have a key with iOS restrictions, you may use that key. You can use the same key with any of your iOS applications within the same project.
- From the dialog displaying the API key, select Restrict key to set an iOS restriction on the API key.
- In the Restrictions section, select iOS apps, then enter your app's bundle identifier.
- Click Save.
- Your new iOS-restricted API key appears in the list of API keys for your project.
- Go to the
AppDelegate.m
file and add the following code "@import GoogleMaps;" to the header of the file.
- Add the following to your application's didFinishLaunchingWithOptions method, replacing YOUR_API_KEY with your API key: [GMSServices provideAPIKey:@"YOUR_API_KEY"];
To declare the URL schemes used by the Google Maps SDK for iOS, add the following lines to your Info.plist:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>googlechromes</string>
<string>comgooglemaps</string>
</array>
OR
Add them through the Xcode interface.
- Update your
AppDelegate.m
code with the code below, replacing the "maps api key" with your Google Maps API key.
#import "AppDelegate.h"
@import GoogleMaps;
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[GMSServices provideAPIKey:@"maps api key"];
return YES;
}
@end
- Update your
ViewController.h
file to match the code below.
#import <UIKit/UIKit.h>
#import "Wia.h"
#import <GoogleMaps/GoogleMaps.h>
@interface ViewController : UIViewController <WiaClientDelegate>
@end
- Next, update your
ViewController.m
file match the code below.
#import "ViewController.h"
#import <GoogleMaps/GoogleMaps.h>
@interface ViewController ()
@property GMSMapView *mapView;
@property GMSCameraPosition *camera;
@property GMSMarker *marker;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[WiaClient debug:YES];
[[WiaClient sharedInstance] setDelegate:self];
[[WiaClient sharedInstance] initWithToken:@"Your user secret key"];
[[NSNotificationCenter defaultCenter] addObserverForName:@"WiaStreamConnect" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
NSLog(@"CONNECTED TO STREAM");
[[WiaClient sharedInstance] subscribeToLocations:@{@"device": @"Your device id"}];
}];
[[WiaClient sharedInstance] connectToStream];
self.camera = [GMSCameraPosition cameraWithLatitude:0.000000
longitude:0.000000
zoom:16];
self.mapView = [GMSMapView mapWithFrame:CGRectZero camera:self.camera];
self.mapView.myLocationEnabled = YES;
self.view = self.mapView;
// Creates a marker in the center of the map.
self.marker = [[GMSMarker alloc] init];
self.marker.title = @"Location Device";
self.marker.map = self.mapView;
}
- (void)newLocation:(WiaLocation *)location {
CLLocationCoordinate2D coordinates;
coordinates.latitude = [location.latitude doubleValue];
coordinates.longitude = [location.longitude doubleValue];
GMSCameraUpdate *updatedCamera = [GMSCameraUpdate setTarget:coordinates zoom:13];
[self.mapView animateWithCameraUpdate:updatedCamera];
self.marker.position = CLLocationCoordinate2DMake([location.latitude doubleValue], [location.longitude doubleValue]);
}
@end
- Replace the "Your user secret key" placeholder with your user secret key which can be located in the Wia Dashboard in the My account > Security tab.
- Replace the Your device id placeholder with the device id of your device from the dashboard which can be found in the Device > Settings tab.
- Now, simply build your project and it should run smoothly.
Congratulations
You just build a location tracker app!
Comments