Google xarita androidda markerni GPS bilan olib boring

Belgini Google MAP ga ko'chirishni istayman, gps esa UBER ilovasida bo'lgani kabi o'zgaradi. Men ba'zi echimlar topdim, ammo muammoimni hal qila olmayapman. Ushbu echimlar 1 va 2

Quyida mening onLocationChange() usuli mavjud

public void onLocationChanged(Location location) {

    double lattitude = location.getLatitude();
    double longitude = location.getLongitude();

    mLastLocation = location;
    if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
    }
    //Place current location marker
    LatLng latLng = new LatLng(lattitude, longitude);
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("I am here");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));

    mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

    tv_loc.append("Lattitude: " + lattitude + "  Longitude: " + longitude);

    //move map camera
    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

    //stop location updates
    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }

}

1-yangilash (qayta tahrirlangan)

Ko'proq tushunish uchun men bir nechta qo'shimcha kodni qo'shmoqdaman, lekin birinchi bo'lib men ilovada ichki oynalarni ishlataman. Birinchi yorlig'i mening xaritamda. Shuning uchun uning qismlarini ishlataman.

public class MyLocation extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
LocationListener{

GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker=null;
TextView tv_loc;
private static View view;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    if(view != null)
    {
        ViewGroup viewGroupParent = (ViewGroup)view.getParent();
        if(viewGroupParent !=null)
        {
            viewGroupParent.removeView(viewGroupParent);
        }
    }
    try{
        view = inflater.inflate(R.layout.my_location,container, false);
    }catch (Exception e)
    {
         /* map is already there, just return view as it is */
        return  view;
    }

   //inflat and return the layout
    //View rootView = inflater.inflate(R.layout.my_location, container, false);

    tv_loc = (TextView)view.findViewById(R.id.textView);
    mapFrag = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
    mapFrag.getMapAsync(this);

    return view;

}

@Override
public void onPause() {
    super.onPause();

    //stop location updates when Activity is no longer active
    if(mGoogleApiClient !=null)
    {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }

}


@Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap=googleMap;
    mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    //Initialize Google Play Services
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(getActivity(),
                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);
    }
}

protected synchronized void buildGoogleApiClient() {

    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    if (ContextCompat.checkSelfPermission(getActivity(),
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

}

@Override
public void onConnectionSuspended(int i) {

}


@Override
public void onLocationChanged(Location location) {

    double lattitude = location.getLatitude();
    double longitude = location.getLongitude();

    //Place current location marker
    LatLng latLng = new LatLng(lattitude, longitude);


    if(mCurrLocationMarker!=null){
        mCurrLocationMarker.setPosition(latLng);
    }else{
        mCurrLocationMarker = mGoogleMap.addMarker(new MarkerOptions()
                .position(latLng)
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
                .title("I am here"));
    }

    tv_loc.append("Lattitude: " + lattitude + "  Longitude: " + longitude);
    mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));

    //stop location updates
    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }
    /*double lattitude = location.getLatitude();
    double longitude = location.getLongitude();

    mLastLocation = location;
    if (mCurrLocationMarker != null) {
        //mGoogleMap.clear();
        mCurrLocationMarker.remove();
    }
    //Place current location marker
    LatLng latLng = new LatLng(lattitude, longitude);
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("I am here");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)).draggable(true);

    mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
    mCurrLocationMarker.setPosition(new LatLng(lattitude,longitude));

    tv_loc.append("Lattitude: " + lattitude + "  Longitude: " + longitude);

    //move map camera
    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

    //stop location updates
    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }*/
}

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {

    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

       //Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                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.
            new AlertDialog.Builder(getActivity())
                    .setTitle("Location Permission Needed")
                    .setMessage("This app needs the Location permission, please accept to use location functionality")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //Prompt the user once explanation has been shown
                            ActivityCompat.requestPermissions(getActivity(),
                                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                    MY_PERMISSIONS_REQUEST_LOCATION );
                        }
                    })
                    .create()
                    .show();


        } else {
           //No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION );
        }
    }
}


@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {

    /*super.onRequestPermissionsResult(requestCode, permissions, 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(getActivity(), 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.
                //finish();
                Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
            }
            return;
        }
       //other 'case' lines to check for other
       //permissions this app might request
    }
}


@Override
public void onResume()
{
    super.onResume();
}

@Override
public void onDestroy() {
    super.onDestroy();
}

@Override
public void onLowMemory() {
    super.onLowMemory();
}


@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}}

Har qanday yordam juda yuqori baholanadi

15
Buni ishlatganim yo'q, lekin uni ishlatmaslik kerak
qo'shib qo'ydi muallif Moeez, manba
mCurrLocationMarker.remove() o'rniga mGoogleMap.clear() harakat qilib ko'ring
qo'shib qo'ydi muallif Fernando Gallego, manba
Tez savol, qani bu usul? Faoliyat, xizmat, ilovada? Faoliyatda siz faoliyatga qaytguncha ishlaysizmi yoki faqat ishlamayapsizmi? Sizga yordam berish uchun ko'proq kodni ko'rishimiz kerak. Bu usul asosan qaerda joylashgan.
qo'shib qo'ydi muallif Pablo Baxter, manba
Buni stackoverflow.com/a/42778943/7399521 dan foydalaning.
qo'shib qo'ydi muallif Akash pasupathi, manba

8 javoblar

Markerning manzilini yangilash uchun quyidagi kodni ishlatishingiz mumkin

public void onLocationChanged(Location location) {

    double lattitude = location.getLatitude();
    double longitude = location.getLongitude();

    //Place current location marker
    LatLng latLng = new LatLng(lattitude, longitude);


    if(mCurrLocationMarker!=null){
        mCurrLocationMarker.setPosition(latLng);
    }else{
        mCurrLocationMarker = mGoogleMap.addMarker(new MarkerOptions()
                                .position(latLng)
                                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
                                .title("I am here");
    }

    tv_loc.append("Lattitude: " + lattitude + "  Longitude: " + longitude);
    gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));

    //stop location updates
    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }

}

Har safar xaritani tozalashga hojat yo'q. Belgini Markerga qo'shish paytida qaytariladigan Marker obyekti orqali buni amalga oshirishingiz mumkin. Umid qilamanki sizga yordam beradi.

12
qo'shib qo'ydi
Bir narsani so'rashni istardim, chunki joylashuv yangiligi yangilangan bo'lsa, unda nega ko'k nuqta bir joydan ikkinchisiga ko'chib ketadi, chunki qurilmam hali ham joylangan va u harakatga kelmaydi. Bunga o'xshash gpsni tutish normalmi? Bundan tashqari markerning harakatlanishi asl joydan uzoq emas.
qo'shib qo'ydi muallif Moeez, manba
Men allaqachon sinab ko'rdim va u ishlaydi, lekin yuqoridagi matn yuqoridagi satrni to'ldiradi, ya'ni kenglik va uzunlikning matn ko'rinishi avvalgi ko'rsatilishicha yana va yana ko'rsatishda davom etadi.
qo'shib qo'ydi muallif Moeez, manba
Bundan tashqari, har doim onLocationChange usuli chaqiriladi. Mening yangilash kodimni ham ko'rishingiz mumkin
qo'shib qo'ydi muallif Moeez, manba
manzilni yangilashni to'xtatish bu manzilni yangilashni to'xtatadi, shuning uchun markerni ko'chirmang. Bu mening fikrimcha xato bo'lishi mumkin
qo'shib qo'ydi muallif Moeez, manba
Kodingizni tekshirib ko'rdingiz, lekin ko'k nuqta harakatlanayotganda marker bir xil holatidadir. Pim harakatlanayotganda ko'k nuqta ustiga o'rnatilgan bo'lishi kerak
qo'shib qo'ydi muallif Moeez, manba
Iltimos, to'xtatib turilgan Joylashuvni yangilab turish kodini olib tashlang. Va yana. Agar iloji bo'lsa, barcha faoliyatingiz kodini yuklab qo'ying. Nima uchun yangilanib turilmayotganligi haqida aniq tasavvurga ega bo'lasiz
qo'shib qo'ydi muallif Mushahid Khatri, manba
Kodingizni tekshirib chiqqandan so'ng, siz Joylashtirilgan o'zgarishlardan Joylashuv yangiliklarini olib tashlayapsiz. Birinchi marta bu Manzilni o'zgartirish tadbirini chaqiradi. U Markerni xaritaga qo'shadi va keyingi qatorni o'chirib qo'yadi Joylashuvni yangilash. shuning uchun hozirda joy o'zgartirilganda hodisa hech qachon qayta chaqirilmaydi. Natijada sizning joylashuvingizdagi o'zgarishingiz faqat bir marta chaqiriladi, shuning uchun sizning markerlaringiz joylashuvi yangilangan holatda bo'lmaydi. RemoveLocationUpdate-ni o'chirish uchun chiziqlarni olib tashlang va joylashuvni yangilab turadigan belgini ko'rasiz. Hali ham muammolar mavjudligini bilib qo'ying.
qo'shib qo'ydi muallif Mushahid Khatri, manba
Iltimos, onLocationChanged hodisangizni tekshirishga ruxsat bera olasizmi? Shuningdek, ko'k pin standart xaritadir va ular joyni o'zgartirish uchun turli xil mantiqdan foydalanishi mumkin. SetPostion usulini qiymatlarni qattiq kodlash orqali tekshirishingiz mumkin va pozitsiyaning o'zgarganligini tekshirishingiz mumkin. Men ham xuddi shunday harakat qildim va u o'zgarib boryapti.
qo'shib qo'ydi muallif Mushahid Khatri, manba
Siz foydalangan API-ning vazifasi. Bu sizning joylashuvingizga ham bog'liq. Agar ochiq havoda bo'lsangiz, u aniqroq bo'ladi. Agar siz Lift kabi metallarning atrofida bo'lsangiz yoki undan kamroq ma'lumotga ega bo'lsangiz. Hali ham aniqroq natijaga erishish uchun "Joylashuvdagi birinchi o'ringa" so'rovini belgilashingiz mumkin. Rahmat
qo'shib qo'ydi muallif Mushahid Khatri, manba

Birinchidan, Siz ActivityList joylashuvini amalga oshirasiz

agar siz faqat bitta Markerni ko'rsatishingiz kerak bo'lsa (markerni yangilash holati), quyidagini tanlang:

private Marker currentPositionMarker = null;

 @Override
    public void onLocationChanged(Location location) {

      LatLng  latLng = new LatLng(location.getLatitude(), location.getLongitude());
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(latLng).zoom(14).build();

       //mMap.clear();//Call if You need To Clear Map
        if (currentPositionMarker == null)
            currentPositionMarker = mMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
                    .position(latLng)
                    .zIndex(20));
        else 
            currentPositionMarker.setPosition(latLng);


        mMap.animateCamera(CameraUpdateFactory
                .newCameraPosition(cameraPosition));
    }

yoki har safar yangi belgini qo'shishni xohlasangiz:

 @Override
    public void onLocationChanged(Location location) {

        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(latLng).zoom(14).build();

        mMap.addMarker(new MarkerOptions()
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
                .position(latLng)
                .zIndex(20));

        mMap.animateCamera(CameraUpdateFactory
                .newCameraPosition(cameraPosition));
    } 

joylashuv tez o'zgargan bo'lsa, ilova joylashuv belgisini yangilash uchun bir necha soniya kerak bo'ladi

4
qo'shib qo'ydi

buni ishlatish

implement LocationListener ,GoogleMap.OnMyLocationChangeListener in your map activity

joylashish o'zgaruvchisi dan foydalaning

   @Override
public void onMyLocationChange(Location location) { //mMap.clear //if you want refresh map remove comand
   //Getting latitude of the current location
    double latitude = location.getLatitude();

   //Getting longitude of the current location
    double longitude =location.getLongitude();

   //Creating a LatLng object for the current location
    LatLng latLng = new LatLng(latitude, longitude); //your_text_view.settext(latitude+","+longtitudde)

   //Showing the current location in Google Map
  mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.destination_marker)).position(latLng).title(maping_status));

   //Zoom in the Google Map
  mMap.animateCamera(CameraUpdateFactory.zoomTo(20));
}
3
qo'shib qo'ydi
qo'shib qo'ydi muallif Moeez, manba
"GoogleMap.OnMyLocationChangeListener" hisobidan eskirgan. Bundan tashqari, hech qanday marker yoki matn ko'rsatilmaydi
qo'shib qo'ydi muallif Moeez, manba
Siz nima dedingiz, nimani o'zgartirdingiz? Men butun kodni iltifot bilan ko'rib chiqdim
qo'shib qo'ydi muallif Moeez, manba
Tajribali, marker harakat qiladi va oldingi har bir harakati hali ham ko'rsatilsa, bundan tashqari, hozirgi latitude va uzunlik ni ko'rsatadigan matn ko'rinishini ishlataman. Shunday qilib, matn ko'rinishida avvalgi holat hali ham mavjud bo'lsa, bir-birini takrorlaydi.
qo'shib qo'ydi muallif Moeez, manba
mMap.clear() kabi markerni tozalash parametrini ishlatasiz. joydan uzoqroq oldin, yuqoridagi kodni qo'shing.
qo'shib qo'ydi muallif Akash pasupathi, manba
Umid qilamanki, bu sizga yordam beradi @ faisal1208
qo'shib qo'ydi muallif Akash pasupathi, manba
va yuqoridagi usulda your_text_view.settext (latitude + "," + longtitudde) joriy manzildan uzoqroq bo'lgandan keyin qo'shing »kabi ichki usulni qo'shing
qo'shib qo'ydi muallif Akash pasupathi, manba
siz istagan narsam uchun mening xabarimni tahrir qilmoqdaman stackoverflow.com/a/42778943/7399521 o'chirib tashlangan buyruqni Umid qilamanki siz @ faisal1208 ni tushunasiz
qo'shib qo'ydi muallif Akash pasupathi, manba
onLocationchanged-ni olib tashlash o'rniga, bro @ faisal1208 kodimni ishlatish
qo'shib qo'ydi muallif Akash pasupathi, manba

Animatsiya uchun oldingi joylashuvi va Marker obyekti bilan birga yangi joylashuv bilan ushbu usulni ( animateMarker ) chaqiring

private Marker mCurrentMarker;
private float ZOOMLEVEL=18.0f;
private LatLng previousLatLon;
private Handler mLocalHandler;
private GoogleMap mGoogleMap;

public void animateMarker(final Marker marker, final LatLng toPosition,final LatLng fromPosition) {


        final long duration = 500;
        final Interpolator interpolator = new LinearInterpolator();

        mLocalHandler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - mStartTime;
                float t = interpolator.getInterpolation((float) elapsed
                       /duration);
                marker.setPosition(toPosition);
                marker.setAnchor(Constants.MAPANCHOR, Constants.MAPANCHOR);
                mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(toPosition, ZOOMLEVEL));
                if (t < 1.0) {
                   //Post again 16ms later.
                    mLocalHandler.postDelayed(this, 16);
                } else {
                    marker.setVisible(true);
                }
                }
            }
        });
        previousLatLon=toPosition;// reassign the previous location to current location
    }
2
qo'shib qo'ydi

Buni Lineer interpolator yordamida CameraPosition, googleMap.animateCamera va marker harakati animatsiyasi yordamida amalga oshirish mumkin.

Ushbu qo'llanmani bu yerda va sahifa .

Ushbu qo'llanmada Google maps v2 ishlatiladi. Umid qilamanki bu yordam.

2
qo'shib qo'ydi

Hope this Answer Will help you.instead of gps use Google Fused Api Read Documentation Here For Fused Api and Read this Answer how To Make Bus Marker Move

try this tutorial link for better understanding Fused Api Example

0
qo'shib qo'ydi

Agar siz hali ham echimni izlamoqchi bo'lsangiz, ushbu https://www.youtube.com/ v = WKfZsCKSXVQ sizga yordam beradi. Men buni ilovalarimdan birida ishlatganman va belgini bir joydan boshqa joyga animatsiyalashga yordam beradi. Manba kodini bu yerda olish mumkin https://gist.github.com/broady/6314689 .

Markerning aniq yo'nalishini ko'rsatish uchun markerga rotatsiyani kiritishingiz kerak bo'lishi mumkin. Quyida rulmanni topish uchun foydalanadigan kod bloklari keltirilgan.

    private float bearingBetweenLatLngs(LatLng begin, LatLng end) {
        Location beginL = convertLatLngToLocation(begin);
        Location endL = convertLatLngToLocation(end);

        return beginL.bearingTo(endL);
    }
0
qo'shib qo'ydi

Manifestda bu qatorlarni qo'shing

    
    

va keyin ushbu sinfdan foydalaning

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

GoogleMap mgoogleMap;
GoogleApiClient mgoogleApi;
Context context;
Marker marker;
LocationRequest locationrequest;
public static final int map=1111;
public static final int coarse=1112;

@Override
protected void onCreate(Bundle savedInstanceState) {
    if (googleServiceAvalable()) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = getApplicationContext();
        checkReadPermission();
        checkCoarsePermission();
        initMap();
    } else {

    }

}
public boolean googleServiceAvalable() {
    GoogleApiAvailability api = GoogleApiAvailability.getInstance();
    int isavailable = api.isGooglePlayServicesAvailable(this);
    if (isavailable == ConnectionResult.SUCCESS) {
        return true;
    } else if (api.isUserResolvableError(isavailable)) {
        Dialog dialog = api.getErrorDialog(this, isavailable, 0);
        dialog.show();
    } else {
        Toast.makeText(this, "cant connect to play services", Toast.LENGTH_LONG).show();
    }
    return false;
}

private void initMap() {
    MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.fragment);
    mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mgoogleMap = googleMap;
    if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
           //TODO: Consider calling
           //   ActivityCompat#requestPermissions
           //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 ActivityCompat#requestPermissions for more details.
            return;
        }
    }
    mgoogleMap.setMyLocationEnabled(true);

    if(checkCoarsePermission() && checkReadPermission()){
        mgoogleApi = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        mgoogleApi.connect();
    }else {
        checkReadPermission();
        checkCoarsePermission();
    }
}

private void goToLocation(double latitude, double longitude, int i) {
    LatLng ll = new LatLng(latitude, longitude);
    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, i);
    mgoogleMap.animateCamera(update);

    if(marker !=null){
        marker.remove();
    }

    MarkerOptions options =new MarkerOptions()
            .title("Test")
            .draggable(true)
            .position(new LatLng(latitude,longitude ));
    marker= mgoogleMap.addMarker(options);
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    locationrequest = new LocationRequest().create();
    locationrequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationrequest.setInterval(1000);

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
       //TODO: Consider calling
       //   ActivityCompat#requestPermissions
       //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 ActivityCompat#requestPermissions for more details.
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mgoogleApi, locationrequest, this);
    Toast.makeText(context,"Location Connected and ready to publish",Toast.LENGTH_SHORT).show();
}

@Override
public void onConnectionSuspended(int i) {
    Toast.makeText(context,"Location Connection Suspended",Toast.LENGTH_SHORT);
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Toast.makeText(context,"Location Connection Failed"+connectionResult.getErrorMessage(),Toast.LENGTH_SHORT);
}

@Override
public void onLocationChanged(Location location) {
    if(location==null){
        Toast.makeText(context,"Cant Find User Location",Toast.LENGTH_SHORT);
    }else {
        LatLng ll=new LatLng(location.getLatitude(),location.getLongitude());
        goToLocation(ll.latitude,ll.longitude,18);
    }
}

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public boolean checkReadPermission() {
    int currentAPIVersion = Build.VERSION.SDK_INT;
    if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MainActivity.this);
                alertBuilder.setCancelable(true);
                alertBuilder.setTitle("Permission necessary");
                alertBuilder.setMessage("Read Internal Storage permission required to display images!!!");
                alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions((Activity) MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, map);
                    }
                });
                AlertDialog alert = alertBuilder.create();
                alert.show();
            } else {
                ActivityCompat.requestPermissions((Activity) MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, map);
            }
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }
}

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public boolean checkCoarsePermission() {
    int currentAPIVersion = Build.VERSION.SDK_INT;
    if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)) {
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MainActivity.this);
                alertBuilder.setCancelable(true);
                alertBuilder.setTitle("Permission necessary");
                alertBuilder.setMessage("Read Internal Storage permission required to display images!!!");
                alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions((Activity) MainActivity.this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, coarse);
                    }
                });
                AlertDialog alert = alertBuilder.create();
                alert.show();
            } else {
                ActivityCompat.requestPermissions((Activity) MainActivity.this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, coarse);
            }
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                       int[] grantResults) {
    switch (requestCode) {
        case map:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            } else {
                Toast.makeText(context,"You have to give permission",Toast.LENGTH_SHORT).show();
            }
            break;

        case coarse:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            } else {
                Toast.makeText(context,"You have to give permission",Toast.LENGTH_SHORT).show();
            }
            break;


    }
}}
0
qo'shib qo'ydi