在谷歌地图android中使用gps移动标记 [英] Move marker with gps in google map android

查看:151
本文介绍了在谷歌地图android中使用gps移动标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 GOOGLE MAP 中移动标记,而 gps 位置更改就像 UBER 应用程序。我找到了一些解决方案,但无法解决我的问题。解决方案是 1 2

I want to make move of the marker in GOOGLE MAP while gps location changes just like in UBER app. I have found some solutions but unable to solve my issue. The solutions are 1 and 2

以下是我的 onLocationChange()方法

Below is my onLocationChange() method

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(Re - 编辑)

为了更多了解,我添加了更多的代码,但首先我想告诉我,我在我的应用程序中使用选项卡。第一个标签是我的地图。所以我正在使用它的片段。

For more understanding i am adding some more code, but first i want to tell that i am using tabs in my app. The very first tab is of my map. So i am using fragments for it.

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) {

}}

任何帮助将不胜感激

Any help would be highly appreciated

推荐答案

您可以使用下面的代码更新标记的位置

You can use below code to update position of the Marker

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);
    }

}

您无需清除每次都可以映射,你可以通过标记对象来实现,这是在将标记添加到地图时返回的。
希望它能帮助你。

You don't need to clear map every time. You can do it by Marker object that is returned when adding Marker to Map. Hope it will help you.

这篇关于在谷歌地图android中使用gps移动标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆