【问题标题】:Move marker with gps in google map android在谷歌地图android中使用gps移动标记
【发布时间】:2017-07-23 10:12:11
【问题描述】:

我想移动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 是我的地图。所以我正在使用片段。

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

}}

任何帮助将不胜感激

【问题讨论】:

  • 试试mGoogleMap.clear()而不是mCurrLocationMarker.remove()
  • 试过了,没用
  • 快速提问,这个方法在哪里?在活动、服务、应用程序中?如果在一个活动中,它会在你回到活动之前工作,还是根本不工作?我们需要查看更多代码才能真正帮助您。主要是这个方法所在的地方。

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


【解决方案1】:

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

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

}

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

【讨论】:

  • 尝试了您的代码,但当蓝点移动时,标记仍然位于同一位置。销钉移动时应设置在蓝点上
  • 你能检查一下你的 onLocationChanged 事件被调用了吗?蓝色引脚也是默认地图,他们可能使用不同的逻辑来更改位置。您可以通过硬编码值来检查 setPostion 方法,并检查位置是否改变。我尝试了同样的方法,它正在改变。
  • stop location updates 这会停止更新位置,所以我认为这就是不移动标记的原因。我的想法可能是我错了
  • 而且每次都会调用onLocationChange方法。你也可以看到我的更新代码
  • 您能否尝试删除停止位置更新下的代码。然后。如果仍然没有,请尽可能上传您的整个活动代码。将清楚地知道为什么它没有被更新
【解决方案2】:

首先在你的Activity中实现LocationListener,然后

如果您只需要显示一个标记(更新标记的位置),请使用:

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

或者如果您想每次都添加一个新标记:

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

如果位置快速更改,您的应用需要几秒钟来更新其位置标记

【讨论】:

    【解决方案3】:

    这可以使用 CameraPosition、googleMap.animateCamera 和使用线性插值器的标记移动动画来完成。

    你可以看看这个教程here和各自的githubpage

    本教程使用谷歌地图 v2。希望这会有所帮助。

    【讨论】:

      【解决方案4】:

      使用这个:

      在您的地图活动中实现LocationListener ,GoogleMap.OnMyLocationChangeListener,然后使用位置更改监听器

             @Override
          public void onMyLocationChange(Location location) { 
              //mMap.clear //if you want refresh map remove comment
              // 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));
          }
      

      【讨论】:

      • 试过了,标记确实移动了,每次它移动前一个仍然显示,此外,我使用的文本视图显示当前latitudelongitude。所以文本视图会继续一个一个地重复,而前一个仍然存在。
      • 您使用像 mMap.clear() 这样的标记清除选项。在从我的位置获取 lat long 之前添加上面的代码。
      • 我希望这会帮助你@faisal1208
      • 并在上面的方法中添加像your_text_view.settext(latitude+","+longtitudde)这样的内部方法在从当前位置获取lat long后添加
      • 我根据你的喜好编辑我的帖子stackoverflow.com/a/42778943/7399521 删除我提到的命令 希望你能理解@faisal1208
      【解决方案5】:

      为了动画,只需调用此方法 (animateMarker) 与以前的位置和新的位置以及标记对象

      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
          }
      

      【讨论】:

        【解决方案6】:

        希望这个答案能帮助你。而不是 gps 使用 Google Fused Api Read Documentation Here For Fused Api 并阅读这个答案 how To Make Bus Marker Move

        试试这个教程链接以更好地理解Fused Api Example

        【讨论】:

          【解决方案7】:

          在清单中添加这些行

              <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
              <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
          

          然后使用这个类

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

          【讨论】:

            【解决方案8】:

            如果您仍在寻找解决方案,希望 https://www.youtube.com/watch?v=WKfZsCKSXVQ 对您有所帮助。我在我的一个应用程序中使用了它,它有助于将标记从一个位置动画化到另一个位置。 源码可以在这里https://gist.github.com/broady/6314689获取。

            您可能需要为标记添加旋转以显示标记的确切方向。以下是我用来查找方位的代码块。

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

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2017-09-21
              • 1970-01-01
              • 2019-12-18
              • 1970-01-01
              • 1970-01-01
              • 2014-08-28
              • 2013-09-13
              相关资源
              最近更新 更多