Skip to content

Instantly share code, notes, and snippets.

@strfle
Created April 12, 2013 03:43
Show Gist options
  • Save strfle/5369164 to your computer and use it in GitHub Desktop.
Save strfle/5369164 to your computer and use it in GitHub Desktop.
Here is a plugin for PhoneGap Apache Cordova 2.1.0 or below that gets the GPS reliably. The built in navigator.geolocation does not work on the S3, HTC One, Note etc. So this is a native plugin to get that reliably everytime.
var GPSplugin = {
show: function (success, fail, resultType) {
return cordova.exec( success, fail, "GPSPlugin", "nativeAction", [resultType]);
}
};
//Call GPS
GPSplugin.show(onSuccess, onError, "go" );
//onSucces Function
var onSuccess = function(position) {
console.log('on success');
var n=position.split("|");
latx = n[2];
longx = n[1];
console.log(longx);
console.log(latx);
//Send Latitude and Longitude wherever it needs to go
searchLocationsNear(1,n[1],n[2]);
}
// onError Callback receives a PositionError object
//
var onError = function(error) {
alert('Unable to get approximate position. Enter in a location or zip and try again');
window.location = "index.html"
}
//package com.yourpackagename;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.util.Log;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import android.app.Activity;
public class GPSPlugin extends Plugin {
public static int GET_GEONAME_URL = 0;
public static int RESULT_OK = 0;
private String callbackId;
@Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
String s = args.toString();
PluginResult result = null;
Log.d("start activity","strat");
Log.d("GETGPS", "here");
double [] gps = getGPS(this.cordova.getActivity().getApplicationContext());
String[] s1 = new String[gps.length];
String me = "";
for (int i = 0; i < s1.length; i++){
s1[i] = String.valueOf(gps[i]);
me += "|" + s1[i];
Log.d("GETGPS",me);
}
Log.d("amount",me);
if(me.equals("|0.0|0.0")){
Log.d("failure",me);
return new PluginResult(PluginResult.Status.ERROR);
} else {
Log.d("success",me);
return new PluginResult(PluginResult.Status.OK, me);
}
}
private double[] getGPS(Context context) {
LocationManager lm = (LocationManager) this.cordova.getActivity().getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
/*
* Loop over the array backwards, and if you get an accurate location,
* then break out the loop
*/
Location l = null;
for (int i = providers.size() - 1; i >= 0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null)
break;
}
double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment