Using Cordova Plugin in your App

Plugin can be integrated into your application through command line. After adding platform, we pass another command to integrate plugin(optional).

For Example:

To add Camera plugin, type cordova plugin add cordova-plugin-camera.

Plugin Integration

Above command will add Camera plugin, now you can use functions to call it.

Plugin Integration


Using GeoLocation Plugin

Let's create an app which collects your location coordinates and show it on Google Map. We have already created an app with Google Map integration, now we will create another application which will show your device's location on Google Map.

  1. Create project.
  2. Add platform → android
  3. Add geolocation plugin - Type cordova plugin add cordova-plugin-geolcation and press enter.
  4. Now write the following code in your index.html file and put it in www directory in the project folder.

    <html>
        <head>
        <style type="text/css">
            #map_area {
    	    position:fixed;
    	    height:100%;
    	    width:100%;
    	    top:0;
    	    left:0;
            }
        </style>
        <script type="text/javascript">
        function getLocation() {
            if (navigator.geolocation) {
        	    function showLocation(position) {
                    var latitude = position.coords.latitude;
                    var longitude = position.coords.longitude;
                }
                navigator.geolocation.getCurrentPosition(showPosition);
            } 
            else {
                alert('Not allowed by device');
            }
        }
    
        function showPosition(position) {
            var lat = (position.coords.latitude);
            var long = (position.coords.longitude);
    
            start(lat, long);
        }	
    
        function start(lat, long) {
            var latlong = {lat: lat, lng: long};
            var map = new google.maps.Map(document.getElementById('map_area'), {
              zoom: 15,
              center: latlong
            });
            var marker = new google.maps.Marker({
              position: latlong,
              map: map
            });
         }
        </script>
        </head>
        <body>
            <div id="map_area"></div>
            <script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=getLocation"><script>
    
        </body>
    </html>
    

    After the script loads successfully, it will call geo Location function. This function requests the device to grant the required permission. If the device grants permission, it will pass the latitude and longitude to start function. And your device location will be shown on the map.