发布
社区首页 >问答首页 >Android:为什么de方法getLatitude()和getLongtitude()返回null?

Android:为什么de方法getLatitude()和getLongtitude()返回null?
EN

Stack Overflow用户
提问于 2016-07-11 03:48:04
回答 0查看 371关注 0票数 0

我试图为一个位置获取2个变量,但它返回null。我不知道我做错了什么。如果我想启动活动,它会自动停止。下面是我的代码:

代码语言:javascript
代码运行次数:0
复制
 private GoogleMap mMap;
LocationManager myLocationManager;
Location myLocation;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pechhulp);
    // 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);

    myLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    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) {
        return;
    }
    myLocation = myLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

}


@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Pak de Latitude en Longtitude van de aangemaakte locatie.
    // These variables are returning null 
    double latitude = myLocation.getLatitude();
    double longtitude = myLocation.getLongitude();

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-34, 151);
    LatLng myPosition = new LatLng(latitude, longtitude);

    mMap.addMarker(new MarkerOptions().position(sydney).title("Dit is uw plaats"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(myPosition));
}

下面是错误:

代码语言:javascript
代码运行次数:0
复制
                                                                                  java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38295875

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档