android - 在谷歌地图android中使用gps移动标记

标签 android google-maps google-maps-api-3 gps

我想移动 GOOGLE MAP 中的标记,同时 gps 位置发生变化,就像在 UBER 应用中一样。我找到了一些解决方案,但无法解决我的问题。解决方案是12

下面是我的onLocationChange()方法

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

为了更好地理解,我添加了更多代码,但首先我想告诉我我在我的应用程序中使用标签。第一个 tab 是我的 map 。所以我正在使用 fragment 。

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

}}

任何帮助将不胜感激

最佳答案

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

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

}

您不需要每次都清除 map 。您可以通过将 Marker 添加到 Map 时返回的 Marker 对象来完成。 希望对你有帮助。

关于android - 在谷歌地图android中使用gps移动标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42576534/

相关文章:

java - 获取特定位置的 map View 我选择纬度和经度

javascript - Google js api动态为每个标记提供不同的标记图像

java - 20 秒后音乐停止(安卓音板)

android - 在 ListView 适配器中从我的应用程序打开电子邮件应用程序

java - 是否有用于 java 的 Backgroundworker(例如在 .Net 中)

javascript - Google map 监听器在 Firefox 中加载正常,但在其他浏览器中加载不正常

java - Android:使叠加图像可点击

javascript - 标记在 Google map API 中不起作用

google-maps-api-3 - 过滤来自 Google 自动完成的结果

android - 为什么 AIDL 被设计成不能将异常发送回调用者