Now we want to add Google Map in our application so we will add Google Maps API it is a JavaScript library.
We will add the following script inside the <head></head> tag.
- <script src="https://maps.googleapis.com/maps/api/js" type="text/javascript"></script>
Now we will find current position of device, display latitude and longitude and integrate Google Maps in our Cordova application by writing the following script inside the
<head></head> tag:
- <script type="text/javascript">
-
- navigator.geolocation.getCurrentPosition(onSuccess, onerror);
-
- function onSuccess(position)
- {
- var element = document.getElementById('geolocation');
- element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + 'Longitude: ' + position.coords.longitude + '<br />' + '<hr />' + element.innerHTML;
- var lat = position.coords.latitude;
- var lang = position.coords.longitude;
- var myLatlng = new google.maps.LatLng(lat, lang);
- var mapOptions = {
- zoom: 4,
- center: myLatlng
- }
-
- var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
-
- var marker = new google.maps.Marker(
- {
- position: myLatlng,
- map: map
- });
- }
-
- function onError(error)
- {
- alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
- }
-
- var watchID = navigator.geolocation.watchPosition(onSuccess, onError,
- {
- timeout: 3000
- });
-
- google.maps.event.addDomListener(window, 'load', onSuccess);
- </script>
Step 9: Build Application
Now we will build this application for an Android phone only using the following command in Node.Js command prompt.
C:\Geo>cordova build android
Step 10: To run this application in an emulator we will use the following command.
C:\Geo>cordova emulate android
Now after building the application we will get .apk file at:
C:\Geo\platforms\android\ant-build\CordovaApp-debug.apk
Now we will use this .apk file in Android mobile and see our Geolocation Mobile App output.
Note: We must have internet connection and mobile GPS on.
Output:
Geolocation App Icon,
Using this App we can see current position of device and find latitude and longitude.
Using this App we can see current position in Google Map
Using this App we can watch continuous changes in current GPS location of device.
Read more articles on Android: