简体   繁体   English

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

[英]Not able to get current location in Google Map fragment

I am trying to get current location in map fragment but the crashes with an error in line googleMap.setMyLocationEnabled(true); 我正在尝试在地图片段中获取当前位置,但是由于googleMap.setMyLocationEnabled(true)行中的错误而崩溃; I used Location and Latlang to detect current location. 我使用了Location和Latlang来检测当前位置。

mapFragment.java 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 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" />

Looks like you have a few issues, but the crash is happening because you need to call getMap() before you call setMyLocationEnabled() . 看起来你有一些问题,但飞机坠毁发生,因为你需要调用getMap()调用之前setMyLocationEnabled()

Change this: 更改此:

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

...to this: ...对此:

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

Updated: I was able to get this code working. 更新:我能够使此代码正常工作。

Getting the current location should be done with the Fused Location Provider API , but that is beyond the scope of this question. 获取当前位置应该使用融合位置提供程序API来完成,但这超出了此问题的范围。

The method in this sample code might work on older devices, but on 4.4.4 it's returning a null location due to getMyLocation() being depricated. 此示例代码中的方法可能适用于较旧的设备,但在4.4.4上,由于使用了getMyLocation() ,因此返回的是空位置。

However, with the null check in place the map displays correctly, and you can click on the location button to have the map move to your current location. 但是,使用null选中后,地图将正确显示,您可以单击“位置”按钮以将地图移至当前位置。

        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;
        }

You can use the setOnMyLocationChangeListener method to get the current location. 您可以使用setOnMyLocationChangeListener方法获取当前位置。 Download the source here( Show Google Map In Android ) 在此处下载源代码( 在Android中显示Google Map

MainActivity.Java 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();
                }
            }
        }
    }
}
}

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

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