无法获取Google Map片段中的当前位置

时间:2015-04-06 22:27:28

标签: java android google-maps android-fragments location

我正在尝试获取地图片段中的当前位置,但是在googleMap.setMyLocationEnabled(true)行中出现错误的崩溃; 我使用Location和Latlang来检测当前位置。

mapFragment.java

public class mapFragment extends Fragment {

    MapView mMapView;
    private GoogleMap googleMap;
    Location location;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // inflat and return the layout
        View v = inflater.inflate(R.layout.fragment_map, container,
                false);
        mMapView = (MapView) v.findViewById(R.id.mapView);
        mMapView.onCreate(savedInstanceState);

        mMapView.onResume();// needed to get the map to display immediately

        try {
            MapsInitializer.initialize(getActivity().getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
        googleMap.setMyLocationEnabled(true);
        googleMap = mMapView.getMap();
        // latitude and longitude
        LatLng lat = new LatLng(location.getLatitude(), location.getLongitude());
        /*double latitude = 17.385044;
        double longitude = 78.486671;*/

        // create marker
        MarkerOptions marker = new MarkerOptions().position(
                lat).title("Hello Maps");

        // Changing marker icon
        marker.icon(BitmapDescriptorFactory
                .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

        // adding marker
        googleMap.addMarker(marker);
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(lat).zoom(12).build();
        googleMap.animateCamera(CameraUpdateFactory
                .newCameraPosition(cameraPosition));

        // Perform any camera updates here
        return v;
    }


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

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }
}

fragment_map.xml

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.maps.MapView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mapView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

2 个答案:

答案 0 :(得分:0)

看起来您遇到了一些问题,但发生了崩溃,因为您需要在致电getMap()之前致电setMyLocationEnabled()

改变这个:

googleMap.setMyLocationEnabled(true);
googleMap = mMapView.getMap();

......对此:

googleMap = mMapView.getMap();
googleMap.setMyLocationEnabled(true);

更新:我能够使这段代码正常工作。

获取当前位置应该使用Fused Location Provider API,但这超出了这个问题的范围。

此示例代码中的方法可能适用于较旧的设备,但在4.4.4中,由于getMyLocation()被删除,它会返回空位置。

但是,通过空检查,地图可以正确显示,您可以点击位置按钮,让地图移动到当前位置。

        MapView mMapView;
        private GoogleMap googleMap;
        Location location;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // inflat and return the layout
            View v = inflater.inflate(R.layout.fragment_main, container,
                    false);
            mMapView = (MapView) v.findViewById(R.id.mapView);
            mMapView.onCreate(savedInstanceState);

            mMapView.onResume();// needed to get the map to display immediately

            try {
                MapsInitializer.initialize(getActivity().getApplicationContext());
            } catch (Exception e) {
                e.printStackTrace();
            }
            googleMap = mMapView.getMap();
            googleMap.setMyLocationEnabled(true);

            location = googleMap.getMyLocation();

            if (location != null) {

                // latitude and longitude
                LatLng lat = new LatLng(location.getLatitude(), location.getLongitude());

                //double latitude = 17.385044;
                //double longitude = 78.486671;
                //LatLng lat = new LatLng(latitude,longitude);

                // create marker

                MarkerOptions marker = new MarkerOptions().position(
                        lat).title("Hello Maps");

                // Changing marker icon
                marker.icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

                // adding marker
                googleMap.addMarker(marker);

                CameraPosition cameraPosition = new CameraPosition.Builder()
                        .target(lat).zoom(12).build();


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

            }

            // Perform any camera updates here
            return v;
        }

答案 1 :(得分:0)

您可以使用setOnMyLocationChangeListener方法获取当前位置。在此处下载源代码(Show Google Map In Android

<强> MainActivity.Java

package deepshikha.googlemap;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends AppCompatActivity {
public GoogleMap googleMap;
private static final int REQUEST_PERMISSIONS = 100;
Button btn;

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


    fn_permission();
    fn_currentlocation ();
}

public void fn_currentlocation (){

    if (googleMap == null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

        try {

            googleMap.setMyLocationEnabled(true);
        } catch (Exception e) {

        }

        if (googleMap != null) {

            googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {

                @Override
                public void onMyLocationChange(Location arg0) {
                    // TODO Auto-generated method stub
                    double current_latitude = arg0.getLatitude();
                    double currrent_longitude = arg0.getLongitude();
                    LatLng current_latLng = new LatLng(current_latitude, currrent_longitude);
                    googleMap.moveCamera(CameraUpdateFactory.newLatLng(current_latLng));

                    Log.e("CURRENT LONGITUDE", currrent_longitude + "");
                    Log.e("CURRENT LATITUDE", current_latitude + "");

                    googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
                    googleMap.addMarker(new MarkerOptions().position(current_latLng).title("Marker"));
                }
            });

        }


    }
}

private void fn_permission(){
    if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) ||
            (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
        if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) &&
                (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION))) {
        } else {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},
                    REQUEST_PERMISSIONS);
        }
    }

}


@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    switch (requestCode) {
        case REQUEST_PERMISSIONS: {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {

                } else {
                    Toast.makeText(MainActivity.this, "The app was not allowed to read or write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}
}