2017-03-06 104 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名稱。