angularjs:ionic IOS emulator is showing wrong GPS co-ordinates - ios

In ionic angularjs
I'm trying to get the Latitude and Longitude of my current location.
It is giving my current location correctly when I'm running it on the browser , but when I run it on IOS emulator it is giving some sanfransisco address.
COntroller.js
ionic.Platform.ready(function() {
LocationService.GetLocation().then(function(data){
console.log(data.latitude,data.longitude);
var code="https://maps.googleapis.com/maps/api/geocode/json?latlng="+data.latitude+","+data.longitude;
$http.get(code).success(function(dataval){
//console.log(dataval.results[0]);
$("#Locationval").text(dataval.results[0]["formatted_address"])
});
});
});
Service.js
appnService.factory('LocationService', function($q){
var currentLocation = {
latitude:"",
longitude:""
}
return {
GetLocation : function(){
var d = $q.defer();
//console.log(d);
navigator.geolocation.getCurrentPosition(function (pos) {
currentLocation.latitude = pos.coords.latitude;
currentLocation.longitude = pos.coords.longitude;
d.resolve(currentLocation);
});
return d.promise
}
};
});
On browser I'm Getting latitude=11.9384867 Longitude=79.8352657(These are correct)
On IOS emulator I'm getting latitude=37.785834 Longitude= -122.406417 (These are wrong)
Please help me with this
Thankyou

Related

iOS 9: cannot open the page when launch the local ios app by browser

if (isIos) {
if (isIos9) {
window.location = 'bdwm://';
iosGo();
} else {
createIframe();
iosGo();
}
}
function createIframe() {
var iframe = document.createElement('iframe');
iframe.style.cssText = 'display:none;width:0;height:0';
document.body.appendChild(iframe);
iframe.src = 'bdwm://';
}
function iosGo() {
var t = Date.now();
setTimeout(function () {
if (Date.now() - t < 600) {
location.href = "https://itunes.apple.com/cn/app/....."//the iOS app url
}
}, 500);
}
I want to solve this question "when exists your app on your iPhone, you can first launch the local your app,but when not exists, you must go to download the iOS app".
The above is my code. When in iOS 9.3, the app will alert the dialog "cannot open the page because the address is invalid", how can i solve it?

Cordova ionic geolocation fails : Position retrieval timed out error code 3 on iOS

I'm working on an app ios/android using cordova and ionic.
cordova plugin geolocation is in version 2.2.0.
it's working good on android.
but on ios, after receiving new position from the watcher 4 times, i have the following error :
PositionError {code: 3, message: "Position retrieval timed out.", PERMISSION_DENIED: 1, POSITION_UNAVAILABLE: 2, TIMEOUT: 3}
somebody have a solution ?
here a part of my code :
var posOptions = {
timeout : 10000,
enableHighAccuracy: false
};
var watchOptions = {
timeout : 10000,
enableHighAccuracy: false // may cause errors if true
};
/**
* Sets initial user position.
*/
$ionicPlatform.ready(function () {
console.log('ready');
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
setLocationData(position);
}, function (err) {
// error
});
/**
* Watches for user position.
*/
$timeout(function() {
console.log(watchOptions);
var watch = $cordovaGeolocation.watchPosition(watchOptions);
watch.then(
null,
function (err) {
// error
console.log(watchOptions);
console.log(err);
alert(err);
},
function (position) {
console.log(watchOptions);
console.log('refresh')
alert('refresh');
setLocationData(position);
});
}, 10000);
});
I solved my issue by doing this :
when Watcher have errors. stop it and restart.
here my code :
/**
* Sets initial user position.
*/
$ionicPlatform.ready(function () {
console.log('ready');
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
setLocationData(position);
}, function (err) {
// error
});
/**
* Watches for user position.
*/
$timeout(function() {
console.log(watchOptions);
watchLocation();
}, 10000);
});
function watchLocation(){
var watch = $cordovaGeolocation.watchPosition(watchOptions);
watch.then(
null,
function (err) {
watch.clearWatch();
watchLocation();
},
function (position) {
setLocationData(position);
});
}
I'm really sorry that I cannot help you more but this is the code I was using in the past...
(it was a Cordova application using Phonegap build)
var getLocation = function() {
var deferred = Q.defer();
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
var onSuccess = function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
deferred.resolve({lat : lat, lng : lng});
};
var onError = function() {
var lat = -77.847635;
var lng = 166.760616;
deferred.resolve({lat : lat, lng : lng});
};
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
} else {
onError();
}
return deferred.promise;
};
There are plenty things that can possibly go wrong. First of all does the app ask user for permission to use the location?
In some instances it wasn't working for me - and the error codes weren't consistent - so there is a fallback to Antarctica...
I have solved by modifying the iOS Cordova Plugin (CDVLocation.m) as follow:
if (enableHighAccuracy) {
__highAccuracyEnabled = YES;
// Set distance filter to 5 for a high accuracy. Setting it to "kCLDistanceFilterNone" could provide a
// higher accuracy, but it's also just spamming the callback with useless reports which drain the battery.
//self.locationManager.distanceFilter = 5; //OLD CODE
self.locationManager.distanceFilter = kCLDistanceFilterNone; //NEW CODE
// Set desired accuracy to Best.
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
} else {
__highAccuracyEnabled = NO;
//self.locationManager.distanceFilter = 10; //OLD CODE
self.locationManager.distanceFilter = kCLDistanceFilterNone; //NEW CODE
self.locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
}
Source: Apache Cordova geolocation.watchPosition() times out on iOS when standing still

Geolocation Using Ionic Cordova Returning Incorrect Lat/Long Values

I am facing issue using Geolocation pluggin with Ionic and Cordova framework.
Using Visual Studio Community 2015, with Cordova CLI version :4.3.0 and added the org.apache.cordova.geolocation pluggin to VSC-2015
My controller.js
.controller('MapCtrl', function ($scope) {
function onSuccess(position) {
console.log(position.timestamp);
console.log(position.coords.latitude + " " + position.coords.longitude);
}
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
})
Added the google maps into the index.html
<script src="https://maps.googleapis.com/maps/api/js?sensor=true&v=3.exp"></script>
Added a Map to my Map.html file
<div id="map" data-tap-disabled="true" map> </div>
The problem is I always get a fixed value of Lat/Long
ie Lat = 43.465187 and Long = -80.522372
This is not my correct Geolocation in terms of Lat/Long.I need my current Geolocation in terms of Lat/Long
Please help me identity the fault.
Also I am using Ripple -Nexus (Galaxy) on Browser.
Any help is appreciated...
Thanks,
Download the Latest version of GeoLocation pluggin from https://github.com/apache/cordova-plugin-geolocation
Then inject the $cordovaGeolocation into the controller.
Code is as below:
.controller('HomeCtrl', function($scope,$cordovaGeolocation) {
$scope.getLocation = function() {
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
//these are your your lat long values
var lat = position.coords.latitude
var long = position.coords.longitude
}, function(err) {
// error
});
}
})
Note: The device need to be connected to internet or wifi and also need to keep the GPS location ON in the device for getting the correct Lat/Long Values.
I am not sure why you get fixed lat/long values. However to get the device's position using Ionic, the following works for me:
ionic.Platform.ready($scope.getLocation);
$scope.getLocation = function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition($scope.showPosition, $scope.showError);
}
else {
console.log('Geolocation is not supported by this browser.');
}
}
$scope.showPosition = function (position) {
console.log(position.timestamp);
console.log(position.coords.latitude + ' ' + position.coords.longitude);
}
$scope.showError = function (error) {
switch (error.code) {
case error.PERMISSION_DENIED:
console.log('User denied the request for Geolocation.');
break;
case error.POSITION_UNAVAILABLE:
console.log('Location information is unavailable.');
break;
case error.TIMEOUT:
console.log('The request to get user location timed out.');
break;
case error.UNKNOWN_ERROR:
console.log('An unknown error occurred.');
break;
}
}
Note that the call to:
ionic.Platform.ready($scope.getLocation);
Is crucial, as you can only guarantee you'll get an accurate GPS fix once the device is ready/initialised.

Google Maps JS API v3 not Geolocating with Phonegap iOS 3.5.0 and jQuery Mobile

The Setup
Currently building my phone gap iOS app which includes geolocation in addition to sending the results to a database and getting back nearby locations. Because I am using jQuery Mobile and Phonegap, I was testing on a browser to perfection, geolocation was success and everything returned was as well. On the iOS device, not so much. When sending a set latitude and longitude, everything returned successfully, but when using the google maps geolocation, and eventually the cordova plugin for geolocation, both failed as unable to find my location, even though they are the exact same code, minus the phone gap initializer on the website.
The Code
jQuery
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
$(document).ready(function () {
//Load Google Map & Geolocate
$(document).on("pagecreate", "#game", function () {
// keep as separate function call to allow for DOM to update after a tag
loadGoogleMap();
});
function loadGoogleMap() {
var defaultLatLng = new google.maps.LatLng(34.0983425, -118.3267434); //default location is Hollywood, CA
if (navigator.geolocation) {
function success(pos) {
//set fields for current user latitude and longitude
$("#lat_in").val(pos.coords.latitude);
$("#lon_in").val(pos.coords.longitude);
//location found
drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
}
function fail(error) {
//try cordova geolocation plugin
function onSuccess(position) {
alert("CDV position success");
//alert(position.coords.latitude);
//alert(position.coords.longitude);
}
function onError(error) {
alert("CDV position error");
//alert("code: " + error.code + "\n" + "message: " + error.message);
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
alert("CDV position fail. Google geolocate fail"); //WHERE THE ERROR IS THROWN. THIS IS ALWAYS THE OUTCOME
//drawMap(defaultLatLng); //Failed to find location. Show default location
}
//Geolocate. Cache location for 5 mins. Timeout after 6 seconds
navigator.geolocation.getCurrentPosition(success, fail, {
maximumAge: 500000,
enableHighAccuracy: true,
timeout: 6000
});
} else {
drawMap(defaultLatLng); //No geolocation support, show default map
}
function drawMap(latlng) {
//Collect Data to Send
var uname = $("#unm_in").val();
var lat = $("#lat_in").val();
var lon = $("#lon_in").val();
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
//update latitude and longitude on DB for logged in user && get nearby users
$.post("PHP_ON_SERVER", {
uname: uname,
lat: lat,
lon: lon
}, function (data) {
$.each(data, function (key, value) {
//Define variables
var allUsrLoc = new google.maps.LatLng(value.lat, value.lon);
var contentString = value.uname;
var mkrImg = "inUsrIcon.png"; //icon for logged in user
var inUserName = value.fname + " " + value.lname;
//if info belongs to current user
if (contentString === uname) {
var marker = new google.maps.Marker({
position: allUsrLoc,
map: map,
title: "Player",
icon: mkrImg
});
//change header to name and points
$("#inUserInfo").text("Hi " + inUserName + " || You have " + value.points + " points");
//disable tag button if not it
if (value.isit === "notit") {
$("#tagBtn").addClass("ui-state-disabled");
}
}
//if not current user and is not it
else if (contentString != uname && value.isit != "it") {
var marker = new google.maps.Marker({
position: allUsrLoc,
map: map,
title: "Player"
});
google.maps.event.addListener(marker, 'click', function () {
//Change selected player hidden field to match marker
$("#unm_sel").val(contentString);
$("#lat_sel").val(value.lat);
$("#lon_sel").val(value.lon);
$("#isit_sel").val(value.isit);
//Change tag button to selected player's username
$("#tagBtn").text("Tag " + contentString);
});
}
//no condition for if not current user and is it. TBD if anything will come
});
}, "json");
} //end drawMap
} // end loadGoogleMap
}
HTML
<div data-role="content" role="main" id="map-canvas">
<!-- Map loads here -->
</div>
Some More to Know
I have been reading up on other related questions, but none of the others do work. Either they say use the plugin, which I am to no avail, or set <access origin="*" /> which I am doing already. In addition, most of the other questions revolve around pre-3.0.0 versions of phone gap, which was its own monster. Also, the map loads, just no markers display. On the DB, the user who's location is being updated is set to (0,0). Lastly, when using geolocation in any other app, the iOS device I test on is successfully finding my location. In addition, I am testing on the same WiFi network as the browser which worked, so anything relating to internally being unable to locate due to network or hardware is ruled out.
If you want to see the working example, just ask.

Ways to get location of the client from the browser?

What i need is the lat/long of the client(via browser)
Found some articles on the net,found some in stack overflow itself(an old article) Get GPS location from the web browser. it was answered almost 18months ago -- wondering if there's any other(more efficient) way of getting the information of the location of the user from the browser.
Soo far,found 2
using Maxmind
http://coding.smashingmagazine.com/2010/03/08/entering-the-wonderful-world-of-geo-location/
Other,using google's api
http://briancray.com/2009/05/29/find-web-visitors-location-javascript-google-api/
w3c's geo api will have downward compatibility issues: http://dev.w3.org/geo/api/spec-source.html ,so not choosing that.
Found a site, www.drumaroo.com -- requests for the location to be shared the 1st time when we drop into the site.Needed something similar
The user can be located by using following ways:-
Using the IP addr.
easiest to achieve but most unreliable due to the uncertainty of network addresses /
topologies.
Using the latitude, longitude pair
most accurate solution, but most of the end users don’t know about their latitude,
longitude value.
Using the zipcodes
nice to think but quite difficult to achieve, although ZipCodes are being used for
quite a long time but this is not a standard yet. (see link
http://en.wikipedia.org/wiki/Postal_code ). ZipCode alone is not sufficient for
calculation of distance we need to convert it to latitude, longitude pair which is an
overhead.
Using user’s address
most compelling thought since each user will have at least one geographic address.
Address alone is not sufficient for calculation of distance we need to convert it to
latitude, longitude pair which is an overhead.
The Best option will be to use options 2,3.4 together, You can do that in two steps:-
First determine the latitude, longitude from the address.
Then use this lat, long value for further processing i.e. storing in
database etc.
For various options available for this see the answer of this question
Try HTML5 geolocation
function init() {
var mapOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}
} else {
alert('Geolocation not detected');
}
}
Here is geolocation described:
http://www.w3schools.com/htmL/html5_geolocation.asp
The lat/lng can then be reverse-geocoded to find the country, address. etc.
https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse
https://developers.google.com/maps/documentation/javascript/examples/map-geolocation . simply click on javascript+html and copy the code into an html file.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Reverse Geocoding</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
var location_timeout = setTimeout("geolocFail()", 10000);
navigator.geolocation.getCurrentPosition(function(position) {
clearTimeout(location_timeout);
var lat = position.coords.latitude;
var lng = position.coords.longitude;
geocodeLatLng(lat, lng);
}, function(error) {
alert("inside error ");
clearTimeout(location_timeout);
geolocFail();
});
} else {
alert("Turn on the location service to make the deposit");
// Fallback for no geolocation
geolocFail();
}
function geolocFail(){
alert("Turn on the location service to make the deposit");
document.write("Turn on the location service to make the deposit");
}
/*if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
alert("Geocoder failed");
} */
function initialize() {
geocoder = new google.maps.Geocoder();
}
function geocodeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
var add= results[0].formatted_address
alert(add);
//city data
//alert(city.short_name + " " + city.long_name)
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
</body>
</html>
This is HTML code to trace the device(Browser/Mobile) location .Just save the above file as .html extension and browse it from any browser on your system or Mobile ,it will display the user current location.

Resources