要查找附近的位置,可以使用Xamarin forms 中的Google Places API Web Service。使用这个api 可以从谷歌服务器检索谷歌地方数据。地点数据包括有关餐馆、旅馆、医院、保健中心等的信息。示例是这样的:
public async Task<List<Place>> GetNearByPlacesAsync()
{
RootObject rootObject=null;
client = new HttpClient();
CultureInfo In = new CultureInfo("en-IN");
string latitude = position.Latitude.ToString(In);
string longitude = position.Longitude.ToString(In);
string restUrl = $"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+latitude+","+longitude+"&radius=1000&type="+search+"&key=your API";
var uri = new Uri(restUrl);
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
rootObject = JsonConvert.DeserializeObject<RootObject>(content);
}
else
{
await Application.Current.MainPage.DisplayAlert("No web response", "Unable to retrieve information, please try again", "OK");
}
return rootObject.results;
}
此根对象包含 Web 请求中询问的所有信息。现在您可以通过pins 显示附近的位置,如下所示:
private async void AddPins()
{
try
{
var Places = await GetNearByPlacesAsync();
if (Places.Count == 0|| Places==null)
await Application.Current.MainPage.DisplayAlert("No Places found", "No Places found for this location", "OK");
else
{
map.Pins.Clear();
foreach(Place place in Places)
{
map.Pins.Add(new Pin()
{
BindingContext = place,
Tag = place,
Label = place.name,
Position = new Position(place.geometry.location.lat, place.geometry.location.lng),
});
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(@" ERROR{0}", ex.Message);
}
}
map 是 UI 中 Map Element 的名称。