I'm trying to use maui webView to load a map.
how to use navigator.geolocation.getCurrentPosition to get location?
Android and kotlin has the same implementation。
You and use the code to get the location:
private CancellationTokenSource _cancelTokenSource;
private bool _isCheckingLocation;
public async Task GetCurrentLocation()
{
try
{
_isCheckingLocation = true;
GeolocationRequest request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10));
_cancelTokenSource = new CancellationTokenSource();
Location location = await Geolocation.Default.GetLocationAsync(request, _cancelTokenSource.Token);
if (location != null)
Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");
}
catch (Exception ex)
{
// Unable to get location
}
finally
{
_isCheckingLocation = false;
}
}
public void CancelRequest()
{
if (_isCheckingLocation && _cancelTokenSource != null && _cancelTokenSource.IsCancellationRequested == false)
_cancelTokenSource.Cancel();
}
Here is the website which you can refer to: https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/device/geolocation?tabs=ios
Related
I'm building a class that tracks orders origin to deliver packages, im getting an error message that states that FusedLocationProviderApi is deprecated and seems now i have to use FusedLocationProviderClient instead, when i applied FusedLocationProviderApi i also implemented a LocationListener a ConnectionCallback and GoogleaApiClient which i suppose should be removed.
how can i implemente this here
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tracking_order);
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
requestRuntimePermission();
}
else
{
if (checkPlayServices())
{
buildGoogleApiClient();
createLocationRequest();
}
}
displayLocation();
}
private void displayLocation() {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
requestRuntimePermission();
}
else
{
mLastLocation = LocationServices.fused(null).getLastLocation(mGoogleApiClient);
if (mLastLocation != null)
{
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
LatLng yourLocation = new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(yourLocation).title("Tu ubicacion"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(yourLocation));
mMap.animateCamera(CameraUpdateFactory.zoomTo(17.0f));
}
else
{
Toast.makeText(this, "No se pudo obtener ubicacion", Toast.LENGTH_SHORT).show();
}
}
}
ended up with a new approach that worked finer
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tracking_order);
mService = Common.geoCodeService();
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mapFrag = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
public void onMapReady(GoogleMap googleMap)
{
mMap=googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(120000); // two minute interval
mLocationRequest.setFastestInterval(120000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mMap.setMyLocationEnabled(true);
}
}
LocationCallback mLocationCallback = new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
Log.i("MapsActivity", "Location: " + location.getLatitude() + " " + location.getLongitude());
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng yourLocation = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(yourLocation);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(yourLocation, 11));
//after add marker for your location add marker for this order
drawRoute(yourLocation,Common.currentRequest.getAddress());
}
}
};
I'm trying to build a background service which is able to log the data and save it into a SQLite database at a specific time interval without user consent.
So far:
I was able to start the services and toast current LastKnownLocation. This just to see if the variable is okay before I insert it to SQLite table.
However, if the GPS is not active the application will crash.
What's wrong with my code, and how to make it auto change when location changes?
public class SpycareServices extends Service {
/*Location Listener Declaration*/
PhoneInfo myPhone;
Util myFunction;
private LocationListener listener;
private LocationManager locationManager;
boolean gps_enabled = false;
boolean network_enabled = false;
Location net_loc = null, gps_loc = null, finalLoc = null;
public double longitude,latitude;
/*Declare SharedPref StartService*/
public SpycareServices(){
}
/*Declare constructor for location listener*/
public SpycareServices(Context context){
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate(){
/*Instantiate listener*/
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//Check which provider active
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(gps_enabled)
{
gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if(network_enabled)
{
net_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//net_loc = locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,3000,0,listener);
}
/*If both gps and network has value, choose the better one*/
if (gps_loc != null && net_loc != null) {
//smaller the number more accurate result will
if (gps_loc.getAccuracy() > net_loc.getAccuracy()){
finalLoc = net_loc;
//
}
else{
finalLoc = gps_loc;
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,listener);
}
} else {
if (gps_loc != null) {
finalLoc = gps_loc;
} else if (net_loc != null) {
finalLoc = net_loc;
}
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
Toast.makeText(getApplicationContext(),"Services Has Been Started!",Toast.LENGTH_SHORT).show();
//Instance util to get timestamp
myFunction = new Util(this);
Toast.makeText(getApplicationContext(),"My time "+ myFunction.getTimestamp(this),Toast.LENGTH_SHORT).show();
//Instance Imei
myPhone = new PhoneInfo(this);
Toast.makeText(getApplicationContext(),"My Imei "+ myPhone.betaGetImei(this),Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"My Location Provider is "+ finalLoc.getProvider(),Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"My Longitude is "+ finalLoc.getLongitude(),Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"My Latitude is "+ finalLoc.getLatitude(),Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onDestroy(){
Toast.makeText(getApplicationContext(),"Services Has Been Destroyed!",Toast.LENGTH_SHORT).show();
//super.onDestroy();
//Prevent memory leaks by deregister listener when destroyed
if(locationManager!=null){
locationManager.removeUpdates(listener);
}
}
I notice that Parse Unity support still doesn't provide push notification for iOS.
Has anyone implemented a Unity plugin or another solution to support iOS Push Notifications via Parse?
(Cross posted on Unity Answers.)
It's actually possible now, using a ParseObject to mock up the ParseInstallation object.
Gist here: https://gist.github.com/gfosco/a3d092651c32ba3385e6
Explanation in the Parse Google Group: https://groups.google.com/d/msg/parse-developers/ku8-r91_o6s/6ioQ9T2TP7wJ
Attach this script to a GameObject, replace the important parts with your own:
using UnityEngine;
using System.Collections;
using Parse;
public class PushBehaviorScript : MonoBehaviour {
bool tokenSent = false;
public ParseObject currentInstallation = null;
void Start () {
if (PlayerPrefs.HasKey ("currentInstallation")) {
string objId = PlayerPrefs.GetString ("currentInstallation");
currentInstallation = ParseObject.CreateWithoutData ("_Installation", objId);
}
if (currentInstallation == null) {
#if UNITY_IPHONE && !UNITY_EDITOR
NotificationServices.RegisterForRemoteNotificationTypes (RemoteNotificationType.Alert | RemoteNotificationType.Badge | RemoteNotificationType.Sound);
#endif
}
}
void FixedUpdate () {
if (!tokenSent && currentInstallation == null) {
#if UNITY_IPHONE && !UNITY_EDITOR
byte[] token = NotificationServices.deviceToken;
if(token != null) {
tokenSent = true;
string tokenString = System.BitConverter.ToString(token).Replace("-", "").ToLower();
Debug.Log ("OnTokenReived");
Debug.Log (tokenString);
ParseObject obj = new ParseObject("_Installation");
obj["deviceToken"] = tokenString;
obj["appIdentifier"] = "com.parse.unitypush";
obj["deviceType"] = "ios";
obj["timeZone"] = "UTC";
obj["appName"] = "UnityPushTest";
obj["appVersion"] = "1.0.0";
obj["parseVersion"] = "1.3.0";
obj.SaveAsync().ContinueWith(t =>
{
if (obj.ObjectId != null) {
PlayerPrefs.SetString ("currentInstallation", obj.ObjectId);
}
});
}
#endif
}
}
}
To implement iOS push with parse.com You need to get the token from apple first. Then save Current instalation
Unity does have this functionality build in now.
//push notification
bool tokenSent = false;
void RegisterForPush()
{
Debug.Log("Register for push");
tokenSent = false;
#if UNITY_IOS
UnityEngine.iOS.NotificationServices.RegisterForNotifications(NotificationType.Alert |
NotificationType.Badge |
NotificationType.Sound, true);
#endif
}
void Update () {
if (!tokenSent) {
byte[] token = UnityEngine.iOS.NotificationServices.deviceToken;
if (token != null) {
// send token to a provider
tokenSent = true;
string hexToken = "%" + System.BitConverter.ToString(token).Replace('-', '%');
#if UNITY_IOS
ParseManager.instance.RegisterForPush(hexToken);
#endif
}
}
}
And inside ParseManager (or whatever class you use to manage parse>client communication)
public void RegisterForPush(string token) {
Debug.Log("Parse updating instalation");
ParseInstallation instalation = ParseInstallation.CurrentInstallation;
instalation["deviceToken"] = token;
instalation["user"] = ParseUser.CurrentUser.ObjectId;
instalation["timeZoneOffset"] = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
instalation.SaveAsync();
}
Tested on Unity 5.1.2 and iOS 8.4
I can't get my locayion. It always crashes. I checked everything. Can anyone please help me find my location?
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
if(isGooglePlay()){
setContentView(R.layout.map);
setupmapifneeded();
}
}
private void setupmapifneeded() {
if(map==null){
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}if(map!=null){
map.setMyLocationEnabled(true);
LocationManager mlm = (LocationManager)getSystemService(LOCATION_SERVICE);
Criteria c = new Criteria();
String provider = mlm.getBestProvider(new Criteria(), false);
if(provider == null){
onProviderDisabled(provider);
}
Location mylocation = mlm.getLastKnownLocation(provider);
if(mylocation != null){
onLocationChanged(mylocation);
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
private boolean isGooglePlay(){
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(status == ConnectionResult.SUCCESS){
return true;
}else{
((Dialog)GooglePlayServicesUtil.getErrorDialog(status, this, 10)).show();
//Toast.makeText(this, "nai", Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public void onLocationChanged(Location mylocation) {
double lat = mylocation.getLatitude();
double longi = mylocation.getLongitude();
LatLng latlng = new LatLng(lat,longi);
map.moveCamera(CameraUpdateFactory.newLatLng(latlng));
map.animateCamera(CameraUpdateFactory.zoomTo(10));
}
you can simply use
map.setMyLocationEnabled(true)
this will get your location on the map automatically.
Location location = map.getMyLocation();
Currently my location not updating when I change it to different location via emulator. But it will change after I restart my application. This is what I write when the app launch
private void Application_Launching(object sender, LaunchingEventArgs e)
{
IsolatedStorageSettings Settings = IsolatedStorageSettings.ApplicationSettings;
GeoCoordinate DefaultLocation = new GeoCoordinate(-6.595139, 106.793801);
Library.GPSServices MyGPS;
if (!Settings.Contains("FirstLaunch") || (bool)Settings["FirstLaunch"] == true)
{
Settings["FirstLaunch"] = false;
Settings["LastLocation"] = DefaultLocation;
Settings["SearchRadius"] = 1;
}
//If key not exist OR key value was set to false, ask for permission to use location
if (!Settings.Contains("LocationService") || (bool)Settings["LocationService"] == false)
{
var result = MessageBox.Show(
"Jendela Bogor need to know your location to work correctly, do you want to allow it?",
"Allow access to your location?",
MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
Settings["LocationService"] = true;
MyGPS = new Library.GPSServices();
}
else
{
Settings["LocationService"] = false;
}
Settings.Save();
}
else if ((bool)Settings["LocationService"] == true)
{
MyGPS = new Library.GPSServices();
}
}
I store my location in my application setting IsolatedStorage with name Settings["LastLocation"]
How should I do to constantly update my location in the Background using MVVM Pattern (MVVM-Light) so my PushPin on map in the ThirdPageView always updated?
EDIT
public GPSServices()
{
if ((bool)Settings["LocationService"] == true)
{
if (_watcher == null)
{
_watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
_watcher.MovementThreshold = 20;
}
StartWatcher();
_watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
_watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
}
else if ((bool)Settings["LocationService"] == false)
{
StopWatcher();
}
}
private void StartWatcher()
{
_watcher.Start();
}
private void StopWatcher()
{
if (_watcher != null)
_watcher.Stop();
}
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
if (e.Position.Location.IsUnknown)
{
MessageBox.Show("Please wait while your position is determined....");
return;
}
Settings["LastLocation"] = e.Position.Location;
Settings.Save();
}
System.Device.Location.GeoCoordinateWatcher provides what you need.
var geoWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
// This event fires every time the device location changes
geoWatcher.PositionChanged += (s, e) => {
//e.Position.Location will contain the current GeoCoordinate
};
geoWatcher.TryStart(false, TimeSpan.FromMilliseconds(2000));
is this helpful for you ? using GeocoordinateWatcher.PositionChanged event?
public Location()
{
GeoCoordinateWatcher location == new GeoCoordinateWatcher();
location.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(location_PositionChanged);
location.Start();
}
//event to track the location change
public void location_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
}