Google Maps Android - tracking location changes - java

I'm developing a tracking application, for which I would also like be able to continue tracking when the application is sent to background. For this purpose I implemented a LocationListener. But clearly I'm missing something here, because during runtime none of the debug printlns appear, so the application never enters any of the inherited LocationListener functions.
michal.myapp.activities;
import java.util.ArrayList;
import java.util.Calendar;
import michal.myapp.R;
import michal.myapp.db.DataSource;
import michal.myapp.model.Track;
import android.content.Context;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
/**
* #author Michał Szydłowski
*
* Class representing user's map activity with location change detection and sensors.
*
*/
public class MapActivity extends FragmentActivity implements LocationListener,
SensorEventListener{
private GoogleMap map;
private DataSource dataSource;
private SensorManager sensorManager;
private Sensor senAccelerometer;
private ArrayList <LatLng> trackPoints;
private boolean zoomEnabled;
private Button saveTrackButton;
private static final long INTERVAL = 1000;
private static final float ACCURACY = 20;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
initialize();
check();
saveTrackButton = (Button) findViewById(R.id.saveTrackButton);
saveTrackButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getDataFromPopupWindow();
}
});
}
private void check() {
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) != ConnectionResult.SUCCESS) {
System.out.println("yes");
}
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
Log.i("provider", "" + provider);
if (provider.equals("")) {
System.out.println("nope");
}
setUpMapIfNeeded();
}
private void initialize()
{
dataSource = new DataSource(this);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
senAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, senAccelerometer , SensorManager.SENSOR_DELAY_NORMAL);
trackPoints = new ArrayList <LatLng> ();
zoomEnabled = true;
}
private void getDataFromPopupWindow()
{
LayoutInflater layoutInflater
= (LayoutInflater)getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.save_track_window, null);
final PopupWindow popupWindow = new PopupWindow(
popupView,
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
final EditText editName = (EditText) popupView.findViewById (R.id.trackName);
editName.requestFocus();
Button btnDismiss = (Button)popupView.findViewById(R.id.cancel);
btnDismiss.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
popupWindow.dismiss();
}
});
Button btnSave = (Button) popupView.findViewById(R.id.save);
btnSave.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String trackName = editName.getText().toString();
saveTrack(trackName);
popupWindow.dismiss();
}
});
popupWindow.setFocusable(true);
popupWindow.update();
popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
popupWindow.showAtLocation(saveTrackButton, Gravity.CENTER, 0, 0);
}
/**
* Saves the track to database when finished
*/
private void saveTrack(String trackName){
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
String date = String.valueOf(year) + "-" + String.valueOf(month) + "-" + String.valueOf(day) ;
Track recordedTrack = new Track(trackName, trackPoints, date);
dataSource.open();
dataSource.insertTrack(recordedTrack);
dataSource.close();
}
/**
* Centers the view of the map around the current user's location.
* #param loc LatLng object representing user's current coordinates.
*/
private void zoom (LatLng loc)
{
if(zoomEnabled)
{
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16));
zoomEnabled = false;
}
}
/** Initializes the GoogleMap object if it hasn't been already done.
* If successful, enables location tracking.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (map == null) {
// Try to obtain the map from the SupportMapFragment.
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
map.setMyLocationEnabled(true);
// Check if we were successful in obtaining the map.
if (map != null) {
//setUpMap();
setUpMap();
}
}
}
private void setUpMap()
{
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, INTERVAL, ACCURACY, this);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
System.out.println("setupmap");
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
dataSource.close();
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
dataSource.open();
super.onResume();
setUpMapIfNeeded();
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
Sensor mySensor = event.sensor;
if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
if(event.values[0] > 15 || event.values[1] > 15 || event.values[2] > 15)
{
// Intent intent = new Intent(this, CameraActivity.class);
// startActivity(intent);
}
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
trackPoints.add(loc);
map.addPolyline(new PolylineOptions().addAll(trackPoints).width(5).color(Color.BLUE));
zoom (loc);
System.out.println("location changed");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
System.out.println("status changed");
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
System.out.println("provider enabled");
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
System.out.println("provider disabled");
}
}
I have the following permissions in my Android Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCELEROMETER"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
It is also worth mentioning, that I already try to attach an OnMyLocationChangeListener to my GoogleMap object, and it did track location changes, but not if the application was sent to background. Any ideas?

Related

Get user location: Android

So I have searched the internet for lots of different solutions to get my android phone to show current location through the Google Maps API using play services. I believe I have the right set-up but something is just not right.
Please see below the .java and .xml code.
Java
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.os.Bundle;
import android.provider.SyncStateContract;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private UiSettings mUiSettings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
android.support.v4.app.FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment mySupportMapFragment
= (SupportMapFragment) myFragmentManager.findFragmentById(R.id.map);
}
private void centerMapOnMyLocation() {
mMap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
Location location = mMap.getMyLocation();
// Getting latitude
double latitude = location.getLatitude();
// Getting longitude
double longitude = location.getLongitude();
LatLng latlng;
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(#NonNull String[] permissions, int requestCode)
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
Location myLocation = locationManager.getLastKnownLocation(provider);
if (location != null) {
//Create a LatLng object for the current location
latlng = new LatLng(latitude, longitude);
} else {
locationManager.requestLocationUpdates(provider, 20000, 0, (LocationListener) this);
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
tools:context="example.navigationapplication_10.MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
</LinearLayout>
Many thanks
Try using this class to get the Latitude and Longitude..
import android.app.AlertDialog.Builder;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
public class GPSTracker extends Service implements LocationListener {
private Context context;
boolean isGPSEnabled=false;
boolean isNetworkEnabled=false;
boolean canGetLocation=false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES=10;
private static final long MIN_TIME_BW_UPDATES=1000*60*1;
protected LocationManager locationManager;
public GPSTracker(Context context)
{
this.context=context;
getLocation();
}
public Location getLocation()
{
try{
locationManager=(LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled)
{
showSettingsAlert();
}
else{
this.canGetLocation=true;
if(isNetworkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager !=null)
{
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location !=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
if(isGPSEnabled){
if(location==null)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager !=null)
{
location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location !=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return location;
}
public void stopUsingGPS()
{
if(locationManager !=null)
{
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude()
{
if(location!=null)
{
latitude=location.getLatitude();
}
return latitude;
}
public double getLongitude()
{
if(location!=null)
{
longitude=location.getLongitude();
}
return longitude;
}
public boolean canGetLocation(){
return this.canGetLocation;
}
public void showSettingsAlert(){
Builder alertDialog=new Builder(context);
alertDialog.setTitle("GPS Settings");
alertDialog.setMessage("GPS is not enabled.Do you want to go to the settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
And for marking your position in the map
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
try {
gps = new GPSTracker(MapsActivity.this);
if (gps.canGetLocation) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
LatLng sydney = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(sydney).title("I am here"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
for(int i=0;i<MainActivity.nameArray.length;i++)
{
latitude=Double.parseDouble(MainActivity.latArray[i]);
longitude=Double.parseDouble(MainActivity.lonArray[i]);
LatLng shops = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(shops).title(MainActivity.nameArray[i]));
}
} else {
gps.showSettingsAlert();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Hope this Helps

how to send the data to server and update repeatedly in a certain time interval in android

this is my code of current location. i'm new to android so can anyone help me out ?
i need to send the current location to server and update it i certain time interval so that the user can fetch the location and display it on the map.it is basically a tracking device.
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.activity_main);
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
googleMap = supportMapFragment.getMap();
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
}
#Override
public void onLocationChanged(Location location) {
TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
}

Android Google Maps v2 not showing Compass and Location Icon

I am not able to show the compass icon and the my location icon either. I have the code googleMap.getUiSettings.setMyLocationButtonEnabled(true) and googleMap.getUiSettings().setCompassEnabled(true); but it is not showing on the maps.
package com.ctc.weathermap;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.Toast;
public class WeatherMapActivity extends Activity implements LocationListener {
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather_maps_main);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!enabledGPS) {
Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
else if(!enabledWiFi) {
Toast.makeText(this, "Network signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
initializeMap();
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
}
private void initializeMap() {
// check if map is created
if(googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); // creates the map
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Map could not be created", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
initializeMap();
}
#Override
public void onLocationChanged(Location location) {
googleMap.clear();
MarkerOptions marker = new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude()));
marker.title("Current location");
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
googleMap.addMarker(marker);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 16));
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
The rest of the code works such as markers and what not. I have tried putting the code for location and compass in initializeMap() but it still does not show up. I would appreciate any help. Thank you!
You havent enabled the my-location layer.Check this link for more details
So please do
googleMap.setMyLocationEnabled(true);
before
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
This will make your setMyLocationButton come up..
And,the compass icon will appear only if you rotate the map to not align to north.

Localisation Service doesn't start android

I'm working on an android map and i'm trying to use Service class to find the current location of users. I had already succeed to do that whitout Service (directly in the main activity) but given the fact that i'll do network operations to find adresses and points of interest i thinked it was a good training to try Service with current location.
But the problem is my service doesn't start at all even if i reported it in the manifest
my class which extends Service :
`
package toutel.testcarte;
import org.osmdroid.bonuspack.overlays.Marker;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
public class FindMe extends Service {
private MapView mapView;
private MapController mapController;
private LocationManager lm;
private LocationListener mylocationlistener = new LocationListener() {
public void onLocationChanged(Location location) {
// Context ctx = getApplicationContext();
GeoPoint myposition = new GeoPoint(location.getLatitude(),
location.getLongitude());
mapController.animateTo(myposition);
mapController.setCenter(myposition);
mapController.setZoom(17);
Marker marker = new Marker(mapView);
marker.setPosition(myposition);
marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
mapView.getOverlays().add(marker);
mapView.invalidate();
try {
Thread.sleep(5 * 1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
mapView.getOverlays().clear();
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
public IBinder onBind(Intent arg0) {
return null;
}
public void onCreate(Bundle savedInstanceState) {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0,
mylocationlistener);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0,
mylocationlistener);
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
public void onDestroy() {
super.onDestroy();
lm.removeUpdates(mylocationlistener);
}
}
`
Im starting the service in the main activity with
startService(new Intent(MainActivity.this, FindMe.class));
and i added the service in the manifest :
<service android:name = "toutel.testcarte.FindMe"> </service>
So what am i doing wrong ?
Thanks !

Android - GMapsV2 - Why is my activity not drawing the polyline?

I'm trying to get a red polyline to draw whenever the user moves. Here is the following code I have:
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationSource, LocationListener {
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
TextView tvLocInfo;
LocationManager myLocationManager = null;
OnLocationChangedListener myLocationListener = null;
Criteria myCriteria;
Location lastLocationloc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvLocInfo = (TextView)findViewById(R.id.locinfo);
FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment
= (MapFragment)myFragmentManager.findFragmentById(R.id.map);
myMap = myMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
myCriteria = new Criteria();
myCriteria.setAccuracy(Criteria.ACCURACY_FINE);
myLocationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_legalnotices:
String LicenseInfo = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(
getApplicationContext());
AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(MainActivity.this);
LicenseDialog.setTitle("Legal Notices");
LicenseDialog.setMessage(LicenseInfo);
LicenseDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS){
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS",
Toast.LENGTH_LONG).show();
//Register for location updates using a Criteria, and a callback on the specified looper thread.
myLocationManager.requestLocationUpdates(
0L, //minTime
0.0f, //minDistance
myCriteria, //criteria
this, //listener
null); //looper
//Replaces the location source of the my-location layer.
myMap.setLocationSource(this);
}else{
GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
}
}
#Override
protected void onPause() {
myMap.setLocationSource(null);
myLocationManager.removeUpdates(this);
super.onPause();
}
#Override
public void activate(OnLocationChangedListener listener) {
myLocationListener = listener;
}
#Override
public void deactivate() {
myLocationListener = null;
}
/*#Override
public void onLocationChanged(Location location) {
if (myLocationListener != null) {
myLocationListener.onLocationChanged(location);
double lat = location.getLatitude();
double lon = location.getLongitude();
tvLocInfo.setText(
"lat: " + lat + "\n" +
"lon: " + lon);
}
}*/
#Override
public void onLocationChanged(Location location) {
if (lastLocationloc == null) {
lastLocationloc = location;
}
LatLng lastLatLng = locationToLatLng(lastLocationloc);
LatLng thisLatLng = locationToLatLng(location);
//Log.e(TAG, "Last LatLng is :"+lastLatLng);
//Log.e(TAG, "Last LatLng is :"+thisLatLng);
myMap.addPolyline(new PolylineOptions().add(lastLatLng).add(thisLatLng).width(3).color(Color.RED));
lastLocationloc = location;
}
public static LatLng locationToLatLng(Location loc) {
if (loc != null)
return new LatLng(loc.getLatitude(), loc.getLongitude());
return null;
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
When I go to run application on an actual device nothing happens. No polyline appears. What am I doing wrong?

Categories