Getting Current Location using only GPS in Cordova/Phonegap - html

I use the geolocation plugin in Cordova 3.5. And I have coded as follow:
navigator.geolocation.getCurrentPosition(function(pos) {
var lat = pos.coords.latitude;
var lng = pos.coords.longitude;
alert("lat : "+lat+" lng : " +lng");
});
I am wandering whether this code can work to get lat lng without Internet connection and GPS on. If not, is there any solution to do so? Thank for your help.

Without Internet connection, there are still sources like Cell ID's, RFID and MAC addresses of devices you are connected to (e. g. WIFI routers, Bluetooth)
The code should work, but you can add a few things (Eventlistener and error alert in case that the position cannot be found):
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
function onSuccess(pos) {
var lat = pos.coords.latitude;
var lng = pos.coords.longitude;
alert("lat : " + lat + " lng : " + lng);
}
function onError(error) {
alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}
I know that for example the Google location API uses a cache for the latest known location, which can be read out anytime.
I am not sure if Cordova also uses something similar but it could be.

check if geolocation is properly installed or not
restart your phone (silly solution but it works sometimes.I faced it once)
check if your geo permissions & settings are turned on in device
test with this code
options = { enableHighAccuracy: true };
navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
If you're using android, try to get the error with eclipse logcat.
On iOS this will always work one way or the other. If the plugin fails, the browser's own Geolocation API will be used. There's some undesired side effects with the fallback though:
The permission dialog that pop's up has the html file's name in the title instead of the app name
Granted permissions will only persist as long as the app is running
On Android it only works if you have set the correct permissions in app/AndroidManifest.xml:
<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" />

As #jcesarmobile pointed out here Cordova geolocation plugin not getting location from GPS for Android:
They are using HTML5 geolocation implementation instead of native
code. They removed the android java code on release 0.3.7 of the
plugin
### 0.3.7 (Apr 17, 2014)
* CB-6422: [windows8] use cordova/exec/proxy
* CB-6212: [iOS] fix warnings compiled under arm64 64-bit
* CB-5977: [android] Removing the Android Geolocation Code. Mission Accomplished.
* CB-6460: Update license headers
* Add NOTICE file
Hope this helps

Related

Google Maps API - How to use custom icons with text?

I tried the following URL:
http://chart.apis.google.com/chart?chst=d_map_spin&chld=0.7|0|FFAA11|19|_|A
But it only works in Chrome, IE, surprise, does not work, the intention was to display an orange marker icon with a letter A in the middle!
I want to work in Internet Explorer, please someone help me!
I'm using IE 11.
The code is as follows:
var iconURL = ((selecionado != i) ?
'https://mts.googleapis.com/vt/icon/name=icons/spotlight/spotlight-waypoint-a.png&text=' + String.fromCharCode(65 + l) + '&psize=16&font=fonts/Roboto-Regular.ttf&color=ff333333&ax=44&ay=48&scale=1'
:
'http://chart.apis.google.com/chart?chst=d_map_spin&chld=0.7|0|FFAA11|19|_|' + String.fromCharCode(65 + l)
);
marker[i] = new google.maps.Marker({
position: ((i >= latln.length) ? latLonEmpresa : latln[i]),
map: map,
icon: ((titulo[i]) ? iconURL : '')
});
When I use https://chart.apis.google.com/chart?chst=d_map_spin&chld=0.7|0|FFAA11|19|_|A
It redirect to https and get error in IE:
There is a problem connecting securely to this website.
The security certificate presented by this website was issued for a different website's address.
Security certificate problems may indicate an attempt to fool you or intercept any data you send to the server.
Seem the certificate only for www.google.com
If you use: http://www.google.com/chart?chst=d_map_spin&chld=0.7|0|FFAA11|19|_|A seem working

Iphone is not able to open link to google maps directions

i have this code:
if(navigator.platform.indexOf("iPhone") != -1 || navigator.platform.indexOf("iPod") != -1 || navigator.platform.indexOf("iPad") != -1) {
window.open("https://maps.google.com?saddr=Current+Location&daddr=" + lat + "," + lon);
}
else {
window.open("https://www.google.com/maps/dir/Current+Location/" + lat + "," + lon);
//window.open("https://maps.google.com?saddr=Current+Location&daddr=" + lat + "," + lon);
}
I know that lon and lat have correct values. it works on all desktop browsers and on an android phone i have tested (gives me the directions), but when i window.open runs on the iphone it loads google maps and it says "route not found"..
is this code not supposed to work on and ios device?
You have two methods to embed Google Maps URL in your iOS app.
Using OpenInGoogleMapsController class.
URL Scheme method.
In the first one it is easy to build links to open a map (or display Street View or directions) directly in Google Maps for iOS. Rather than creating URLs by hand, you can create map requests using Objective-C classes and types, so you can take advantage of all the type-checking and code hinting you've come to expect from Xcode.
For Direction follow this code:
GoogleDirectionsDefinition *defn = [[GoogleDirectionsDefinition alloc] init];
defn.startingPoint =
[GoogleDirectionsWaypoint waypointWithQuery:#"221B Baker Street, London"];
defn.destinationPoint = [GoogleDirectionsWaypoint
waypointWithLocation:CLLocationCoordinate2DMake(51.498511, -0.133091)];
defn.travelMode = kGoogleMapsTravelModeBiking;
[[OpenInGoogleMapsController sharedInstance] openDirections:defn];
To launch the Google Maps app for iOS and optionally perform one of the supported functions, use a URL scheme of the following form:
comgooglemaps://?parameters
Use the Display Direction scheme to request and display directions between two locations. You can also specify the transportation mode.
An example URL is below to display transit directions between Google NYC and JFK Airport:
comgooglemaps://?saddr=Google+Inc,+8th+Avenue,+New+York,+NY&daddr=John+F.+Kennedy+International+Airport,+Van+Wyck+Expressway,+Jamaica,+New+York&directionsmode=transit
Hope tat Helps!!

HTML5 GEOLocation 2nd prompt

Is there a way to prompt user for geolocation again on some trigger, after they denied the location sharing?
navigator.geolocation.getCurrentPosition
fires it once, consecutive calls do not produce the same result. Cant find the answer anywhere/
Take a look at this Code Snippet and this SO Answer: What is the best JQuery plugin that handles HTML5 location?
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}else{
errorFunction();
}
function successFunction(position) { //uses HTML5 if available
var lat = position.coords.latitude;
var lng = position.coords.longitude;
}
function errorFunction(){ //uses IP if no HTML5
$.getJSON("http://freegeoip.net/json/", function(res){
var lat = res.latitude;
var lng = res.longitude;
});
}
Take a Look at this Fiddle Link also
JQuery Geolocator Plugin
In Geolocation API? No.
If user clicks deny permission it simply means "No, and don't bother me again..."
However user can do it by deleting Location-share-settings, then of course the prompt pops out again.
Or user can just change the settings if browser allows it, however e.g. Chrome manages these settings as exceptions (no matter whether user've allowed or denied permission) so user have to delete the settings, resp. exception anyway.
What now?
Your only option is to catch the error and use e.g. some external API to find the user's location by IP. You can program it by yourself or there are of course existing solutions as #Venkat suggested.
But be aware IP geolocation is a tricky one - sometimes it has an adress-number-accuracy sometimes it's just state-accuracy.
This examle from Mozilla's docs shows a nice example how to handle Geolocation errors:
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
console.log('Your current position is:');
console.log('Latitude : ' + crd.latitude);
console.log('Longitude: ' + crd.longitude);
console.log('More or less ' + crd.accuracy + ' meters.');
};
function error(err) {
/*
CALL EXTERNAL API HERE
*/
console.warn('ERROR(' + err.code + '): ' + err.message);
};
navigator.geolocation.getCurrentPosition(success, error, options);
The best option for this is to setup a geolocation subdomain, and load it in a iframe.
geo-0.domain.com
geo-1.domain.com
geo-2.domain.com
geo-3.domain.com
geo-4.domain.com
geo-N.domain.com
This will allow you unlimited attempts on every browser, all you need to do is program in your own retry logic.

Geolocation not working with HtmlService

I created the following two files:
code.gs
function doGet() {
var html = HtmlService.createHtmlOutputFromFile('html.html');
return html;
}
html.html
<html>
<body>
<p id="messaging">Click the button to get your coordinates:</p>
<button onclick="getLocation()">Where am I</button>
<script>
var message=document.getElementById("messaging");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
message.innerHTML="Geolocation is not supported.";
}
}
function showPosition(position) {
message.innerHTML="Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
When I call the published URL, I get the expected message and button. Click the button and I get my failure message "Geolocation is not supported". If I save html.html in a file and open it in a browser it works as expected.
Any ideas?
As of 2016, geolocation works with HtmlService in IFRAME mode. Test it here: GAS-geolocation
Tested with Chrome and Firefox (desktop), both ok. Doesn't work with Safari (desktop) (the share location confirmation box doesn't popup. I hate Safari!)
Funny thing is, it works with Safari on iOS 9 but not the latest Chrome on iOS 9. (same issue, no confirmation popup)
GeoLocation is not yet available in HtmlService
I believe, Caja is culprit here. Could you run your code on Caja playground to check if the behavior is same. If same, you may open an issue in Caja Issue Tracker
To know more what Caja does with HtmlService, you may refer to this page.
Update
Above answer is obsolete. Now one can access location using navigator.geolocation object available in browser.
I just tried your code, as I'd like to do something with Google Apps Script in Google Sites.
It appears that GeoLocation is still not supported in HTMLService at this time, but I found a possible workaround for my specific need (i.e. in conjunction with Google Sites) that may help someone else too :
What does work, is to create a custom "Google Sites Gadget"
using the example code from tutorials point
I end up with a 'skeleton' XML file for my gadget as such :
<?xml version="1.0" encoding="UTF-8"?>
<Module>
<ModulePrefs title="GeoLocation"
>
</ModulePrefs>
<Content type="html"><![CDATA[
<form>
<input type="button" onclick="getLocation();"
value="Get Location"/>
</form>
<script>
function showLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude : " + latitude + " Longitude: " + longitude);
}
function errorHandler(err) {
if(err.code == 1) {
alert("Error: Access is denied!");
}else if( err.code == 2) {
alert("Error: Position is unavailable!");
}
}
function getLocation(){
if(navigator.geolocation){
// timeout at 60000 milliseconds (60 seconds)
var options = {timeout:60000};
navigator.geolocation.getCurrentPosition(showLocation,
errorHandler,
options);
}else{
alert("Sorry, browser does not support geolocation!");
}
}
</script>
]]></Content>
</Module>
Now instead of the alerts, I can pass the results to the Google Apps Scripts Web App as a URL parameter.
It's not ideal, but seems to work ok so far.

Google Maps Custom Projection

I have created a custom Google Maps projection using the Google Maps Javascript API V2. It looks like this, as per the API specification:
function PProjection(levels) {
this.fromLatLngToPixel = function(latlng, zoom) {
...
};
this.fromPixelToLatLng = function(pixel, zoom) {
...
};
this.tileCheckRange = function(tile, zoom, tilesize) {
...
};
this.getWrapWidth = function(zoom) {
...
};
}
Previously, I had my version of the API set to 2.147 and everything worked fine. However, Google recently made the lowest version available 2.193. This new version breaks my projection. Whenever I try to add a marker, I get the following error in Firebug:
d.getNearestImage is not a function
According to this post a new method called
GProjection.getNearestImage(pixel,zoom,centrepixel)
was added in version 2.148, so it kind of makes sense that this problem would occur if I used a version of the API above 2.147. However, there is no note in the reference manual of an official change in the API. I added a dummy method of this name to my projection, but no luck. Any ideas on how to fix my projection or on how to revert to 2.147?
You can request a specific version through this method: http://groups-beta.google.com/group/google-maps-api/web/javascript-maps-api-versioning