简体   繁体   English

Google映射Android API和当前位置

[英]Google maps Android API and current location

I am trying to implement the google maps API. 我正在尝试实现Google Maps API。 I want to see my own position on the map and I want that it changes when I move significantly. 我想在地图上看到自己的位置,并且希望它在我大幅移动时发生变化。 The problem is that there are no errors but it does not display a marker of my position on the map. 问题是没有错误,但是没有在地图上显示我的位置标记。 This is my onCreate() methode in the .java file 这是我的.java文件中的onCreate()方法

private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
public static final String TAG = MapPane.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map_pane);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 1000)        // 10 seconds, in milliseconds
            .setFastestInterval(1 * 1000); // 1 second, in milliseconds

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

And this is the method I think I am missing here something 这就是我认为我在这里缺少的方法

 public void onConnected(@Nullable Bundle bundle) {
    Log.i(TAG, "Location services connected.");

    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (location == null) {
        Log.i(TAG, "loc exists");
        if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }//if
    }//if
    else {
        handleNewLocation(location);
    }//else
}//onConnected

because I never get into the second if statement. 因为我从不进入第二个if语句。 I guess I need the permission of the user first? 我想我首先需要用户的许可吗? Turning the gps on manually on my device does not work either. 在我的设备上手动打开GPS也不起作用。 And the method below I used for displaying the marker on the map 我在地图上显示标记的以下方法

private void handleNewLocation(Location location) {
    Log.d(TAG, location.toString());
    double currentLatitude = location.getLatitude();
    double currentLongitude = location.getLongitude();
    LatLng latLng = new LatLng(currentLatitude, currentLongitude);

    MarkerOptions options = new MarkerOptions()
            .position(latLng)
            .title("I am here!");
    mMap.addMarker(options);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

}//handleNewLocation

I used more methods but I think there is no flaw in there. 我使用了更多的方法,但我认为其中没有缺陷。 In the AndroidManifest.xml I included 在AndroidManifest.xml中,我包含了

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

You can use LocationManager instead of google api client 您可以使用LocationManager代替Google API客户端

             LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
    final Geocoder gc = new Geocoder(this, Locale.getDefault());

    LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            //here you can get current position location.getLatitude(),location.getLongitude();

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

It seems your code is not providing any location to the handlelocation() method. 看来您的代码没有为handlelocation()方法提供任何位置。

private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
public static final String TAG = MapPane.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
LocationListener li;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map_pane);
    // Obtain the SupportMapFragment and get notified when the map is reato be used.
    SupportMapFragment mapFragment = (SupportMapFragment)         getSupportFragmentManager()
        .findFragmentById(R.id.map);
mapFragment.getMapAsync(this);

 li=new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            handleNewLocation(location);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };


  getHandledCurrentLocation();
}//onCr

private void getHandledCurrentLocation() {
    String locationProvider = LocationManager.NETWORK_PROVIDER;

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
    }
    Log.e("LOCATION_DEBUG","LOCATION REQUESTED--- ");
    LCM.requestLocationUpdates(locationProvider, 10 * 1000, 0,li);

}
private void handleNewLocation(Location location) {
 Log.d(TAG, location.toString());
 double currentLatitude = location.getLatitude();
 double currentLongitude = location.getLongitude();
 LatLng latLng = new LatLng(currentLatitude, currentLongitude);

 MarkerOptions options = new MarkerOptions()
        .position(latLng)
        .title("I am here!");
 mMap.addMarker(options);
 mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

}//handleNewLocation

this code should work. 此代码应该工作。

I can see few issues with your code. 我看不到您的代码有什么问题。 I don't think you are handling the location updates provided by FusedLocationApi. 我认为您没有处理FusedLocationApi提供的位置更新。 I believe you are implementing LocationListener even though that part of the code is not provided in your question. 我相信您正在实现LocationListener即使您的问题中未提供该部分代码。 In that case you are implementing a method ' onLocationChanged(Location location) ' in your activity. 在这种情况下,您将在活动中实现方法“ onLocationChanged(Location location) ”。 This is the method in which you should try to set the new location on the map. 这是您应尝试在地图上设置新位置的方法。 Your handleNewLocation method will not be called by FusedLocationApi automatically handleNewLocation不会自动调用您的handleNewLocation方法

You may want to provide the complete code for your activity , then we can help you better. 您可能需要为您的活动提供完整的代码,然后我们可以为您提供更好的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM