How to find Geolocation (longitude and latitude)in jquery mobile +phonegap - android

can you please tell me how to find Geo location (longitude and latitude) in jquery mobile using phonegap.And then i need to show the position on map.

I assume you have referred Phonegap's Getting Started Guide to create basic project.
This is the script to get Lattitude and Longitude
/*
* This file contains script to get lattitude and longitude
*
*/
var lat = 0;
var lng = 0;
//A button click will call this function
function getLocation() {
navigator.geolocation.getCurrentPosition(onSuccess, onError, { enableHighAccuracy: true });
}
// onSuccess Geolocation
//
function onSuccess(position) {
//Lat long will be fetched and stored in session variables
//These variables will be used while storing data in local database
lat = position.coords.latitude;
lng = position.coords.longitude;
alert('Lattitude: ' + lat + ' Longitude: ' + long);
sessionStorage.setItem('lattitude', lat);
sessionStorage.setItem('longitude', lng);
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
You will have to add necessary permissions in your manifest file.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
Call getLocation() function onclick event of button or wherever you wish to get geolocation.
For more details refer Phonegap Geolocation Documentation
To show google map please refer Google MAP API
Hope that helps.

Related

How can I retrieve the latitude and longitude using Ionic?

How can I get the latitude/longitude using the Ionic Framework. In Android it sometimes provides it as intended and sometimes it doesn't give latitude/longitude using the following:
navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
You could use a call to a URL API which returns a JSON object, and then get the latitude and longitude. The following example calls http://freegeoip.net/json/ and prints out the results. To access the latitude and longitude, you would use the result.latitude and result.longitude fields.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://freegeoip.net/json/", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
this is an example how to get Lat,Long using https://github.com/apache/cordova-plugin-geolocation
.controller('MyCtrl', function($scope, $cordovaGeolocation) {
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var lat = position.coords.latitude
var long = position.coords.longitude
console.log(lat + ' ' + long)
}, function(err) {
console.log(err)
});
var watchOptions = {timeout : 3000, enableHighAccuracy: false};
var watch = $cordovaGeolocation.watchPosition(watchOptions);
watch.then(
null,
function(err) {
console.log(err)
},
function(position) {
var lat = position.coords.latitude
var long = position.coords.longitude
console.log(lat + '' + long)
}
);
watch.clearWatch();
})
You also noticed posOptions and watchOptions objects. We are using timeout to adjust maximum length of time that is allowed to pass in milliseconds and enableHighAccuracy is set to false. It can be set to true to get the best possible results but sometimes it can lead to some errors. There is also maximumAge option that can be used to show how old position is accepted. It is using milliseconds, the same as timeout option.
When we start our app and open the console it will log the latitude and longitude of the device. When our position is changed, the lat and long values will change.
Not quite sure what you are asking here, but Ionic can't give you geolocations, cordova however can. If you want to make it easy for yourself you should look into ngCordova, it's a angular wrapper for cordova plugins. Have a look here: http://ngcordova.com/docs/plugins/geolocation/

How to stop watchPosition() Position retrieval timed out error?

I am developing a phonegap application that uses the current location of the device in its functionalities but when tested on Iphone the App give an error message every 60 seconds as follows:
The Source code I am using to get the location is:
function onDeviceReady() {
var options = { maximumAge: 0, timeout: 10000,enableHighAccuracy: false };
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
function onSuccess(position) {
if (position.coords.latitude) {
sessionStorage.setItem("appLatitude", position.coords.latitude);
sessionStorage.setItem("appLongitude", position.coords.longitude);
}
//alert(sessionStorage.getItem("appLatitude") + "&" + sessionStorage.getItem("appLongitude"));
}
function onError(error) {
z.appNotification.getAlert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
}
How can stop that error message from prompting?
If you only want to get the location once use:
navigator.geolocation.getCurrentPosition(onSuccess, onError);
If you want to stop watching for any reason, use:
navigator.geolocation.clearWatch(watchID);

Geolocation error in android

here is the code below
if (navigator.geolocation) {
alert("ok");
// var options = { timeout: 0, maximumAge: 600000 };
navigator.geolocation.watchPosition(onSuccess, onError);
}
function onSuccess(position) {
alert("success");
lat = position.coords.latitude;
lng = position.coords.longitude;
}
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
It works in all browsers , iphone and WindowsPhone. But in andorid in gives me error code :3 timeout expired error.
I enabled gps, wi-fi also in the settings menu--> location services -->location and Google Search,
In the browser menu settings--> privacy and settings enable location is checked.
What is the problem , any ideas? i really stuck in.
Normally , we accept the website request that wants to share your location.
In android if you do not see the question then in the browser settings advanced--> website settings add your URL to there.
It solves the problem.

wikitude 3.01: adding some features between examples did not work properly

i downloaded the SDK of Wikitude 3.1, installed the samples into my Eclipse workspace and on my Gnexus everything works. I divide the questions in points so could be easier to answer:
I added the "onMarkerSelectedFn" method into the "limitingVisiblePois.js" file because i wanted to have my POIs clickable and when clicked, appear the information page like the 5.1 example. I added the method but it doesn't work and i haven't understand where i'm making mistakes. Each other file is the same for the 5.x samples.
Code of "limitingVisiblePois.js" edited by me
var World = {
markerDrawable_idle: new AR.ImageResource("assets/marker_idle.png"),
markerDrawable_selected: new AR.ImageResource("assets/marker_selected.png"),
markerDrawable_directionIndicator: new AR.ImageResource("assets/indi.png"),
markerList: [],
// called to inject new POI data
loadPoisFromJsonData: function loadPoisFromJsonDataFn(poiData) {
PoiRadar.show();
document.getElementById("statusElement").innerHTML = 'Loading JSON objects';
var poiImage = new AR.ImageResource("img/marker.png", {
onError: World.errorLoadingImage
});
// TODO: call single POI-creation statement instead
for (var i = 0; i < poiData.length; i++) {
var singlePoi = {
//EDIT BRUS: adding the ID of each POIs
"id": poiData[i].id,
"latitude": parseFloat(poiData[i].latitude),
"longitude": parseFloat(poiData[i].longitude),
"altitude": parseFloat(poiData[i].altitude),
"title": poiData[i].name,
"description": poiData[i].description
};
World.markerList.push(new Marker(singlePoi));
}
document.getElementById("statusElement").innerHTML = 'JSON objects loaded properly';
},
// user's latest known location, accessible via userLocation.latitude, userLocation.longitude, userLocation.altitude
userLocation: null,
// location updates
locationChanged: function locationChangedFn(lat, lon, alt, acc) {
World.userLocation = {
'latitude': lat,
'longitude': lon,
'altitude': alt,
'accuracy': acc
};
},
//EDIT BRUS: Adding onMarkerSelected function
onMarkerSelected: function onMarkerSelectedFn(marker) {
// notify native environment
document.location = "architectsdk://markerselected?id=" + marker.poiData.id;
},
// called from slider.js every time the slider value changes
onSliderChanged: function onSliderChangedFn(value) {
if (value > 0) {
var valueMeters = value * 1000;
PoiRadar.setMaxDistance(valueMeters);
AR.context.scene.cullingDistance = valueMeters;
}
}
};
// forward locationChanges to custom function
AR.context.onLocationChanged = World.locationChanged;
2) I wasn't able to understand where the POIs latlong coordinates where declareated. In the same code posted ahead, there is the function
loadPoisFromJsonData: function loadPoisFromJsonDataFn(poiData)
but i don't understand how the poiData are taken.
I used the last 3.1 SDK in Android and phonegap.
thanks in advance,
Kind regards
Brus
PhoneGap Plugin samples are yet not in sync with those from the native SDK.
Whereat the current "HelloWorld" sample in PhoneGap Plugin requests POI-Data from a webservice the sample you pointed out is from the Android SDK and passes POI-data from native Android via "architectView.callJavaScript('loadPoisFromJsonData(...)')".
Both are making use of the same method to parse POI data, PhoneGap sample uses it e.g. that way
// request POI data
requestDataFromServer: function requestDataFromServerFn(lat, lon) {
var serverUrl = ServerInformation.POIDATA_SERVER + "?" + ServerInformation.POIDATA_SERVER_ARG_LAT + "=" + lat + "&" + ServerInformation.POIDATA_SERVER_ARG_LON + "=" + lon + "&" + ServerInformation.POIDATA_SERVER_ARG_NR_POIS + "=20";
var jqxhr = $.getJSON(serverUrl, function(data) {
World.loadPoisFromJsonData(data);
})
.error(function(err) {
alert("JSON error occured! " + err.message);
})
.complete(function() {});
}
You may just add these lines in your locationChanged implementation to use places from a dummy-webserver (don't forget to define 'alreadyRequestedData= false;' )
if (!World.alreadyRequestedData) {
World.requestDataFromServer(lat, lon);
World.alreadyRequestedData = true;
}
Kind regards,
Andreas

GPS doesnt' work (Android web application)

I'm writing web application for mobile phones and I need to use geolocation.
I wrote: (javascript)
function GeoLocationStart(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(onSuccess,onError);
}
else{
alert("Functionality not available");
}
}
function onSuccess(position) {
var initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
var userMarker = new google.maps.Marker({
position: initialLocation,
map: map,
title: "You're here",
icon: face
});
userMarker.setMap(map);
var userhtml = "It's you!";
var UserInfoWindow = new google.maps.InfoWindow({content: userhtml});
google.maps.event.addListener(userMarker, 'click', function() {
UserInfoWindow.open(map, userMarker);
});
};
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
It works fine but without GPS.
Though I set in Android manifest file permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
app doesn't start even searching sattelites. (Of course I checked GPS on my phone, it works in other applications)
How to switch GPS on?
Thanks
I found a solution.
After location had found using wireless network, GPS stopped to work because the goal has been achieved - location is defined!
To continue searching position I wrote
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { frequency: 3000 });
so GPS launched.

Categories

Resources