我想在Android应用中显示当前用户位置,例如GMaps中的蓝点。我在网上搜索,但我可能遗漏了一些重要的东西。
这些是我的类派生的类或接口
public class TargetActivity : AppCompatActivity, IOnMapReadyCallback, Android.Locations.ILocationListener
这段代码来自我的MainActivity,这是我第一次在Android上编程,所以我真的不知道从哪里开始。
public GoogleMap _map;
public MapFragment _mapFragment;
LocationManager locationManager;
string provider;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Target);
_mapFragment = FragmentManager.FindFragmentById(Resource.Id.map) as MapFragment;
if (_mapFragment == null)
{
GoogleMapOptions mapOptions = new GoogleMapOptions()
.InvokeMapType(GoogleMap.MapTypeTerrain)
.InvokeZoomControlsEnabled(false)
.InvokeCompassEnabled(true);
FragmentTransaction fragTx = FragmentManager.BeginTransaction();
_mapFragment = MapFragment.NewInstance(mapOptions);
fragTx.Add(Resource.Id.map, _mapFragment, "map");
fragTx.Commit();
}
_mapFragment.GetMapAsync(this);
if (_map != null)
{
_map.UiSettings.ZoomControlsEnabled = false;
_map.UiSettings.CompassEnabled = true;
_map.MapType = GoogleMap.MapTypeTerrain;
}
locationManager = (LocationManager)GetSystemService(Context.LocationService);
provider = locationManager.GetBestProvider(new Criteria(), false);
Location location = locationManager.GetLastKnownLocation(provider);
if (location == null)
{
System.Diagnostics.Debug.WriteLine("no location");
}
}
public void OnMapReady(GoogleMap googleMap)
{
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.SetPosition(new LatLng(16.03, 108));
markerOptions.SetTitle("AAAA");
googleMap.AddMarker(markerOptions);
}
public void OnLocationChanged(Location location)
{
double lat, lng;
lat = location.Latitude;
lng = location.Longitude;
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.SetPosition(new LatLng(lat, lng));
markerOptions.SetTitle("Posizione");
_map.AddMarker(markerOptions);
CameraPosition.Builder builder = CameraPosition.InvokeBuilder();
builder.Target(new LatLng(lat, lng));
CameraPosition cameraPosition = builder.Build();
CameraUpdate cameraUpdate = CameraUpdateFactory.NewCameraPosition(cameraPosition);
_map.MoveCamera(cameraUpdate);
}
public void OnProviderDisabled(string provider)
{
//throw new NotImplementedException();
}
public void OnProviderEnabled(string provider)
{
//throw new NotImplementedException();
}
public void OnStatusChanged(string provider, [GeneratedEnum] Availability status, Bundle extras)
{
//throw new NotImplementedException();
}
答案 0 :(得分:0)
您需要实施OnMyLocationButtonClickListener
和OnMyLocationClickListener
。在地图实例上启用位置服务并覆盖相关方法。只要您拥有定位权限,几乎所有内容都会为您完成。请查看文档here