Android “地图”API仅使用位置设置GPS加载

Android “地图”API仅使用位置设置GPS加载,android,google-maps,gps,Android,Google Maps,Gps,我在Android应用程序中使用谷歌地图API,并使用 LocationManager和getLatitude(),getLatitude()。 但是现在手机上必须有奇怪的设置才能得到地图。位置设置必须更改为仅使用GPS,即使这样,它也不能一直工作,有时地图没有加载。如果未加载,由于NullPointerException,应用程序将在设置第一个标记时关闭 这是为什么?我如何预防? 我已经尝试了getmapsync,但没有任何帮助 GoogleMap googleMap; LocationMan

我在Android应用程序中使用谷歌地图API,并使用
LocationManager
getLatitude()
getLatitude()
。 但是现在手机上必须有奇怪的设置才能得到地图。位置设置必须更改为仅使用GPS,即使这样,它也不能一直工作,有时地图没有加载。如果未加载,由于
NullPointerException
,应用程序将在设置第一个标记时关闭

这是为什么?我如何预防? 我已经尝试了
getmapsync
,但没有任何帮助

GoogleMap googleMap;
LocationManager locationManager;
String provider;
Criteria criteria;
Location myLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);

   try {
        if(googleMap == null) {
            googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
        }
        googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        googleMap.setMyLocationEnabled(true);
        googleMap.setTrafficEnabled(true);
        googleMap.setIndoorEnabled(true);
        googleMap.setBuildingsEnabled(true);
        googleMap.getUiSettings().setZoomControlsEnabled(true);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, true);
        myLocation = locationManager.getLastKnownLocation(provider);
        double latitude = myLocation.getLatitude();
        double longitude = myLocation.getLongitude();
        LatLng latLng = new LatLng(latitude, longitude);
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(14));
        iconDone = R.drawable.markerdone;
        icon = R.drawable.marker;
    }
    catch(Exception e) {
        e.printStackTrace();
    }

    Marker marker1 = googleMap.addMarker(new MarkerOptions()
            .position(new LatLng(49.793012, 9.926201))
            .title(getString(R.string.Title1))
            .snippet("")
            .icon(BitmapDescriptorFactory.fromResource(icon)));

问题是您正在调用
getLastKnownLocation()
,这将经常返回空位置,因为它不会显式请求新的位置锁

因此,当您的应用程序崩溃时,这是由于尝试取消引用Location对象时出现NullPointerException

最好请求位置更新,如果您只需要一个,只要在第一个
onLocationChanged()
回调到来时取消注册位置更新即可

下面是一个使用FusedLocationProvider API的示例,该API会在需要时自动使用网络位置和GPS位置:

活动的相关进口:

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
活动:

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends AppCompatActivity 
        implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks, 
        GoogleApiClient.OnConnectionFailedListener, LocationListener {


    GoogleMap googleMap;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Marker marker;

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buildGoogleApiClient();
        mGoogleApiClient.connect();
    }

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

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);

        mapFragment.getMapAsync(this);
    }

    protected synchronized void buildGoogleApiClient() {
        Toast.makeText(this,"buildGoogleApiClient", Toast.LENGTH_SHORT).show();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    @Override
    public void onMapReady(GoogleMap map) {

        googleMap = map;

        setUpMap();

    }

    public void setUpMap() {

        googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        googleMap.setMyLocationEnabled(true);
        googleMap.getUiSettings().setZoomControlsEnabled(true);

    }

    @Override
    public void onConnected(Bundle bundle) {

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(10);
        mLocationRequest.setFastestInterval(10);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        //mLocationRequest.setSmallestDisplacement(0.1F);

        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onLocationChanged(Location location) {

        //unregister location updates
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

        //remove previously placed Marker
        if (marker != null) {
            marker.remove();
        }

        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        //place marker where user just clicked
        marker = googleMap.addMarker(new MarkerOptions()
                .position(latLng)
                .title("Current Location")
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));

        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(latLng).zoom(5).build();

        googleMap.animateCamera(CameraUpdateFactory
                .newCameraPosition(cameraPosition));


    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

}
build.gradle(更改为您当前使用的Google Play服务的任何版本):

布局xml中的SupportMapFragment(也可以使用MapFragment):


仅使用网络位置:

地图在启动后几秒钟移动到当前位置:


显示您的代码,以便更好地了解问题发生的原因。您正在使用FusedLocationProvider吗?第一次打开应用程序时它不会加载?还是在转到另一个活动/片段之后?而且它不会加载和崩溃(如果是这样,请发布日志)!或者它加载时没有任何内容?请澄清你的问题。帮助我们帮助您我做的一切都像您一样,但在onLocationChanged方法上,它给我一个错误,说“方法不重写其超类中的方法”如果我使用其中的当前位置来知道用户在标记附近,您将在哪里设置
setOnInfo ClickListener
。@maidi我刚刚更新了格式,这样您就可以在不滚动的情况下看到活动实现的所有界面,请看一看!还要确保导入正确的LocationListener:
import com.google.android.gms.location.LocationListener
@maidi for
setOnInfoWindowClickListener
查看此答案,在
setUpMap()
中设置它:我像您一样在
onLocationChanged()
中设置当前位置,并将其命名为
myposition
。现在我想在WindowClickListener的
中使用它,并用
设置纬度(myposition.latitude)
和经度设置一个位置变量。对于这个
位置
变量,我使用
距离到
。(这是我添加您的解决方案之前的做法)。这样做是错误的吗?
    <fragment
    android:id="@+id/map"
    class="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>