Java 在MapFragment中显示当前位置

Java 在MapFragment中显示当前位置,java,android,Java,Android,我有一个location类,它在MapFragment上创建一个实例,根据创建地图的活动,它将删除一个不同的标记。我还想在地图上显示手机当前位置的标记 我假设我可以做这样的事情,但我无法确定如何获取和更新手机的当前坐标并将其分配给我的位置 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_

我有一个location类,它在MapFragment上创建一个实例,根据创建地图的活动,它将删除一个不同的标记。我还想在地图上显示手机当前位置的标记

我假设我可以做这样的事情,但我无法确定如何获取和更新手机的当前坐标并将其分配给我的位置

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_location);

MapFragment googleMap = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
    googleMap.getMapAsync(this);

    }

    @Override
            public void onMapReady(GoogleMap nMap){

        if(MainMenu.bkSource == true) {
            LatLng bkLatLng = new LatLng(54.5816008, -5.9651271);
            LatLng myLocation = new LatLng(???);
            nMap.addMarker(new MarkerOptions().position(bkLatLng).title("Burger King, Boucher Road"));
            nMap.addMarker(new MarkerOptions().position(myLocation).title("You Are Here");
            nMap.moveCamera(CameraUpdateFactory.newLatLngZoom(bkLatLng, 15));
            nMap.animateCamera(CameraUpdateFactory.zoomTo(18.0f));
        }
        if(MainMenu.kfcSource == true){
            LatLng bkLatLng = new LatLng(54.5771914, -5.9620562);
            nMap.addMarker(new MarkerOptions().position(bkLatLng).title("KFC, Boucher Road"));
            nMap.moveCamera(CameraUpdateFactory.newLatLngZoom(bkLatLng, 15));
            nMap.animateCamera(CameraUpdateFactory.zoomTo(18.0f));
        }
        if(MainMenu.mcdSource == true){
            LatLng bkLatLng = new LatLng(54.5879486, -5.9580009);
            nMap.addMarker(new MarkerOptions().position(bkLatLng).title("McDonald's, Boucher Road"));
            nMap.moveCamera(CameraUpdateFactory.newLatLngZoom(bkLatLng, 15));
            nMap.animateCamera(CameraUpdateFactory.zoomTo(18.0f));
        }

    }

在你的片段中实现了这一点

implements GoogleMap.InfoWindowAdapter, OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
然后创建一个全局变量

 private GoogleMap mMap;
 private GoogleApiClient mGoogleApiClient;
 double curt_lat = 0;
 double curt_log = 0;
 int Locationtry = 0;

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        if (gps == null)
            gps = new GPSTracker(getActivity());

        checkPermision();
    }



@Override
    public void onConnected(@Nullable Bundle bundle) {

        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //    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;
        }
        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            Log.e(TAG, "onConnected: " + String.valueOf(mLastLocation.getLatitude()) + ":" + String.valueOf(mLastLocation.getLongitude()));
            try {

                curt_lat = mLastLocation.getLatitude();
                curt_log = mLastLocation.getLongitude();
                Log.d(TAG, "OnConnected-" + "" + mLastLocation.getLatitude() + "" + mLastLocation.getLongitude());
                selectMapFragment();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            getLocationFormGoogleApi();   // OnConnected
            ((Handler) new Handler()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (Locationtry < 2) {
                        Locationtry++;
                        if (mGoogleApiClient != null) {
                            mGoogleApiClient.disconnect();
                        }
                        mGoogleApiClient = null;
                        getLocationFormGoogleApi();
                        // OnConnected
//                        Consts.displayDialog(MapsActivity.this);
                    } else {
                        Locationtry = 0;
//                        Consts.stopDialog();
//                        Consts.animationDialog(false, AllRestaurntMapActivity.this, R.layout.activity_all_restaurnt_map);
//                        isAnimation = false;

                    }
                }
            }, 10000);
        }

    }



 @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            Log.i(TAG, "resultCode: " + resultCode);

            if (requestCode == 1) {
                if (isGPSEnable()) {

                    Log.d(TAG, "get GPS Enable");

                    checkPermision();
                    getLocationFormGoogleApi();


                } else {
                    isGpsDialogOpen = false;
                    Log.d(TAG, "GPS NOT Enable");
                }
            }
            super.onActivityResult(requestCode, resultCode, data);
        }

        public boolean isGPSEnable() {
            LocationManager locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
            return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        }

        public void getLocationFormGoogleApi() {
            Log.d(TAG, "getLocationFormGoogleApi");
    //        Consts.animationDialog(true, AllRestaurntMapActivity.this, R.layout.activity_all_restaurnt_map);
    //        new Handler().postDelayed(animation, 0);
            // Create an instance of GoogleAPIClient.
            if (mGoogleApiClient == null) {
                Log.d(TAG, "get the LagLog... ");
                mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                        .addConnectionCallbacks(this)
                        .addOnConnectionFailedListener(this)
                        .addApi(LocationServices.API)
                        .build();

            } else {
                Log.d(TAG, "all ready have LagLog... ");
    //            makeReq(String.valueOf(UserInfo.getLatitude()), String.valueOf(UserInfo.getLongitude()));

                Log.d(TAG, "get the LagLog... from permission request accept.. ");
                mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                        .addConnectionCallbacks(this)
                        .addOnConnectionFailedListener(this)
                        .addApi(LocationServices.API)
                        .build();

                mGoogleApiClient.connect();
            }
        }

@Override
    public void onMapReady(GoogleMap googleMap) {
        Log.d(TAG, "onMapReady");
        if (mMap != null) {
            mMap.clear();
        }


        String url = "";

        mMap = googleMap;
        mMap.getUiSettings().setMapToolbarEnabled(false);

        final LatLngBounds.Builder mapboundbuilder = new LatLngBounds.Builder();

        // lat log driver....
        Log.d(TAG, "LatLog driver :" + curt_lat + "," + curt_log);
        LatLng latLng = new LatLng(curt_lat, curt_log);
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_map_one));
        markerOptions.position(latLng);
        markerOptions.title("You are Here!");
//        markerOptions.snippet("");
        mMap.addMarker(markerOptions);
        mapboundbuilder.include(latLng);
        LatLngBounds tmpbnd = mapboundbuilder.build();


        Log.v("connectionurl", url);


        LatLng center = tmpbnd.getCenter();
        LatLng northEast = Consts.mappointmove(center, 209, 209);
        LatLng southWest = Consts.mappointmove(center, 209, 209);
        mapboundbuilder.include(southWest);
        mapboundbuilder.include(northEast);

        LatLngBounds bounds = mapboundbuilder.build();

        try {
            int width, height;
            Display display = getActivity().getWindowManager().getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            width = size.x;
            height = size.y - 250;
            CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, 100);
            googleMap.animateCamera(cu);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    @Override
    public void onStop() {
        if (mGoogleApiClient != null) {
            mGoogleApiClient.disconnect();
        }

        super.onStop();
    }

    @Override
    public void onStart() {
        if (mGoogleApiClient != null) {
            Log.d(TAG, "Location not Null");
            mGoogleApiClient.connect();
        }

        super.onStart();
    }

下面是一个扩展SupportMapFragment的示例片段,在启动时,它将获取用户的当前位置,放置一个标记,并放大:

public class MapFragment extends SupportMapFragment
    implements OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener {

GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;

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

    setUpMapIfNeeded();
}

private void setUpMapIfNeeded() {

    if (mGoogleMap == null) {
        getMapAsync(this);
    }
}
@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_HYBRID);

    //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 onConnectionFailed(ConnectionResult connectionResult) {}

@Override
public void onLocationChanged(Location location)
{
    mLastLocation = location;
    if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
    }

    //Place current location marker
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Current Position");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
    mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

    //move map camera
    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));

}

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) {
    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.
                Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}
}

由于位置权限请求需要通过活动,因此需要将结果从活动路由到片段的onRequestPermissionsResult方法:

公共类MainActivity扩展了AppCompatActivity{

MapFragment mapFragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mapFragment = new MapFragment();

    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.add(R.id.mapframe, mapFragment);
    transaction.commit();
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    if (requestCode == MapFragment.MY_PERMISSIONS_REQUEST_LOCATION){
        mapFragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    else {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
}

该布局仅包含一个映射片段所在的FrameLayout


activity_main.xml:

使用以下代码获取当前位置:

 @Override
    public void onMapReady(GoogleMap googleMap) {


     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;
                }
                mMap.setMyLocationEnabled(true);
}
如果要在当前位置添加标记,请尝试以下操作:

1.在活动中实施LocationListener

2.更新位置请求:

LocationRequest  mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(5000); //5 seconds
        mLocationRequest.setFastestInterval(3000); //3 seconds
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
3.在onLocationChangedLocation上创建标记

我希望这会有帮助:我希望这会有帮助
LocationRequest  mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(5000); //5 seconds
        mLocationRequest.setFastestInterval(3000); //3 seconds
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        Geocoder geocoder;
        List<Address> addresses;
        geocoder = new Geocoder(this, Locale.getDefault());



        //place marker at current position
        //mGoogleMap.clear();

 Marker currLocationMarker;

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

        latLng = new LatLng(location.getLatitude(), location.getLongitude());

        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position.......");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
       currLocationMarker = mMap.addMarker(markerOptions);

}
}