要找到附近的位置可以使用Google Places API Web Service
在Xamarin forms
。使用這個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;
}
此根對象具有網絡請求中詢問的所有信息。現在,你可以通過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
名稱。