location in Ionic project for android - android

In a simple Ionic app I have to get current location on map. It's works fine in browser when i click find me, but it's not working on actual Android device.
I'm using the following code
View.html
<ion-view view-title="{{navTitle}}">
<ion-content>
<div id="map" data-tap-disabled="true"></div>
</ion-content>
<ion-footer-bar class="bar-stable">
<a ng-click="centerOnMe()" class="button button-icon icon ion-navigate">Find Me</a>
</ion-footer-bar>
</ion-view>
controllers.js
.controller('googlemap', function($scope, $ionicLoading, $compile) {
$scope.navTitle = 'Google Map';
$scope.$on('$ionicView.afterEnter', function(){
if ( angular.isDefined( $scope.map ) ) {
google.maps.event.trigger($scope.map, 'resize');
}
});
function initialize() {
//var myLatlng = new google.maps.LatLng(43.07493,-89.381388);
var myLatlng = new google.maps.LatLng(18.520430300000000000,73.856743699999920000);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
//Marker + infowindow + angularjs compiled ng-click
var contentString = "<div><a ng-click='clickTest()'>Click me!</a></div>";
var compiled = $compile(contentString)($scope);
var infowindow = new google.maps.InfoWindow({
content: compiled[0]
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Pune(India)'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
$scope.map = map;
}
initialize();
$scope.centerOnMe = function() {
if(!$scope.map) {
return;
}
$scope.loading = $ionicLoading.show({
content: 'Getting current location...',
showBackdrop: false
});
navigator.geolocation.getCurrentPosition(function(pos) {
$scope.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
$scope.loading.hide();
}, function(error) {
alert('Unable to get location: ' + error.message);
});
};
$scope.clickTest = function() {
alert('Example of infowindow with ng-click')
};
})
Also in my device on the device Location but still I have problem.I got following output on my screen for long time.

Isn't it easier to just use the ngCordova $cordovaGeoLocationPlugin ? You can get the position from this plugin ( latitude and longitude) and then pass this in GoogleAPI. I think it will be lot easier that way.
ngCordova geoLocationPlugin
Just a suggestion.

This example works perfect in case you start the app with GPS on. But starting with GPS off in you device, and after that, entering in the app and selecting GPS on, the function returns always GPS timeout ERROR = 3. Any solution for that?
I have posted this error here:
When I start the App with GPS off , and later GPS is activated, Location is not detected

Related

How to download and get offline tiles in ionic 3 android app?

I am trying to develop a hybrid ol3 map application using ionic3 with angularjs. I have generated xyz tiles of the map service which I was able to use for online maps. When I tried using them for download to a local directory of mobile and use them I am facing issues. Kindly provide any help which is much appreciated. I I could not trace any errors. Kindly suggest me how to check if any errors to test the maps.
//For downloading the image from server and stores it into mobile directory.
this.file.createDir(this.file.externalRootDirectory, 'Offline/Maps/custom_', true).then((files) => {
this.file.createDir(this.file.externalRootDirectory, 'Offline/Maps/custom_/02_02', true).then((files) => {
}).catch((err) => {
});
}).catch((err) => {
});
const imageURL = 'https://server.com/documents/ionic/path_track/maps/0041_0041.jpeg';
const fileTransfer: FileTransferObject = this.transfer.create();
const imageName = imageURL.split('/').pop();
//alert(imageName+"#"+this.file.externalRootDirectory);
//alert(imageName);
fileTransfer.download(imageURL, this.file.externalRootDirectory+'Offline/Maps/custom_07/02_02/'+imageName).then((entry) => {
//loader.dismiss();
//this.showOfflineButton = true;
}, (error) => {
let alert = this.alertCtrl.create({
message: 'Map is not downloaded '+JSON.stringify(error),
buttons: ['Ok'],
enableBackdropDismiss: false,
cssClass:'alert-error'
});
alert.present();
});
//For retrieving image from the mobile directory and to display into mobile app.
var config = {
"bounds": {
"left" : 68.1060582899974,
"bottom" : 6.72246026992798,
"right" : 97.7525939941406,
"top" : 37.0967391635301
}
};
var bounds = [config.bounds.left, config.bounds.bottom, config.bounds.right, config.bounds.top];
var resolutions = [
0.1186495269281333,
0.0593247634640666,
0.0296623817320333,
0.0148311908660167,
0.0074155954330083,
0.0037077977165042,
0.0018538988582521,
0.000926949429126,
0.000463474714563,
0.0002317373572815,
0.0001158686786408,
0.0000579343393204,
0.0000289671696602,
0.0000144835848301,
0.000007241792415
];
var projection_epsg_no = 4326
var layername = 'seamless_xyz1';
var tileGrid = new ol.tilegrid.TileGrid({
extent: bounds,
resolutions: resolutions,
origin: ol.extent.getTopLeft(bounds),
projection: 'EPSG:4326',
tileSize: [256, 256]
});
var view = new ol.View({
extent: [55.948355423604156, 4.853611184459009, 101.73937104860416, 38.07626743445901],
zoom: 10,
center: [78.48695, 17.41217],
projection: 'EPSG:4326',
resolutions: resolutions
});
var tms_source = new ol.source.XYZ({
projection: 'EPSG:4326',
tileGrid: tileGrid,
url: this.file.externalRootDirectory+'/Offline/Maps/custom_{z}/{x}/{-y}.jpeg'
//url: this.file.externalRootDirectory+'/Offline/Maps/custom_07/02_02/0041_0043.jpeg' (If I am giving static image name then its coming fine but not able to do it dynamically.)
});
var basegroup = new ol.layer.Tile({
source: tms_source,
extent: bounds
});
var mapview;
if(this.Source_lat == undefined || this.Source_long == undefined){
this.current_location1 = 'Location is not available.';
mapview = new ol.View({
projection: 'EPSG:4326',
center: [82.491,21.899],
extent: [66.2329, 7.68083, 98.2223, 39.03874],
maxZoom:16,
minZoom: 8,
zoom: 8
});
}else{
this.current_location1 = this.Source_lat+', '+this.Source_long;
mapview = new ol.View({
projection: 'EPSG:4326',
center: [this.Source_long,this.Source_lat],
extent: [66.2329, 7.68083, 98.2223, 39.03874],
maxZoom:10,
minZoom: 10,
zoom: 10
});
}
map = new ol.Map({
target: 'offline_map',
controls: ol.control.defaults({
zoom: false,
attribution: false,
rotate: false
}),
layers: [basegroup, jsonLayer_net1, jsonLayer_net],
overlays: [jsonoverlay],
view: mapview
});
Thanks in advance

LocationService ionic google-maps object failing for ios, but works in android

I have found on android that using geolocation from Google Maps JavaScript API and from the Ionic Framework has caused issues of being very slow or not working at all. I then found a second geolocation module for Ionic called LocationService, from this documentation: https://github.com/ionic-team/ionic-native-google-maps/blob/master/documents/locationservice/README.md. The issue that I am having is although this Location module is working for Android, it is not working on ios or by serving the app on localhost. Below is the error that I am getting and my code that sets the map's center. I am editing this.
map.html:
<ion-header>
<ion-navbar>
<ion-title>
Map
</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<div id='map'></div>
</ion-content>
map.ts:
import { Component, ViewChild, ElementRef } from '#angular/core';
import { NavController, Platform, Navbar } from 'ionic-angular';
import { Geolocation } from '#ionic-native/geolocation';
import {
LocationService,
GoogleMap,
GoogleMapOptions,
MyLocation,
GoogleMaps
} from '#ionic-native/google-maps';
declare var google: any;
#Component({
selector: 'page-map',
templateUrl: 'map.html',
})
export class OfficeLocatorPage {
#ViewChild(Navbar) navBar: Navbar;
map: any;
mapOptions:any;
trafficEnabled = false;
transitEnabled = false;
bicycleEnabled = false;
markers = [];
places = [];
trafficLayer = new google.maps.TrafficLayer();
transitLayer = new google.maps.TransitLayer();
bicycleLayer = new google.maps.BicyclingLayer();
myLocation: any;
infoWindow: any;
isInfoWindowShown: boolean = false;
constructor(private navCtrl: NavController, private platform: Platform, private geolocation: Geolocation) {
}
ionViewDidLoad() {
this.navBar.backButtonClick = (e:UIEvent)=>{
this.navCtrl.pop({animate: true, animation: "transition", direction: "left", duration: 300});
};
}
ionViewDidEnter() {
this.platform.ready().then(() => {
this.places = [];
this.initMap(this);
});
}
initMap(scopeObj) {
LocationService.getMyLocation({enableHighAccuracy: true}).then((location: MyLocation) => {
this.setLocation(location.latLng);
}).catch((error: any) => {
// Can not get location, permission refused, and so on...
console.log(error);
});
}
setLocation(location) {
this.map = new google.maps.Map(document.getElementById('map'), {
center: location,
zoom: 10,
disableDefaultUI: true
});
let image = {
url: "assets/icon/blue_dot.png", // url
scaledSize: new google.maps.Size(25, 33), // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point(0, 0) // ancho
};
let marker = new google.maps.Marker({
position: location,
map: this.map,
icon: image
});
this.myLocation = new google.maps.LatLng(location.lat, location.lng);
}
Error log:
Error: Uncaught (in promise): TypeError: Cannot read property 'LocationService' of null
TypeError: Cannot read property 'LocationService' of null
at http://localhost:8100/build/vendor.js:78338:35
at new t (http://localhost:8100/build/polyfills.js:3:21506)
at Function.LocationService.getMyLocation
The error seems to only show when serving the app in a web browser, Xcode just needed to be cleaned and rebuilt, so the map shows up and works now. I don't believe that it will work on the browser when running the command "ionic serve", because LocationService is an ionic native module and can't be used unless the app is installed on Android or iOS.

Displaying phone's geo location on screen with ionic

I'm learning ionic and I'm having trouble displaying my Android phone's geo location (lat and long) on screen. How can I do this?
Code take from https://www.tutorialspoint.com/ionic/ionic_geolocation.htm
.controller('GeoCtrl', function($scope, $cordovaGeolocation) {
$scope.result = "";
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var lat = position.coords.latitude;
//$scope.geo.lat = position.coords.latitude;
var long = position.coords.longitude;
//$scope.geo.long = position.coords.longitude;
console.log(lat + ' ' + long)
$scope.geo = lat + ' ' + long;
}, function(err) {
console.log(err)
});
})
And here's the html where i just want the geo location to be displayed:
<ion-view view-title="Submit New Thing">
<ion-content class="padding">
<h2>List of items for sale</h2>
<div >
<h3> Geo locaton is {{geo}}</h3>
</div>
</ion-content>
</ion-view>
When I test on my phone {{geo}} is literally displayed.
Answer: I didn't have the ngCordova dependency injected into the app.

ionic apk file not getting location but the system show location

When I am running ionic apk file in mobile I'm not getting my location but the system show location. What is the problem?
Module.js file
angular.module('ionic.example', ['ionic'])
.controller('MapCtrl', function($scope, $ionicLoading, $compile) {
function initialize() {
var myLatlng = new google.maps.LatLng(43.07493,-89.381388);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
//Marker + infowindow + angularjs compiled ng-click
var contentString = "<div><a ng-click='clickTest()'>Click me!/a></div>";
var compiled = $compile(contentString)($scope);
var infowindow = new google.maps.InfoWindow({
content: compiled[0]
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Uluru (Ayers Rock)'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
$scope.map = map;
}
google.maps.event.addDomListener(window, 'load', initialize);
$scope.centerOnMe = function() {
if(!$scope.map) {
return;
}
$scope.loading = $ionicLoading.show({
content: 'Getting current location...',
showBackdrop: false
});
navigator.geolocation.getCurrentPosition(function(pos) {
$scope.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
$scope.loading.hide();
}, function(error) {
alert('Unable to get location: ' + error.message);
});
};
$scope.clickTest = function() {
alert('Example of infowindow with ng-click')
};
});
Here it is not working after installing apk file. On clicking the find me button it is loading ..... but not showing location
This is my code. When I run the browser it is working fine but after build apk file it is not showing details. Can you guys tell me the what the reason is?
The permissions are set correctly in your androidManifest? you need:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Try to connect the device to pc and use chrome://inspect to see the error.

Cant find user location when apk installed on android phone

I have created an ionic angularjs ngCordova mobile app, wherein I have used ngCorodova geolocation plugin in order to get user location. when I am testing this on browser it works fine. but when same I [android-app.apk] I install on mobile app [obviously after checking "unknown sources" option]; I am not able to get the location. I see in app setting, permission is there to access location on mobile. Also, When event is trigerred it shows GPS symbol on top bar but it disappears.
Can anybody help me with this?
Below is the code for location in my controller.js
.directive('reverseGeocode', function ($cordovaGeolocation, $rootScope) {
return {
restrict: 'E',
template: '<div></div>',
link: function (scope, element, attrs) {
var geocoder = new google.maps.Geocoder();
var posOptions = {timeout: 10000, enableHighAccuracy: true};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var lati = position.coords.latitude;
var longi = position.coords.longitude;
// console.log(angular.toJson($rootScope.lati) + " - " );
var request = new XMLHttpRequest();
var method = 'GET';
//var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+long+'&sensor=true';
var async = true;
//alert(url);
//request.open(method, url, async);
//alert(angular.toJson(request.open(method, url, async)));
// var data = JSON.stringify(request.responseText);
// alert(JSON.stringify(request.responseText));
var latlng = new google.maps.LatLng(lati, longi);
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
//alert(results[1].address_components[1].long_name);
$rootScope.colony = results[1].address_components[1].long_name;
//alert(results[1].address_components[1].long_name);
//alert(results[1].address_components[1].long_name);
//alert(angular.toJson(results[1].address_components[1].long_name));
element.text(results[1].formatted_address);
} else {
element.text('Location not found');
}
} else {
element.text('Geocoder failed due to: ' + status);
}
});
}, function(err) {
// error
});
var watchOptions = {
frequency : 1000,
timeout : 3000,
enableHighAccuracy: false // may cause errors if true
};
var watch = $cordovaGeolocation.watchPosition(watchOptions);
watch.then(
null,
function(err) {
// error
},
function(position) {
var lat = position.coords.latitude
alert("abc >>" + lat);
var long = position.coords.longitude
});
watch.clearWatch();
// OR
$cordovaGeolocation.clearWatch(watch)
.then(function(result) {
// success
}, function (error) {
// error
});
},
replace: true
}
})
In html file I am using it as :
<h6>
User Colony: {{ colony }}
<reverse-geocode lat={{lati}} lng={{longi}}></reverse-geocode>
</h6>
<a href="#" ng-click="showStores(colony)" class="button button-block button-positive">
Browse Store
</a>
which triggeres the directive and find lat and long of user.
When testing on browser, it works perfectly but not on mobile itself.
In android it is super complicated to work with the GPS user, remember that often the geolocation we get is from the browser and not the GPS itself, and this varies a lot in the devices. For your help, I recommend installing cordova.plugins.diagnostic
function onDeviceReady() {
cordova.plugins.diagnostic.isLocationAuthorized(function(enabled){
//alert("gps es : " + (enabled ? "enabled" : "disabled"));
}, function(error){
//alert("error: "+error);
});
cordova.plugins.diagnostic.isLocationEnabled(function(enabled){
if(!enabled){
alert("gps not actived");
}else{
navigator.geolocation.getCurrentPosition(onSuccess, onError, {enableHighAccuracy: true,timeout: 5000,maximumAge: 5000});
}
}, function(error){
console.log("The following error occurred: "+error);
});
}
Always trying to see if I can get a latitude and longitude and if that is not activated or not you can get, it sends a message to the user. I hope it helps you.

Categories

Resources