繁体   English   中英

如何在Android Google Map中获取用户位置

[英]How to get user location in android google map

我有以下代码用于在我的应用中显示用户位置:

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, LocationListener {
    private GoogleMap googleMap;
    private Marker userMarker;
    private Marker destinationMarker;
    private Location userLocation;
    private Location destinationLocation;
    private static final int REQUEST_CODE = 101;

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

    SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    supportMapFragment.getMapAsync(this);

}

private void setupLocationManager() {
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    if (locationManager != null) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION
                        , Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE);
            }
            return;
        }
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            onLocationChanged(location);
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 4000, 5, this);
        }
    }
}

@Override
public void onMapReady(final GoogleMap googleMap) {
    this.googleMap = googleMap;
    googleMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
        @Override
        public void onMapLongClick(LatLng latLng) {
            destinationLocation = new Location(LocationManager.GPS_PROVIDER);
            destinationLocation.setLatitude(latLng.latitude);
            destinationLocation.setLongitude(latLng.longitude);
            Polyline line = googleMap.addPolyline(new PolylineOptions()
                    .add(new LatLng(userLocation.getLatitude(),
                            userLocation.getLongitude()), new LatLng(destinationLocation.getLatitude(),
                            destinationLocation.getLongitude())).color(Color.BLUE).width(10).geodesic(true));
            destinationMarker = googleMap.addMarker(new MarkerOptions().position(latLng).title("Destination Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_destination_marker)));
        }
    });
    setupLocationManager();
}

@Override
public void onLocationChanged(Location location) {
    if (location != null && googleMap != null) {
        userLocation = location;
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        if (userMarker != null) {
            userMarker.remove();
        }
        userMarker = googleMap.addMarker(new MarkerOptions().position(latLng).title("Your Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_user_marker)));
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
        googleMap.animateCamera(cameraUpdate);
    }else {
        Toast.makeText(MainActivity.this,"Location is null",Toast.LENGTH_LONG).show();
    }
}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_CODE) {
        if (grantResults[0] == 0) {
            setupLocationManager();
        }
    }
}
}

我的清单权限:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

我有两个问题:

  • 首先:我的代码不显示真实设备中的用户位置(应用程序始终显示位置为空 (onLocationChanged()中的吐司消息)我不知道为什么(已解决)
  • 第二:我想在公路上显示我的折线。 我知道isGeodesic()函数,但是当我使用时它不会显示...

您确定“位置”为空是因为在您的示例中,如果“ googleMap”为空也可以显示吐司吗?

如果您的“位置”为空,请确保您在Android Manifest文件中具有以下权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

然后检查是否向您的应用程序授予了位置许可权(如果您使用的API版本为23或更高版本的设备非常重要,但我认为您是在授予该许可权是因为您要覆盖“ onRequestPermissionsResult”方法)。

如果一切正常,请检查是否启用了设备位置;如果没有,请启用设备并等待位置更改。

添加googleMap.setMyLocationEnabled(true); 在您的onMapReady()中,它将在Google地图上显示用户位置。

 @Override
        public void onMapReady(final GoogleMap googleMap) {
            this.googleMap = googleMap;
            final LatLng current_position = new LatLng(latitude, longitude);
            MarkerOptions marker = new MarkerOptions().position(current_position).title("XY Address").snippet("XY Address");
            googleMap.addMarker(marker);
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(current_position, 12));
            googleMap.getUiSettings().setMapToolbarEnabled(true);
            googleMap.setMyLocationEnabled(true);
    }

暂无
暂无

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

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