Aug 7, 2012

Geolocation in Android

Géolocalisation dans Android


Geolocation in Android

In this section we will resume our tutorial "in Google Map integration Android" that allowed to view a Google map in the main activity of the application and add markers.

 
 

  • LocationListener 
To use the services of geolocation android, the first step is to implement the interface LocationListener in the core business of our project "HelloMap".
  • LocationManager class provides access to location services system.
LocationListener is used for receiving notifications of LocationManager when the position changes. The latter uses four required methods which are:

     OnLocationChanged (Location location) Called when the user's position changes.
     OnProviderDisabled (String provider): Called when the source (GPS or Network) is disabled.
     OnProviderEnabled (String provider): Called when the source (GPS or network) is enabled.
     OnStatusChanged (String provider, int status, Bundle extras): Called when the status of the source changes.



AndroidManifest.xml

First we will add the required permissions to access the location services and GPS:

android:name="android.permission.ACCESS_COARSE_LOCATION'' />
android:name="android.permission.ACCESS_FINE_LOCATION''/>

 
MainActivity.java

Our main class must implement the interface LocationListener as follows:


public class MainActivity extends MapActivity implements LocationListener {
 private MapView mapView = null;

private LocationManager lmanager;
private List  mapOverlays = null;
private OverlayItem overlayitem;
private GeoPoint point ;
private Drawable drawable;
private double lat, lng;
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// faire appel à notre vue principale qui contient la carte de Google maps setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite (true);
// ajouter le contrôleur de Zoom mapView.setBuiltInZoomControls(true);
// récupérer le service de localisation lmanager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// demander au service de localisation de nous notifier tout changement de position sur la source (GPS) lmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
// récupérer l’icône qui sera affichée sur la carte drawable = this.getResources().getDrawable(R.drawable.marker); }
@Override protected boolean isRouteDisplayed()
{ return false; }
// Lorsque la position change... public void onLocationChanged(Location location) {}
// Lorsque la source (GPS ou Réseau 3G…) est activée public void onProviderEnabled(String provider) {}
// Lorsque le statut de la source change public void onStatusChanged(String provider, int status, Bundle extras) {}
// Lorsque la source (GPS ou réseau GSM) est désactivée public void onProviderDisabled(String provider) {
// désactiver le service de Localisation et libérer les ressources
lManager.removeUpdates(this);
}}

  • OnLocationChanged

In this method we will recover the geographical coordinates of the terminal at each update (the frequency is defined through the method requestLocationUpdates ()). His details will be displayed to the user through a toast. We will also recover MapController class that will handle the zoom level of the map and animate it by changing the position of the terminal.
 
 @Override
public void onLocationChanged(Location location) {

if (location!=null)
{
// récupérer la liste "mapOverlays" des overlay ajoutés à notre MapView mapOverlays = mapView.getOverlays();
lat = location.getLatitude(); // récupérer la Latitude de la position courante
lng = location.getLongitude(); // récupérer la Longitude de la position courante
// si "mapOverlays" est videif (mapOverlays.size()==0)
{
// ajouter un marqueur sur la position actuelle du terminal newPosition();
}else {
// supprimer tous les éléments de la liste mapOverlays.clear();
newPosition();
}} }
 
Here is the method to retrieve the position of the terminal and add a marker on the map:
 
public void newPosition (){
 // créer un géopoint à partir de la position courante du terminal
point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));

// ajouter un marqueur sur la position courante du terminal overlayitem = new OverlayItem(point, "Orange DevCenter", "je suis au dev center");
// instancier la classe "HelloItemizedOverlay" HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, MainActivity.this);
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
mapView.invalidate(); // rafraichir la carte
Toast.makeText(getBaseContext(),
"Votre nouvelle position est: Latitude = " + (lat * 1E6) + " Longitude = " + (lng * 1E6),
Toast.LENGTH_SHORT).show(); // afficher la nouvelle position dans un Toast
mapView.getController().animateTo(point); // centrer la carte sur la position du terminal
mapView.getController().setZoom(12); // définir le niveau de zoom 12 }
 
  • Test

To test the geolocation service of our application, three options are available:

     Androphone:  Run application on an Android device physics and enable GPS
     Emulator:       Included with the SDK.
     A telnet client (PuTTYtel):   To use, just launch it and complete the fields below (Host Name: localhost and Port 5554). Regarding geolocation command is: geo fix latitude longitude.

In the event that you will use the Android emulator: In view of DDMS eclipse, you have the window "Emulator Control" in which he has the "Rent Control" where you can send your coordinates to emulator by entering the longitude and latitude of a given position.
 
 

No comments:

Post a Comment