2017-03-06 58 views
0

我找到了获取位置纬度和经度的代码。现在,我想找到一个靠近的位置。就像在附近找到一家餐馆。Xamarin - 靠近位置获取

所以,如果我搜索地铁,我应该得到附近地铁的坐标。

要找到我用这个代码的位置:

var locator = CrossGeolocator.Current; 
      locator.DesiredAccuracy = 50; 
      var position = await locator.GetPositionAsync(timeoutMilliseconds: 10000); 

但我怎么能按位置获得近吗? 我想用Xamarin Forms。

回答

1

但我怎样才能得到附近的位置?我想用Xamarin Forms。

我想你跟着公文Adding a Map in Xamarin.Forms建立自己的应用程序,但Xamarin形式APIs for Map仅用于显示和注释地图。

对于Android平台,指南中使用的地图服务是​​,要找到附近的位置,我们需要使用Places API for Android,并且没有Xamarin Forms API来完成这项工作。由于Xamarin.Forms是一个跨平台UI工具包,允许开发人员创建跨平台共享的本地用户界面布局,因此我们需要使用DependencyService从PCL调用特定于平台的功能。对于iOS平台,我并不熟悉iOS开发,但我认为Xamarin Forms工具包的地图使用的是本地iOS的地图,据我所知,iOS本地地图的地图服务取决于用户所在的区域是。但是你可以按照官方的文档About Location Services and Maps找到附近的地方。另外,我们需要使用DependencyService来从PCL调用iOS平台API。

无论如何,现在还没有简单的方法可以从PCL调用API来找到一个地方,我们需要在每个平台上实现此功能。

0

要找到附近的位置可以使用Google Places API Web ServiceXamarin 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名称。