Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在谷歌地图中显示我的当前位置_Java_Android_Google Maps_Android Studio_Gps - Fatal编程技术网

Java 在谷歌地图中显示我的当前位置

Java 在谷歌地图中显示我的当前位置,java,android,google-maps,android-studio,gps,Java,Android,Google Maps,Android Studio,Gps,最后,我成功地显示了地图,现在,我想显示我的当前位置,我尝试使用这些代码,但当我单击右上角的“我的位置”按钮时,它不起作用 AndroidManifest.xml <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission

最后,我成功地显示了地图,现在,我想显示我的当前位置,我尝试使用这些代码,但当我单击右上角的“我的位置”按钮时,它不起作用

AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="com.example.hp.testmap.MAPS_RECEIVE"></uses-permission>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

<permission
    android:name="com.example.hp.testmap.permission.MAPS_RECEIVE"
    android:protectionLevel="signature"/>

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

阅读以下文件-


可能的副本-

请阅读以下文档-


可能重复的-

将此代码用于当前位置:

googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
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;
}
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(false);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
googleMap.getUiSettings().setZoomGesturesEnabled(true);

if (locationManager == null) {
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
if (locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER)) {
    isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    isNetworkProviderEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    if (isGPSEnabled) {
        location = getLastLocationByProvider(locationManager, LocationManager.GPS_PROVIDER, getApplicationContext());
    } else if (isNetworkProviderEnabled) {
        location = getLastLocationByProvider(locationManager, LocationManager.NETWORK_PROVIDER, getApplicationContext());
    }
    if (location != null) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
    } else {
        if (isNetworkProviderEnabled) {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100000, 1, this);
            provider_info = LocationManager.NETWORK_PROVIDER;
        } else if (isGPSEnabled) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100000, 1, this);
            provider_info = LocationManager.GPS_PROVIDER;
        } else {

            alertDialog = Util.showOkDialog(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (Env.currentActivity != null) {
                        if (Env.currentActivity instanceof LocationActivity) {
                            try {
                                gotoSettings();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                    }
                    if (alertDialog != null) {
                        alertDialog.dismiss();
                        alertDialog = null;
                    }

                }
            }, this.getResources().getString(R.string.location_service_validation));

        }

        location = locationManager.getLastKnownLocation(provider_info);
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }
    }

    MarkerOptions marker = new MarkerOptions().position(
            new LatLng(latitude, longitude))
            .title(getFullAddressLine(this));
    marker.icon(BitmapDescriptorFactory
            .defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

    googleMap.addMarker(marker);
    CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(new LatLng(latitude,
                    longitude)).zoom(15).build();
    googleMap.animateCamera(CameraUpdateFactory
            .newCameraPosition(cameraPosition));
}

将此代码用于当前位置:

googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
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;
}
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(false);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
googleMap.getUiSettings().setZoomGesturesEnabled(true);

if (locationManager == null) {
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
if (locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER)) {
    isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    isNetworkProviderEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    if (isGPSEnabled) {
        location = getLastLocationByProvider(locationManager, LocationManager.GPS_PROVIDER, getApplicationContext());
    } else if (isNetworkProviderEnabled) {
        location = getLastLocationByProvider(locationManager, LocationManager.NETWORK_PROVIDER, getApplicationContext());
    }
    if (location != null) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
    } else {
        if (isNetworkProviderEnabled) {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100000, 1, this);
            provider_info = LocationManager.NETWORK_PROVIDER;
        } else if (isGPSEnabled) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100000, 1, this);
            provider_info = LocationManager.GPS_PROVIDER;
        } else {

            alertDialog = Util.showOkDialog(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (Env.currentActivity != null) {
                        if (Env.currentActivity instanceof LocationActivity) {
                            try {
                                gotoSettings();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                    }
                    if (alertDialog != null) {
                        alertDialog.dismiss();
                        alertDialog = null;
                    }

                }
            }, this.getResources().getString(R.string.location_service_validation));

        }

        location = locationManager.getLastKnownLocation(provider_info);
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }
    }

    MarkerOptions marker = new MarkerOptions().position(
            new LatLng(latitude, longitude))
            .title(getFullAddressLine(this));
    marker.icon(BitmapDescriptorFactory
            .defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

    googleMap.addMarker(marker);
    CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(new LatLng(latitude,
                    longitude)).zoom(15).build();
    googleMap.animateCamera(CameraUpdateFactory
            .newCameraPosition(cameraPosition));
}
实现此侦听器

LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener 
if (mGoogleApiClient == null) {
    mGoogleApiClient = new GoogleApiClient.Builder(mActivity)
        .addApi(LocationServices.API).addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this).build();
    mGoogleApiClient.connect();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
    if (ContextCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null)
            onLocationChanged(mLastLocation);
        return;
    }
}

@Override
public void onLocationChanged(Location location) {
    if (location != null) {
        mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(),location.getLongitude())));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(6), 5000, null);
    }
}
onCreate视图或onCreate方法

LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener 
if (mGoogleApiClient == null) {
    mGoogleApiClient = new GoogleApiClient.Builder(mActivity)
        .addApi(LocationServices.API).addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this).build();
    mGoogleApiClient.connect();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
    if (ContextCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null)
            onLocationChanged(mLastLocation);
        return;
    }
}

@Override
public void onLocationChanged(Location location) {
    if (location != null) {
        mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(),location.getLongitude())));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(6), 5000, null);
    }
}
@覆盖方法

LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener 
if (mGoogleApiClient == null) {
    mGoogleApiClient = new GoogleApiClient.Builder(mActivity)
        .addApi(LocationServices.API).addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this).build();
    mGoogleApiClient.connect();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
    if (ContextCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null)
            onLocationChanged(mLastLocation);
        return;
    }
}

@Override
public void onLocationChanged(Location location) {
    if (location != null) {
        mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(),location.getLongitude())));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(6), 5000, null);
    }
}
希望你的任务完成

public void showMap() {

    mapFragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
    if (map == null) {
        map = mapFragment.getMap();
    }


    // Enable Zoom
    map.getUiSettings().setZoomGesturesEnabled(true);

    //set Map TYPE
    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    //enable Current location Button
    map.setMyLocationEnabled(true);

    LocationManager locationManager = (LocationManager)getActivity().getSystemService(getActivity().LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, true);
    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), 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;
    }
    Location location = locationManager.getLastKnownLocation(bestProvider);
    if (location != null) {
        onLocationChanged(location);
    }
    locationManager.requestLocationUpdates(bestProvider, 2000, 0, this);
}

@Override
public void onLocationChanged(Location location) {

    latitude= location.getLatitude();
    longitude=location.getLongitude();

    LatLng loc = new LatLng(latitude, longitude);

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

    marker=  map.addMarker(new MarkerOptions().position(loc).title("Sparx IT Solutions"));
    map.moveCamera(CameraUpdateFactory.newLatLng(loc));
    map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));

}

@Override
public void onProviderDisabled(String provider) {

    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    startActivity(intent);
    Toast.makeText(getActivity().getBaseContext(), "Gps is turned off!!",
            Toast.LENGTH_SHORT).show();
}

@Override
public void onProviderEnabled(String provider) {

    Toast.makeText(getActivity().getBaseContext(), "Gps is turned on!! ",
            Toast.LENGTH_SHORT).show();
}
实现此侦听器

LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener 
if (mGoogleApiClient == null) {
    mGoogleApiClient = new GoogleApiClient.Builder(mActivity)
        .addApi(LocationServices.API).addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this).build();
    mGoogleApiClient.connect();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
    if (ContextCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null)
            onLocationChanged(mLastLocation);
        return;
    }
}

@Override
public void onLocationChanged(Location location) {
    if (location != null) {
        mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(),location.getLongitude())));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(6), 5000, null);
    }
}
onCreate视图或onCreate方法

LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener 
if (mGoogleApiClient == null) {
    mGoogleApiClient = new GoogleApiClient.Builder(mActivity)
        .addApi(LocationServices.API).addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this).build();
    mGoogleApiClient.connect();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
    if (ContextCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null)
            onLocationChanged(mLastLocation);
        return;
    }
}

@Override
public void onLocationChanged(Location location) {
    if (location != null) {
        mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(),location.getLongitude())));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(6), 5000, null);
    }
}
@覆盖方法

LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener 
if (mGoogleApiClient == null) {
    mGoogleApiClient = new GoogleApiClient.Builder(mActivity)
        .addApi(LocationServices.API).addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this).build();
    mGoogleApiClient.connect();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
    if (ContextCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null)
            onLocationChanged(mLastLocation);
        return;
    }
}

@Override
public void onLocationChanged(Location location) {
    if (location != null) {
        mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(),location.getLongitude())));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(6), 5000, null);
    }
}
希望您的任务完成。

使用以下代码:

public void showMap() {

    mapFragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
    if (map == null) {
        map = mapFragment.getMap();
    }


    // Enable Zoom
    map.getUiSettings().setZoomGesturesEnabled(true);

    //set Map TYPE
    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    //enable Current location Button
    map.setMyLocationEnabled(true);

    LocationManager locationManager = (LocationManager)getActivity().getSystemService(getActivity().LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, true);
    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), 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;
    }
    Location location = locationManager.getLastKnownLocation(bestProvider);
    if (location != null) {
        onLocationChanged(location);
    }
    locationManager.requestLocationUpdates(bestProvider, 2000, 0, this);
}

@Override
public void onLocationChanged(Location location) {

    latitude= location.getLatitude();
    longitude=location.getLongitude();

    LatLng loc = new LatLng(latitude, longitude);

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

    marker=  map.addMarker(new MarkerOptions().position(loc).title("Sparx IT Solutions"));
    map.moveCamera(CameraUpdateFactory.newLatLng(loc));
    map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));

}

@Override
public void onProviderDisabled(String provider) {

    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    startActivity(intent);
    Toast.makeText(getActivity().getBaseContext(), "Gps is turned off!!",
            Toast.LENGTH_SHORT).show();
}

@Override
public void onProviderEnabled(String provider) {

    Toast.makeText(getActivity().getBaseContext(), "Gps is turned on!! ",
            Toast.LENGTH_SHORT).show();
}
//Zoom to the current location
public Location getMyLocation() {
    LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();

    Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
    if (location != null) {
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                new LatLng(location.getLatitude(), location.getLongitude()), 13));

        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
                .zoom(17)                   // Sets the zoom
                .bearing(90)                // Sets the orientation of the camera to east
                .tilt(40)                   // Sets the tilt of the camera to 30 degrees
                .build();                   // Creates a CameraPosition from the builder
        map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    }

    return location;
}
然后在onCreate中调用此方法

希望这有帮助:)

使用以下代码:

//Zoom to the current location
public Location getMyLocation() {
    LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();

    Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
    if (location != null) {
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                new LatLng(location.getLatitude(), location.getLongitude()), 13));

        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
                .zoom(17)                   // Sets the zoom
                .bearing(90)                // Sets the orientation of the camera to east
                .tilt(40)                   // Sets the tilt of the camera to 30 degrees
                .build();                   // Creates a CameraPosition from the builder
        map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    }

    return location;
}
然后在onCreate中调用此方法


希望这有帮助:)

导入最新的谷歌播放服务-->编译'com.google.android.gms:play services:8.4.0'导入最新的谷歌播放服务-->编译'com.google.android.gms:play services:8.4.0'