How To Show Current Position Marker On Map In Android?
I am developing an application in which I want to display current location using marker in my map. I am using Google Map v2. Here I can display Map and marker when GPS is off ,but
Solution 1:
Use below code it worked for me:
@OverridepublicvoidonLocationChanged(Location location) {
map.clear();
MarkerOptionsmp=newMarkerOptions();
mp.position(newLatLng(location.getLatitude(), location.getLongitude()));
mp.title("my position");
map.addMarker(mp);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
newLatLng(location.getLatitude(), location.getLongitude()), 16));
}
Solution 2:
Try this,it is showing current location:
privatevoidinitilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// to set current location
googleMap.setMyLocationEnabled(true);
// check if map is created successfully or notif (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
Solution 3:
Try this:-
privatevoidinitMap() {
if (googleMap != null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// to set current location
googleMap.setMyLocationEnabled(true);
Marker pos_Marker = googleMap.addMarker(new MarkerOptions().position(starting).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_laumcher)).title("Starting Location").draggable(false));
pos_Marker.showInfoWindow();
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(START_locationpoint, 10));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15),2000, null);
// check if map is created successfully or notif (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
Solution 4:
Use this. It works for me.
@OverridepublicvoidonLocationChanged(Location location) {
map.clear();
mp1 = newMarkerOptions();
mp1.position(newLatLng(location.getLatitude(),
location.getLongitude()));
mp1.draggable(true);
mp1.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
map.addMarker(mp1);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
newLatLng(location.getLatitude(), location
.getLongitude()), 20));
}
Solution 5:
You may try this:
publicclassMapsActivityextendsAppCompatActivityimplementsOnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
private Circle mCircle;
doubleradiusInMeters=100.0;
intstrokeColor=0xffff0000; //Color Code you wantintshadeColor=0x44ff0000; //opaque red fill@OverrideprotectedvoidonCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
getSupportActionBar().setTitle("Map Location Activity");
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
@OverridepublicvoidonPause() {
super.onPause();
//stop location updates when Activity is no longer activeif (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
@OverridepublicvoidonMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
//mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);//Initialize Google Play Servicesif (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
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protectedsynchronizedvoidbuildGoogleApiClient() {
mGoogleApiClient = newGoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@OverridepublicvoidonConnected(Bundle bundle) {
mLocationRequest = newLocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
@OverridepublicvoidonConnectionSuspended(int i) {}
@OverridepublicvoidonConnectionFailed(ConnectionResult connectionResult) {}
@OverridepublicvoidonLocationChanged(Location location)
{
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location markerLatLnglatLng=newLatLng(location.getLatitude(), location.getLongitude());
MarkerOptionsmarkerOptions=newMarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
CircleOptionsaddCircle=newCircleOptions().center(latLng).radius(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(8);
mCircle = mGoogleMap.addCircle(addCircle);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updatesif (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
publicstaticfinalintMY_PERMISSIONS_REQUEST_LOCATION=99;
privatevoidcheckLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block// this thread waiting for the user's response! After the user// sees the explanation, try again to request the permission.newAlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", newDialogInterface.OnClickListener() {
@OverridepublicvoidonClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MapsActivity.this,
newString[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
newString[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
@OverridepublicvoidonRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the// location-related task you need to do.if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other// permissions this app might request
}
}
Post a Comment for "How To Show Current Position Marker On Map In Android?"