无法在Google地图上显示当前位置? [英] Unable to show current location on google map?

查看:167
本文介绍了无法在Google地图上显示当前位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发可在google map上显示我当前位置的应用程序.我已经尽力了,但无法在google map上显示我的当前位置. 下面是我的代码. '

I am working on app which show my current location on google map.I have tried hard but i am not able to show my current location on google map. Below is my code. '

public class HomeFragment extends Fragment implements OnMapReadyCallback, LocationListener {

    GoogleMap mMap;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    public void initGamp(View root) {

        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        // check if map is created successfully or not


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_home, container, false);

        initGamp(rootView);

        // Inflate the layout for this fragment
        return rootView;
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

        mMap = googleMap;

        // Add a marker in Sydney, Australia, and move the camera.
//        LatLng sydney = new LatLng(-34, 151);
//        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
//        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), 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;
        }
        Log.i("MAP","BEFORE LOCATION");
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
        Log.i("MAP", "AFTER LOCATION");
        LocationManager locationManager = (LocationManager) getActivity().getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(bestProvider);
        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);

        Log.i("MAP", "END LOCATION");



    }

    @Override
    public void onLocationChanged(Location location) {

        Log.i("MAP","CHANGE LOCATION");

        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        LatLng latLng = new LatLng(latitude, longitude);
        mMap.addMarker(new MarkerOptions().position(latLng));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15));


    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {


    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

清单中的权限

<!-- Required to show current location -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

我已经检查了应用的gps处于打开状态,但仍未显示当前位置

I have checked the gps of app is on but still it does not show current location

推荐答案

我在设备上尝试了您的代码,并且能够看到当前位置之后移动了一小段时间( em>我认为代码触发了onLocationChanged ).它显示了蓝色的当前位置标记,它可以验证Maps的代码是否正常工作 IF 是否正确触发.

I tried out your code on a device, and I was able to see the current location AFTER moving around for a little (I think the code triggered onLocationChanged). It showed the blue current location marker, which verifies that your code for the Maps works fine IF triggered properly.

关于您发布的代码,注意到您在此if statement之后调用return;:

About the code you posted, noticed that you're calling return; after this if statement:

if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

-这使得它下面的代码无法访问.我认为这是为什么当前位置由于某种原因而没有显示的一个因素.修改后(已删除return; ),我可以继续下面的代码:

-- this makes the code below it, unreachable. I think that is a factor as to why the current location doesn't show up for some reason. After modifying it (removed return;), I was able to proceed with the code below it:

Log.i(""MAP"",""BEFORE LOCATION"");
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
        Log.i(""MAP"", ""AFTER LOCATION"");
        LocationManager locationManager = (LocationManager) getActivity().getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(bestProvider);
        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);

        Log.i(""MAP"", ""END LOCATION"");

-在这里,我只是添加了Log来查看location的值是什么,结果就是 null (首先使用模拟器对其进行了测试).我认为这会使地图不显示当前位置标记.我在清单中添加的唯一权限是ACCESS_COARSE_LOCATIONACCESS_FINE_LOCATIONWRITE_EXTERNAL_STORAGE.

-- here, I just added a Log to see what the value of location is which turns out to be null (tested it first using an emulator). I think this causes the map to NOT show a current location marker. The only permissions I added in my manifest were ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION, and WRITE_EXTERNAL_STORAGE.

PS:在您删除了if statement中的return;之后,出现了与权限有关的错误.我所做的就是按照最快的方式从此答案(我刚刚将targetSdkVersion修改为22 ).

PS: After I removed the return; in your if statement, I got an error that was related with the permissions. What I did was follow the fastest way from this answer (I just modified my targetSdkVersion to 22).

决定从现在开始在设备中对其进行测试.最初,地图可以加载,但没有显示任何当前位置标记,只是在地图的右上角显示了 为我定位 按钮,添加了Toast以显示location的值,该值仍显示为null.然后我走了一段时间,那是 地图摄像头对准并放大到我当前的位置 的地方.

Decided to test it out in a device from here on. At first, the map was able to load but did NOT show any current location marker, it just showed the locate me button in the upper right corner of the map, I also added a Toast to show the value of location, which still shows as null. Then I went and move around for sometime and that's when the map camera directed and zoomed in towards my current location.

在模拟器和设备上进行测试时,位置均已打开. :)

因此,我认为这里的主要问题是 无法在地图上显示当前位置,但是无法在地图应传递的地方传递正确的数据直接.我环顾了一会儿,看到了一些与您的代码非常相似的示例,其中仅包含一些示例.此答案中提到的示例项目是有关如何使用Location的一个很好的示例( 答案本身很有用).

So I think the main concern for you here is NOT not being able to show current location on maps but unable to pass the correct data where maps should direct. I looked around for a while and seen some examples that are quite similar to your code, they just have a few more included in it. The sample project mentioned in this answer is a good example on how to use Location (the answer itself is useful).

希望这会有所帮助.祝你好运.

Hope this helps. Good luck.

这篇关于无法在Google地图上显示当前位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆