Cordova Google Maps

cordova-google-maps-example

In this tutorial, I'm going to explain how to Integrate Google Map with Phonegap / Apache Cordova based Projects.

Step by Step Guide:

1. Create Cordova Project:

cordova create GMapExample com.codesundar.gmapexample GMapExample

2. Change Working Directory

cd GMapExample

3. Add Platform

cordova platform add android
cordova platform add ios

4. Add Plugin https://github.com/apache/cordova-plugin-geolocation

cordova plugin add cordova-plugin-geolocation

5. Add Google Map JavaScript Library with your index.html

<script src="http://maps.google.com/maps/api/js" type="text/javascript"></script>

6. Get User's location using Geolocation plugin

navigator.geolocation.getCurrentPosition(onSuccess, onError, {
    timeout: 30000
});

function onSuccess(position) {
    var lat = position.coords.latitude;
    var lang = position.coords.longitude;
}

function onError(error) {
    alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}

Integrate Google Map with PhoneGap Full Code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Geo Location</title>
    <style type="text/css">
        html {
            height: 100%
        }

        body {
            height: 100%;
            margin: 0;
            padding: 0
        }

        #map-canvas {
            height: 100%
        }
    </style>
    <script type="text/javascript" src="cordova.js"></script>
    <script src="http://maps.google.com/maps/api/js" type="text/javascript"></script>
    <script type="text/javascript">
        navigator.geolocation.getCurrentPosition(onSuccess, onError, {
            timeout: 30000
        });

        function onSuccess(position) {
            var lat = position.coords.latitude;
            var lang = position.coords.longitude;

            //Google Maps
            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');
        }
        google.maps.event.addDomListener(window, 'load', onSuccess);
    </script>
</head>

<body>
    <div id="map-canvas"></div>
</body>

</html>

7) Build your project & Run it

    cordova build android

Not Working ?

  • Check your Internet connection
  • Make sure, you've enabled "Location Option" under your Phone Settings