Friday 24 June 2016

get current location in android example code.

Below demonstration is in Visual Studio 2015, cordova application to get the current location in android. It will give the overview that how you will get your current location in google map. Like Below.


Follow the below steps to get current location in android code.
1.       Create A corodova application like below.



2.       You will get the below list of files.

3.       Place the below code into index file. Here the map will be display in div  having the id as “map”. It will work as view for you in android application. [Example Code]

<html>
<head>
    <meta charset="utf-8" />
    <title>Get My location</title>
    <link href="css/index.css" rel="stylesheet" />
</head>
<body>

    <!-- Cordova reference, this is added to your app when it's built. -->
    <script src="cordova.js"></script>
    <script src="scripts/platformOverrides.js"></script>
    <script type="text/javascript" src="scripts/jsapi"></script>
    <script src="scripts/jquery.min.js"></script>
    <script src="scripts/index.js"></script>
    <script src="scripts/MapHelper.js"></script>
    <script type="text/javascript">
       
      
        $(document).ready(function () {
            document.addEventListener("deviceready", onDeviceReady, false);
        });
      
    </script>


    <div data-role="page" id="index">
        <div data-role="header" data-theme="b"></div>
        <div data-role="content" style="padding:0;">
            <div id="map" style="width:100%;height:100%;"></div>
        </div>
        <div data-role="footer" data-theme="b"></div>
    </div>

</body>
</html>

4.       Create a new javascript file and place your javascript code which will help you to load google map in android application. [Example Code]

var map;
var marker;
var marker1;
var infowindow;
var watchID;

//Onloading of your page, phonehap device ready function
function onDeviceReady() {
    $(window).unbind();
    $(window).bind('pageshow resize orientationchange', function (e) {
        max_height();
    });
    max_height();
    google.load("maps", "3", { "callback": map, other_params: "sensor=true&language=en" });
}

// Calculate Height for your map
function max_height() {
    var topheader = $('div[data-role="header"]').outerHeight(true);
    var footer = $('div[data-role="footer"]').outerHeight(true);
    var w = $(window).height();
    var c = $('div[data-role="content"]');
    var c_h = c.height();
    var c_oh = c.outerHeight(true);
    // var c_new = w - h - f - c_oh + c_h;
    var c_new = w - footer - c_oh + c_h;
    var total = topheader + footer + c_oh;
    if (c_h < c.get(0).scrollHeight) {
        c.height(c.get(0).scrollHeight);
    } else {
        c.height(c_new);
    }
}

function map() {
    var latlng = new google.maps.LatLng(20.59, 78.96);
    var myOptions = {
        zoom: 20,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        zoomControl: true
    };
    map = new google.maps.Map(document.getElementById("map"), myOptions);

    google.maps.event.addListenerOnce(map, 'tilesloaded', function () {
        //get geoposition once
        watchID = navigator.geolocation.watchPosition(geo_success, geo_error, { maximumAge: 500, timeout: 500, enableHighAccuracy: true });
    });
}

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

//function geo_success() {
function geo_success(position) {

    map.setCenter(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));

    var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    var geocoder = geocoder = new google.maps.Geocoder();
    var address = "";
    var info =  ('Latitude: ' + position.coords.latitude + '<br>' +
               'Longitude: ' + position.coords.longitude + '<br>' +
               'Altitude: ' + position.coords.altitude + '<br>' +
               'Accuracy: ' + position.coords.accuracy + '<br>' +
               'Timestamp: ' + new Date(position.timestamp));
   
   
    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
                $('div[data-role="header"]').html(results[1].formatted_address);
            }
        }
    });


     var point = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    if (!marker) {
        //create marker
        marker = new google.maps.Marker({
            position: point,
            map: map,
            icon: 'http://maps.google.com/mapfiles/arrow.png'
        });
     
    } else {
        //move marker to new position
        marker.setPosition(point);
    }

    if (!infowindow) {
        infowindow = new google.maps.InfoWindow({
            content: info
        });
    } else {
        infowindow.setContent(info);
    }
    google.maps.event.addListener(marker, 'click', function () {
        infowindow.open(map, marker);
    });

}


5.       Need to give the permission to access the GPRS. Click on config.xml and in plugin select geolocation and click on right side button add.

Final result you will see your current location in android.




2 comments:

  1. Is It VS2015 Enterprise ? Becuase i dont see option for Cordova under javascript template.

    ReplyDelete
    Replies
    1. please use below link to create first application in VS2015 for mobile application. I Used Community version.[It is free of cost]
      http://www.getmscode.com/2017/01/develop-android-apps-using-visual.html

      Delete