Android Tutorial: Geolocation of the user's phone on a GoogleMap V2 through a Marker
Geolocation of the phone on a GoogleMap
In a previous tutorial we learned how to integrate Google Maps V2 in an application.
This article is a continuation of the previous tutorial and could be performed only after completing the work presented in this tutorial: Integrating Google Map V2 in an Android app with Android Studio .
Now after integrating the Map. we will learn :
how to geo-locate the user's device on the Map through a marker.
To geo-locate the user we must implement the interface OnLocationListener. The code of our activity will explain better:
public class Map extends AppCompatActivity implements LocationListener{
LocationManager l;
GoogleMap gMap;
Marker marker;
String providerFine;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
gMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
marker=gMap.addMarker((new MarkerOptions().title("Vous êtes ici")
.position(new LatLng(0,0))));
}
public void getLocation()
{
l=(LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);
criteria.setPowerRequirement(Criteria.POWER_LOW);
// criteria.setAccuracy(Criteria.ACCURACY_FINE);
providerFine = l.getBestProvider(criteria, true);
l.requestLocationUpdates(providerFine,0,20,this);
}
@Override
protected void onResume() {
super.onResume();
getLocation();
}
@Override
public void onLocationChanged(Location location) {
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 8));
// marker.setPosition(new LatLng(location.getLatitude(), location.getLongitude()));
marker.setPosition(new LatLng(location.getLatitude(), location.getLongitude()));
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
getLocation();
}
@Override
public void onProviderDisabled(String provider) {
l.removeUpdates(this);
}
}
Finally do not forget to add the following two permissions to your manifest.xml :
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>

Commentaires
Enregistrer un commentaire
Your comment will be reviewed by moderators