我正在尝试在单击“搜索”按钮时将“编辑”文本中的用户输入转换为LatLng。然后,这将更新相机并移动帽子位置。 这是我的主要代码:
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Gms.Maps;
using Android.Views;
using Android.Gms.Maps.Model;
using System.Collections.Generic;
using Android.Locations;
using System.Linq;
namespace SafeandSound
{
[Activity(Label = "SafeandSound", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
private GoogleMap mMap;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
SetUpMap();
}
private void SetUpMap()
{
if (mMap == null)
{
FragmentManager.FindFragmentById<MapFragment>(Resource.Id.map);
}
}
public void OnMapReady(GoogleMap googleMap)
{
mMap = googleMap;
}
// Button to Search for Address//
public void onMapSearch(View view)
{
EditText address = (EditText)FindViewById(Resource.Id.searchText);
var addressnew = address.Text;
if (addressnew != null)
{
addressnew = address.Text;
}
Geocoder geoCoder = new Geocoder(this);
IList<Address> coordinates = geoCoder.GetFromLocationName(addressnew, 0);
Address gotAddress = coordinates.FirstOrDefault();
LatLng latLng = new LatLng(gotAddress.Latitude, gotAddress.Longitude);
CameraPosition.Builder builder = CameraPosition.InvokeBuilder();
builder.Target(latLng);
builder.Zoom(10);
CameraPosition cameraPosition = builder.Build();
CameraUpdate cameraUpdate = CameraUpdateFactory.NewCameraPosition(cameraPosition);
}
}
}
当我现在使用它时,我收到异常错误。请帮助!!!
答案 0 :(得分:2)
首先,您需要通过静态方法检查设备/模拟器上的Geocoder
服务是否可用:
Geocoder.isPresent
注意:使用地理编码器需要安装互联网和Google Play服务......
接下来,您要求&#34; maxResults&#34;参数:
GetFromLocationName(addressnew, 0);
int:要返回的最大结果数。建议使用较小的数字(1到5)
此外,您可能需要重试请求才能获得结果。你不应该扼杀服务,因为你会被扼杀。使用每次尝试后增加的重试延迟。
if (!Geocoder.IsPresent)
{
Log.Error("SO", "Geocoder is not present");
}
else
{
var geocoder = new Geocoder(this);
var retry = 0;
do
{
var addressList = await geocoder.GetFromLocationNameAsync("Starbucks 523 Pine Street, Seattle, WA, 98101", 5);
if (addressList.Count > 0)
{
foreach (var address in addressList)
{
Log.Debug("SO", $"{address.Latitude}:{address.Longitude} - {address.FeatureName} : {address.GetAddressLine(0)} : {address.GetAddressLine(1)}");
}
break;
}
retry++;
Log.Warn("SO", $"No addresses returned...., retrying in {retry * 2} secs");
await Task.Delay(retry * 1000);
} while (retry < 5);
}
[SO] 47.611423:-122.337519 - Starbucks : Starbucks : 400 Pine Street
[SO] 47.611848:-122.335693 - Starbucks : Starbucks : 515 Pine Street