Recently I started developing Mobile applications using Apache Cordova. In this blog, let me share how we used the Geolocation plugin in Cordova application and displayed the current location of the device.
From Apache Cordova plugin – Geolocation:
Geolocation provides information about the device’s location, such as latitude and longitude. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs. There is no guarantee that the API returns the device’s actual location.
Now, let’s see how to use it:
- The first step is to add the Geolocation plugin via command line to your Cordova application.
The following command applies to all platforms, but there are some platform specific configuration to be added.
[source language=”ruby”]
cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-geolocation.git
[/source] - Next we need to add platform specific settings.
- For Android we need to add the following configuration settings
(in app/res/xml/config.xml)
[source language=”ruby”]
[/source]
(in app/AndroidManifest.xml)
[source language=”ruby”]
[/source] - For iOS we need to add the following configuration settings
(in config.xml)
[source language=”ruby”]
[/source]
- For Android we need to add the following configuration settings
- To get the device’s current location latitude and longitude, we can use navigator.geolocation.getCurrentPosition which can be used inside the deviceReady method.
By using the current ‘position’ object, we can then use Google geocoder to address details like street, state, city and country.
Here is the code sample for it.
[source language=”ruby”]
navigator.geolocation.getCurrentPosition(onSuccess, onError);
function onSuccess(position) {
var element = document.getElementById(‘geolocation’);
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
geocoder.geocode({‘latLng’: latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var result = results[0];
var city = “”;
var state = “”;
for(var i=0, len=result.address_components.length; i= 0) city = ac.long_name;
}
//only report if we got Good Stuff
if(city != ”) {
console.log(“Your current location is “+ city);
}
}
});
}
function onError(error) {
alert(‘message: ‘ + error.message + ‘\n’);
}
[/source]
Hope you find this blog post useful, If you have any question please post it as a comment.