如何在Xamarin应用程序的Map功能中获取当前位置坐标?

时间:2017-03-13 02:51:13

标签: xamarin xamarin.forms

我正在开发App中的位置坐标标记功能。

我正在使用以下dll和谷歌地图。

Xamarin.Forms.Maps
Xam.Plugin.Geolocator
Xam.Plugin.ExternalMaps

在我的iphone模拟器中,如果位置是NONE.It默认位置在意大利罗马的一些地方

以下是为拉动地图而编写的代码..

public async Task<Xamarin.Forms.Maps.Position> GetPosition()
        {
            IsBusy = true;
            Xamarin.Forms.Maps.Position p;
            try
            {
                if (!locator.IsGeolocationAvailable)
                {
                    p = new Xamarin.Forms.Maps.Position();
                }
                if (!locator.IsGeolocationEnabled)
                {
                    p = new Xamarin.Forms.Maps.Position();
                }
                var position = await locator.GetPositionAsync(timeoutMilliseconds: 10000);
                p = new Xamarin.Forms.Maps.Position(position.Latitude,position.Longitude);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                p = new Xamarin.Forms.Maps.Position();
            }
            IsBusy = false;

            return p;
        }

        public async Task<object> GetCityName(double latitude, double longitude) { 
            HttpClient client;
            client = new HttpClient();
            client.MaxResponseContentBufferSize = 256000;
            try
            {
                var response = await client.GetAsync("https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude);
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    var json = Newtonsoft.Json.Linq.JObject.Parse(result);
                    var reValue = "" + json["results"][0]["formatted_address"];

                    var strArr = reValue.Split(',');
                    if (strArr.Length > 2)
                        return strArr[strArr.Length - 2] + ", " +strArr[strArr.Length - 1];
                    else
                        return "";
                }
                else {
                    Debug.WriteLine(@"Failed.");
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(@"ERROR {0}", ex.Message);
                return ex.Message;
            }
        }

图片:

enter image description here

1 个答案:

答案 0 :(得分:0)

请详细说明您的问题,并按如下方式更改您的条件:

List

现在处理来自if (CrossGeolocator.Current.IsGeolocationAvailable) { if (CrossGeolocator.Current.IsGeolocationEnabled) { var position = await locator.GetPositionAsync(timeoutMilliseconds: 10000); p = new Xamarin.Forms.Maps.Position(position.Latitude,position.Longitude); } else { throw new Exception("Geolocation is turned off"); // Geolocation is turned off for the device. } } else { throw new Exception("Geolocation is turned off"); // Geolocation not available for device } 方法的捕获,以确保您没有获得默认位置。