GeoLocation using Phonegap and Android - android

I am Designing a mobile app on phonegap. In this I am trying to get curent location of user. But I am not getting the map on Andriod Emulator.
I used this code :
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width; height=device-height; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>PhoneGap Map</title>
<link rel="stylesheet" href="/master.css" type="text/css" media="screen" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript">
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError,{alert("error"),"enableHighAccuracy":true,"timeout":3000});
}
//GEOLOCATION
var onSuccess = function(position) {
alert("Latitude: " + position.coords.latitude + "\n" +
"Longitude:" + position.coords.longitude + "\n");
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
//MAP
var mapOptions = {
center: new google.maps.LatLng(myLat, myLong),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
};
// onError Callback receives a PositionError object
//
function onError(error) {
alert("code: " + error.code + "\n" +
"message: " + error.message + "\n");
}
</script>
</head>
<body onload="onLoad()">
<div>map</div>
<div id="map_canvas" style="width:100px; height: 100px;" ></div>
</body>
</html>
I don't know where I am gng wrong.Can any one please help me on this?

Check this code... change cordova-1.8.1.js into ur cordova2.0.js... remaining source is refer thro online. If its not works. then there problem in ur phonegap configuration.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Google Maps JavaScript API v3 Example: Info Window Simple</title>
<link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript" charset ="utf-8" src="cordova-1.8.1.js"></script>
<script>
function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">Uluru</h1>'+
'<div id="bodyContent">'+
'<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
'sandstone rock formation in the southern part of the '+
'Northern Territory, central Australia. It lies 335 km (208 mi) '+
'south west of the nearest large town, Alice Springs; 450 km '+
'(280 mi) by road. Kata Tjuta and Uluru are the two major '+
'features of the Uluru - Kata Tjuta National Park. Uluru is '+
'sacred to the Pitjantjatjara and Yankunytjatjara, the '+
'Aboriginal people of the area. It has many springs, waterholes, '+
'rock caves and ancient paintings. Uluru is listed as a World '+
'Heritage Site.</p>'+
'<p>Attribution: Uluru, <a href="http://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
'http://en.wikipedia.org/w/index.php?title=Uluru</a> '+
'(last visited June 22, 2009).</p>'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
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);
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>

Related

Applying geolocation in phonegap doesn't work

I'm rather new to this and currently working on my first app (for a school project). I followed this https://www.w3.org/TR/geolocation-API/ tutorial. When I open the project in the browser (on a pc) it gives the coordinates but once installed (though phonegap) on my phone nothing seems to happen. Also the implementation with google maps does not seem to work (also not on the pc). Can any of you help me or redirect me to easy to follow guids?
These are the sources I looked at as well:
https://demos.jquerymobile.com/1.4.5/map-geolocation/
https://www.w3.org/TR/geolocation-API/
https://forum.jquery.com/topic/jquery-mobile-activating-geolocation-on-mobile-devices
https://mobiforge.com/design-development/html5-mobile-web-a-guide-geolocation-api
https://cordova.apache.org/docs/en/3.0.0/cordova/geolocation/geolocation.getCurrentPosition.html
https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML =
"Latitude: " +
position.coords.latitude +
"<br>Longitude: " +
position.coords.longitude;
}
</script>
<html>
<head>
...
<script>
$(document).ready(function () {
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
//onDeviceReaddy
initMap(); //Google map
navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
}
// user Current Position
function displayAndWatch(position) {
setCurrentPosition(position);
watchCurrentPosition();
}
function setCurrentPosition(pos) {
var image = 'img/ic_CurrentLocationmap.png';
currentPositionMarker = new google.maps.Marker({
icon: image,
map: map,
position: new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
),
title: "Current Location"
});
map.panTo(new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
));
}
function watchCurrentPosition() {
var positionTimer = navigator.geolocation.watchPosition(
function (position) {
setMarkerPosition(
currentPositionMarker,
position
);
});
}
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
var center = {
lat: position.coords.latitude,
lng: position.coords.longitude
}
map.setCenter(center);
}
function locError(error) {
// the current position could not be located
}
});
<script>
</head>
<body>
...
...
<script async defer src="https://maps.googleapis.com/maps/api/js?key=******(Your API Key)">
</script>
</body>
<html>
<!doctype html>
<html>
<head>
<title>Huisartspraktijk app</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- /jquery links en scripts. NIET VERWIJDEREN!! -->
<link rel="stylesheet" href="css/jquery.mobile-1.4.5.css">
<script src="js/jquery.js"></script>
<script src="js/jquery.mobile-1.4.5.js"></script>
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/jquery-ui.js"></script>
<style>
/* css styes for the maps */
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<!-- Script for the geolocation, Stack Overflow -->
<script>
$(document).ready(function () {
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
//onDeviceReaddy
initMap(); //Google map
navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
}
// user Current Position
function displayAndWatch(position) {
setCurrentPosition(position);
watchCurrentPosition();
}
function setCurrentPosition(pos) {
var image = 'img/ic_CurrentLocationmap.png';
currentPositionMarker = new google.maps.Marker({
icon: image,
map: map,
position: new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
),
title: "Current Location"
});
map.panTo(new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
));
}
function watchCurrentPosition() {
var positionTimer = navigator.geolocation.watchPosition(
function (position) {
setMarkerPosition(
currentPositionMarker,
position
);
});
}
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
var center = {
lat: position.coords.latitude,
lng: position.coords.longitude
}
map.setCenter(center);
}
function locError(error) {
// the current position could not be located
}
});
</script>
</head>
<body>
<!-- The mobile page in html5, within this page there is a DIV containing the Java Script to summon google maps -->
<div data-role="page" id="mobiel">
<!-- /header -->
<div data-role="header">
<h1>SPOED</h1>
<div data-role="navbar">
<ul>
<li>Mainpage</li>
<li>Chat met de arts</li>
<li>Consultaanvraag</li>
<li>Doorverwijzing</li>
<li>Bloedonderzoek</li>
<li>Berichten</li>
<li>EPD</li>
<li>Mijn medicijnen</li>
</ul>
</div>
</div>
<!-- /content -->
<div role="main" class="ui-content" align="center">
<h2> "Ga naar deze medische post. Men is op de hoogte van uw komst" </h2>
<div style="background-color: lightyellow">
<br>
<h3> Huisartsenpraktijk Gideonse en Boekhout </h3>
<p>Meteorenstraat 4<br>
2024 RK, Haarlem</p>
<p>Telefoon<br>
023 - 525 36 00 </p>
<p>Keuze 1: Spoed <br>
Keuze 2: Herhaalrecepten <br>
Keuze 3: Assistentie</p>
<br>
<!-- In this DIV you will find a small Java Script for summoning Google maps. But some how it won't work, Google maps won't show within this DIV. -->
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBRewVX3nHmzN6KDiT5g5ruUCINH4wERaQ&callback=initMap"
async defer></script>
</div>
Terug
</div>
<!-- /footer -->
<div data-role="footer">
<h2>© 2019 Huisartsapp</h2>
</div>
</div><!-- /page -->
</body>
</html>

Not asking share your location in worklight hybrid app

The worklight hybrid app is not asking share your location. Without asking it is showing some other location. What can i do for this? Please tell me the solution.
This is my total code
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Go2needs</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
window.$ = window.jQuery = WLJQ;
function wlCommonInit() {
}
function getGeo() {
alert();
/* WL.Device.Geo.acquirePosition(positive, negative, {
enableHighAccuracy: true,
});
alert(); */
if (navigator.geolocation) {
alert('if');
navigator.geolocation.getCurrentPosition(function(position) {
//alert(position.coords.latitude);
//alert(position.coords.longitude);
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
alert('geo');
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
console.log(results[1]);
alert(results[1].formatted_address);
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
});
alert('end');
}
}
/* function positive(data) {
alert();
alert(JSON.stringify(data));
}
function negativa(data) {
alert();
alert(JSON.stringify(data));
} */
</script>
</head>
<body onload="WL.Client.init({})">
<input type="button" value="Click" onclick="getGeo()" />
<script src="js/initOptions.js"></script>
<script src="js/main.js"></script>
<script src="js/messages.js"></script>
</body>
</html>
The way you are implementing this is very strange; it is as if you're following tutorials from Worklight 4.x or 5.x... very old.
Try this:
AndroidManifest.xml
Add required permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
index.html
The head should be like this:
<head>
<meta charset="UTF-8">
<title>index</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<!-- <link rel="shortcut icon" href="images/favicon.png">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png"> -->
<link rel="stylesheet" href="css/main.css">
<script>window.$ = window.jQuery = WLJQ;</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
</head>
And the body:
<body style="display: none;">
<h1>Googlel Maps - show my position</h1>
<div id="map-canvas"></div>
<script src="js/initOptions.js"></script>
<script src="js/main.js"></script>
<script src="js/messages.js"></script>
</body>
main.js:
var myLat;
var myLong;
function wlCommonInit(){
navigator.geolocation.getCurrentPosition(setPositionCoords, errorSettingCoords);
var mapOptions = {
center: new google.maps.LatLng(myLat, myLong),
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(myLat, myLong),
map: map,
title:"Hey Me!"
});
}
function setPositionCoords(position) {
myLat = position.coords.latitude;
myLong = position.coords.longitude;
}
function errorSettingCoords() {
alert ("Failed setting coordinates.");
}

How to add a marker in an Ionic App with the Cordova Geolocation plugin

I have a problem with this code. I can see the Google Maps correctly, with my actual location in the center of the android screen, but I cannot see the marker whatever I do.
This is the html:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<style>
html, body {
height:100%;
}
</style>
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="starter" ng-controller="GeoCtrl" class="platform-android">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
This is the services.js
angular.module('starter.services', [])
.factory('Location', ['$q', function($q) {
return {
getLocation: function(options) {
var q = $q.defer();
navigator.geolocation.getCurrentPosition(function(position) {
q.resolve(position);
}, function(err) {
q.reject(err);
});
return q.promise;
}
}
}]);
And this is the app.js:
angular.module('starter', ['ionic', 'starter.services'])
.run(function($ionicPlatform) {
...
})
.controller('GeoCtrl', function($scope, Location) {
$scope.lat;
$scope.long;
$scope.map;
$scope.marker;
Location.getLocation().then(function (position) {
$scope.lat = position.coords.latitude;
$scope.long = position.coords.longitude;
var mapOptions = {
center: new google.maps.LatLng($scope.lat, $scope.long),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}, function(err) {
// error
});
$scope.marker = new google.maps.Marker({
position: new google.maps.LatLng($scope.lat, $scope.long),
map: $scope.map,
title: 'Holas!'
}, function(err) {
console.err(err);
});
});
Thank you!
I hope this can help to somebody:
I called the marker outside the then flow, whereas it has to be called inside:
Location.getLocation().then(function (position) {
$scope.lat = position.coords.latitude;
$scope.long = position.coords.longitude;
var mapOptions = {
center: new google.maps.LatLng($scope.lat, $scope.long),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
$scope.marker = new google.maps.Marker({
position: new google.maps.LatLng($scope.lat, $scope.long),
map: $scope.map,
title: 'Holas!'
}, function(err) {
console.err(err);
});
}, function(err) {
// error
});
Now it works.

Not able to get the geolocation in Android emulator

I'm doing a small sample app which displays latitude and longitude in a popup when i click on the button
here is my code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>BlankCordovaApp1</title>
<link href="css/index.css" rel="stylesheet" />
<script src="cordova.js"></script>
<script src="scripts/platformOverrides.js"></script>
<script src="scripts/index.js"></script>
<script type="text/javascript" charset="utf-8">
var alertmsg = function (position) {
var msg = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />'
navigator.notification.alert(msg);
}
function geoLocation() {
navigator.geolocation.getCurrentPosition(alertmsg)
}
</script>
</head>
<body>
<input type="button" id="btnClick" onclick="geoLocation()" value="click" />
</body>
</html>
It is working in Ripple emulator
But it is not working in Android emulator and Genymotion
I figured out the problem.
If i use this code it is working fine
navigator.geolocation.getCurrentPosition(alertmsg, onError, { timeout: 30000, enableHighAccuracy: true });
It is working in all emulators(Ripple,Android,Genymotion)
I'm using Visual Studio 13 with a Backbone based smartphone app and this was a pain. Adding the timeout option and enableHighAccuracy always throws the onError handler, without these neither return.
So this is a good answer:
//Android Emulator safe version
function getGpsCordinates(callback) {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(
//Success
function (position) {
console.log("GPS: Success");
callback(position);
},
//Error
function (error) {
console.log("GPS: Error");
var position = {
coords: {
longitude: 0,
latitude: 0,
speed: 0
}
};
callback(position);
},
{ timeout: 7000, enableHighAccuracy: true });
} else {
var position = {
coords: {
longitude: 0,
latitude: 0,
speed: 0
}
};
console.log("GPS: Not Supported");
callback(position);
}
console.log("GPS: Continued");
}
getGpsCordinates(function(mycallback) {
alert(mycallback.coords.latitude);
});
Code Pen Version

Android 4.2.2 does not load google maps for my application

I am developing an android application (build with Phonegap) that requires to display the current location of a user and to load KMZ file (with poly lines) on Google Map (use of google map api).
My application loads the map on a specific zoom level (11) and map is centered based on user's current location (reduce data consumption). I noticed that for android OS 4.2.2 the map is not loaded at all, message displayed " access denied to your current position".
On the other hand map is loaded correctly for android OS 4.1.2, 4.3, 4.4 (not get any message).
Is this a security issue/bug for android 4.2.2?
Or it is a bug related to the Phonegap I use to build the APK?
How can I resolve this issue? Is there any configuration I need to do in the mobile?
Thanks
It works fine on Android 4.2.2 or any other supported version. There might be a mistake in your code settings.
I just re-confirmed by creating a sample App.
Steps:
(1) Include Google API Key and Maps jS link in the html header section
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="width=device-width, height=device-height" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_VALUE_&sensor=true"></script>
<title>Hello World</title>
</head>
<body>
<b>Road View</b>
<div id="map-canvas" style="width: 100%; height: 200px"></div>
<b>Street View</b>
<div id="pano" style="width: 100%; height: 200px;"></div>
<b>Live Traffic Update View</b>
<div id="traffic" style="width: 100%; height: 200px;"></div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
(2) In the index.js file declare following function to render maps
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
app.renderMap();
},
receivedEvent: function(id) {
},
renderMap: function() {
// --- Road View
var fenway = new google.maps.LatLng(42.345573, -71.098326);
var mapOptions = {
center: fenway, zoom: 11
};
var map = new google.maps.Map( document.getElementById('map-canvas'), mapOptions);
// ---- Street View
var panoramaOptions = {
position: fenway,
pov: { heading: 34, pitch: 10 }
};
var panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'), panoramaOptions);
map.setStreetView(panorama);
// ---- Live Traffic View
var myLatlng = new google.maps.LatLng(34.04924594193164, -118.24104309082031);
var mapOptions = {
zoom: 13,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('traffic'), mapOptions);
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
}
};
app.initialize();
(3) Add permission in the AndroidManifest.xml file.
(4) Set your project API level to your desired version, for instance 4.2.2
(5) Run App on device and it should show three different types of Map Views ( Road, Street and Live Traffic)
This is the JS file code I use to load KML files on map, get current position, display marker:
'use strict';
angular.module('ehunter.controllers', []).
controller('RegionListCtrl', ['$scope', '$http', '$window',
function($scope, $http, $window) {
$http.get('regions.json').success(function(data) {
$scope.regions = data;
});
$scope.openBrowser = function(url){
$window.open(url, "_blank", "location=yes");
}
}])
.controller('RegionViewCtrl', ['$scope', '$routeParams',
function($scope, $routeParams) {
$scope.region = angular.fromJson($routeParams.r);
var map;
var src = "MY_SERVER"+ $scope.region.File;
initialize();
function initialize() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 11,
mapTypeId: google.maps.MapTypeId.TERRAIN
});
loadKmlLayer(src, map);
}
function loadKmlLayer(src, map) {
var kmlLayer = new google.maps.KmlLayer(src, {
suppressInfoWindows: true,
preserveViewport: true,
map: map
});
}
getLocation();
function getLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function displayPosition(position) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
map: map
});
marker.setVisible(true);
marker.setMap(map);
map.setCenter(marker.position);
});
}}
}])

Categories

Resources