Geolocation on Android with google maps v3 & jQuery Mobile - android

I followed this tutorial http://www.mobiledevelopersolutions.com/home/start/twominutetutorials/tmt4part1 and i have one problem. The geolocation doesn't work on the default Android browser. It does work on Chrome, IE and Chrome for Android. But not the default Android browser.
I think i have to put { enableHighAccuracy: true } somewhere put i can't get it figured out.
This is the code:
var mapdata = { destination: new google.maps.LatLng(51.3704888, 6.1723862) };
// Home page
$('#page-home').live("pageinit", function() {
$('#map_square').gmap(
{ 'center' : mapdata.destination,
'zoom' : 12,
'mapTypeControl' : false,
'navigationControl' : false,
'streetViewControl' : false
})
.bind('init', function(evt, map) {
$('#map_square').gmap('addMarker',
{ 'position': map.getCenter(),
'animation' : google.maps.Animation.DROP
});
});
$('#map_square').click( function() {
$.mobile.changePage($('#page-map'), {});
});
});
function fadingMsg (locMsg) {
$("<div class='ui-overlay-shadow ui-body-e ui-corner-all fading-msg'>" + locMsg + "</div>")
.css({ "display": "block", "opacity": 0.9, "top": $(window).scrollTop() + 100 })
.appendTo( $.mobile.pageContainer )
.delay( 2200 )
.fadeOut( 1000, function(){
$(this).remove();
});
}
//Create the map then make 'displayDirections' request
$('#page-map').live("pageinit", function() {
$('#map_canvas').gmap({'center' : mapdata.destination,
'mapTypeControl' : true,
'navigationControl' : true,
'navigationControlOptions' : {'position':google.maps.ControlPosition.LEFT_TOP}
})
.bind('init', function() {
$('.refresh').trigger('tap');
});
});
$('#page-map').live("pageshow", function() {
$('#map_canvas').gmap('refresh');
});
// Request display of directions, requires jquery.ui.map.services.js
var toggleval = true; // used for test case: static locations
$('.refresh').live("tap", function() {
// START: Tracking location with device geolocation
if ( navigator.geolocation ) {
fadingMsg('Using device geolocation to get current position.');
navigator.geolocation.getCurrentPosition (
function(position ) {
$('#map_canvas').gmap('displayDirections',
{ 'origin' : new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
'destination' : mapdata.destination, 'travelMode' : google.maps.DirectionsTravelMode.DRIVING},
{ 'panel' : document.getElementById('dir_panel')},
function (result, status) {
if (status === 'OK') {
var center = result.routes[0].bounds.getCenter();
$('#map_canvas').gmap('option', 'center', center);
$('#map_canvas').gmap('refresh')
} else {
alert('Unable to get route');
}
}
);
},
function(){
alert('Unable to get location');
$.mobile.changePage($('#page-home'), { });
});
} else {
alert('Unable to get location.');
}
// END: Tracking location with device geolocation
$(this).removeClass($.mobile.activeBtnClass);
return false;
});
// Go to map page to see instruction detail (zoom) on map page
$('#dir_panel').live("tap", function() {
$.mobile.changePage($('#page-map'), {});
});
// Briefly show hint on using instruction tap/zoom
$('#page-dir').live("pageshow", function() {
fadingMsg("Tap any instruction<br/>to see details on map");
});
Thx for the help!

This is how you may need to call.
navigator.geolocation.getCurrentPosition(successCallback,
errorCallback,
{maximumAge:Infinity, timeout:0, enableHighAccuracy: true });
Ofcourse here you can change maximumAge and timeout values, but this is where you set enableHighAccuracy.
So just specify this as third param in your getcurrentposition method.
EDIT :
navigator.geolocation.getCurrentPosition (
function(position ) {
$('#map_canvas').gmap('displayDirections',
{ 'origin' : new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
'destination' : mapdata.destination, 'travelMode' : google.maps.DirectionsTravelMode.DRIVING},
{ 'panel' : document.getElementById('dir_panel')},
function (result, status) {
if (status === 'OK') {
var center = result.routes[0].bounds.getCenter();
$('#map_canvas').gmap('option', 'center', center);
$('#map_canvas').gmap('refresh')
} else {
alert('Unable to get route');
}
}
);
},
function(){
alert('Unable to get location');
$.mobile.changePage($('#page-home'), { });
},
{ enableHighAccuracy: true } );

Since you want to use geolocation, have you set the sensor to true? Because if you set it false, it won't work.
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>

Related

Moving to another screen after loading screen finishes

In my react native application, in home screen there is a button to open a compass that shows the direction of a specific location. For that I need the coordinates of the user to be passed to the compass screen to make the calculations, m passing the values in the navigator.
Iam loading the coordinates on componentDidMount() method of home screen, my problem is that getting the coordinates of the user sometimes takes a bit of time (depending on the user's gps signal strength and his/her device), so I used conditional render to show a "loading" component if the user presses on compass button before coordinates are loaded. But the problem is that m not knowing how to send him/her to compass screen after the loader, because right now after the loader he/she stays in home screen, and has to press the button again to go to the compass.
state = {
currentLongitude: "unknown",
currentLatitude: "unknown",
locationLoading: false,
};
getCards = () => [...
{id: "3",
card: this.languageCard("Compass"),
onPress: () => {
this.state.currentLatitude != "unknown"
? this.props.navigation.navigate("Compass", {
latitude: this.state.currentLatitude,
longitude: this.state.currentLongitude,
})
: this.setState({ locationLoading: true });
},
}...]
componentDidMount() {
this.requestLocation();
}
requestLocation() {
var that = this;
if (Platform.OS === "ios") {
this.callLocation(that);
} else {
async function requestLocationPermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: "Location Access Required",
message: "This App needs to Access your location",
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
that.callLocation(that);
} else {
alert("Permission Denied");
}
} catch (err) {
alert("err", err);
console.warn(err);
}
}
requestLocationPermission();
}
}
callLocation(that) {
Geolocation.getCurrentPosition(
(position) => {
const currentLongitude = JSON.stringify(position.coords.longitude);
const currentLatitude = JSON.stringify(position.coords.latitude);
that.setState({ currentLongitude: currentLongitude });
that.setState({ currentLatitude: currentLatitude });
this.setState({ locationLoading: false });
},
(error) => alert(error.message),
{ enableHighAccuracy: false, timeout: 20000, maximumAge: 1000 }
);
}
render() {
return this.state.locationLoading ? (
<Loader />
) : (
<SafeAreaView>
....
</SafeAreaView>

React native geolocation getCurrentPosition no reponse (android)

I have read and tested a lot of issues but I still can not get geolocation on Android.
I use navigator.geolocation.getCurrentPosition, on iOS everything works fine, but on Android I have no answer to this function, either success or error.
I have installed react-native-permissions to make sure that the user has activated the permissions but it does not change anything because it says that everything is "authorized".
I noticed that it came from GPS of the device. If I activate it manually, everyting works fine. However, I can not find a way to activate it for the user. On iOS, if GPS is not activated, I fall in the error callback and tell user to activate it, but on android, nothing is happennig.
I don't understand why I can't get geolocation only with getCurrentPosition (I have ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION in manifest).
Here a part of my code:
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
//do my stuff with position value
},
(error) => {
Permissions.getPermissionStatus('location')
.then((response) => {
if (response !== "authorized") {
Alert.alert(
"Error",
"We need to access to your location",
[
{
text: "Cancel",
onPress: () => {
// do my stuff
}, style: 'cancel'
},
{
text: "Open Settings",
onPress: () => Permissions.openSettings()
}
]
);
} else {
// do my stuff
}
});
},
{ enableHighAccuracy: true, timeout: 2000, maximumAge: 1000 }
);
}
Does anyone have any idea ?
Thank you
You should need to enable GPS on android
For enabling location/gps on Android I can recommend this module:
https://github.com/Richou/react-native-android-location-enabler
It is using the standard Android dialog for location:
like this
import React, { Component } from "react";
import { Text, StyleSheet, View, Platform } from "react-native";
import RNAndroidLocationEnabler from "react-native-android-location-enabler";
export default class index extends Component {
componentDidMount() {
this.getLocation();
}
onLocationEnablePressed = () => {
if (Platform.OS === "android") {
RNAndroidLocationEnabler.promptForEnableLocationIfNeeded({
interval: 10000,
fastInterval: 5000,
})
.then((data) => {
this.getLocation();
})
.catch((err) => {
alert("Error " + err.message + ", Code : " + err.code);
});
}
};
getLocation = () => {
try {
navigator.geolocation.getCurrentPosition(
(position) => {
//do my stuff with position value
},
(error) => {
Permissions.getPermissionStatus("location").then((response) => {
if (response !== "authorized") {
Alert.alert("Error", "We need to access to your location", [
{
text: "Cancel",
onPress: () => {
// do my stuff
},
style: "cancel",
},
{
text: "Open Settings",
onPress: () => Permissions.openSettings(),
},
]);
} else {
// do my stuff
}
});
},
{ enableHighAccuracy: true, timeout: 2000, maximumAge: 1000 }
);
} catch (error) {
this.onLocationEnablePressed();
}
};
}

Direct Update error FAILURE_UNZIPPING

We are customizing the DirectUpdate process as in the documentation (https://www-01.ibm.com/support/knowledgecenter/SSHS8R_7.1.0/com.ibm.worklight.dev.doc/dev/c_customizing_direct_update_ui_android_wp8_ios.html - with a directUpdateCustomListener) but in the onFinish callback the status is FAILURE_UNZIPPING.
I am testing on an Android (5.1.1) emulator.
function wlCommonInit(){
WL.Client.connect({
onSuccess: function() {
console.log("Successfully connected to Worklight Server.");
}, onFailure: function() {
console.log("Failed connecting to Worklight Server.");
}
});
}
var busyInd = new WL.BusyIndicator('content');
var savedDirectUpdateContext = null;
var restartDirectUpdate = function () {
if (savedDirectUpdateContext != null) {
savedDirectUpdateContext.start(directUpdateCustomListener); // use saved direct update context to restart direct update
}
};
var directUpdateCustomListener = {
onStart: function(totalSize) {
busyInd.show();
},
onProgress: function(status, totalSize, completeSize) {},
onFinish: function(status) {
busyInd.hide();
console.log("[MFP - DirectUpdate] Finish status: " + status);
var posSuccess = status.indexOf("SUCCESS");
if (posSuccess > -1) {
WL.Client.reloadApp();
} else {
WL.SimpleDialog.show('Update Failed', 'Press try again button', [{
text: "Try Again",
handler: restartDirectUpdate // restart direct update
}]);
wl_directUpdateChallengeHandler.submitFailure();
}
}
};
wl_directUpdateChallengeHandler.handleDirectUpdate = function(directUpdateData, directUpdateContext) {
savedDirectUpdateContext = directUpdateContext
WL.SimpleDialog.show('Update Avalible', 'Press Update button to download the new version!', [{
text : 'Update',
handler : function() {
directUpdateContext.start(directUpdateCustomListener);
}
}, {
text : 'Cancel',
handler : function() {
wl_directUpdateChallengeHandler.submitFailure();
}
}]);
};
How can we fix this?
The custom code is working fine without zxing installed. I suggest that you will try the same without this library. If it works, I suspect that it may be initializing or otherwise interfering with the Direct Update process once an update has been received.
Considering loading the library later in the app life cycle and see if this helps.

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.

Ionic admob implementation using floatinghotpot cordova-plugin-admob

I'm following this tutorial for having banner ads in my android application.
https://blog.nraboy.com/2014/06/using-admob-ionicframework/
The problem is that I get an error callback from the plugin which is only telling me :
Invalid action
I ran the cordova plugin add for the plugin, I modified the admob publisher id, I used the sample code from the tutorial right above but it always get stuck in the second callback function which is the error case callback.
Here is the code I used :
var admobApp = angular.module('myapp', ['ionic'])
.run(function($ionicPlatform, $ionicPopup) {
$ionicPlatform.ready(function() {
if(window.plugins && window.plugins.AdMob) {
var admob_key = device.platform == "Android" ? "ANDROID_PUBLISHER_KEY" : "IOS_PUBLISHER_KEY";
var admob = window.plugins.AdMob;
admob.createBannerView(
{
'publisherId': admob_key,
'adSize': admob.AD_SIZE.BANNER,
'bannerAtTop': false
},
function() {
admob.requestAd(
{ 'isTesting': false },
function() {
admob.showAd(true);
},
function() { console.log('failed to request ad'); }
);
},
function() { console.log('failed to create banner view'); }
);
}
});
});

Categories

Resources