简体   繁体   English

如何使用Xamarin.Forms和GoogleMaps / GeoLocation

[英]How to Use Xamarin.Forms and GoogleMaps/GeoLocation

I am writing a Xamarin.Forms PCL app, to support iOS and Android OS for my app. 我正在编写Xamarin.Forms PCL应用程序,以支持我的应用程序的iOS和Android OS。

In the root project, I have a view containing a ViewList and a map (from Xamarin.Forms.Maps). 在根项目中,我有一个包含ViewList和地图的视图(来自Xamarin.Forms.Maps)。

I learnt I have to use CustomRenderer for each platform to add customized behavior. 我了解到必须为每个平台使用CustomRenderer才能添加自定义行为。 What I am trying to achieve to add a LocationManager/GeoLocation to identify the users position via GPS and show his position with a pin/marker. 我想要实现的目的是添加一个LocationManager / GeoLocation以通过GPS识别用户的位置,并使用图钉/标记显示其位置。 Additionally to that, I get positions from the root project of several persons which pins must also be shown within the map. 除此之外,我还从几个人的根项目中获得位置,这些销也必须显示在地图中。

Should I have to use an interface exporting functionality or use an appropriate custom map renderer? 我应该使用接口导出功能还是使用适当的自定义地图渲染器?

I have no idea to achieve that, the examples at the Xamarin.Forms website and research within Stackoverflow do not give a hint. 我不知道要实现这一点,Xamarin.Forms网站上的示例以及Stackoverflow中的研究都没有给出任何提示。

Here is some code I have so far (extract): 这是我到目前为止(摘录)的一些代码:

using System;
using Awesome;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using Plugin.Geolocator;
using System.Threading.Tasks;

namespace KiLa
{
    public class KidsFinder : ContentPage, ITabPage
    {
        public string TabIcon => FontAwesome.FAMapMarker;
        public string SelectedTabIcon => FontAwesome.FAMapMarker;
        private Boolean _showKidsList;
        private ListView _listView;
        public ObservableCollection<KidsViewModel> kidsList = new ObservableCollection<KidsViewModel>();

        public KidsFinder ()
        {

            Title = "KidsFinder";
            // Define listView

            // Any near/identified kids? Mockup
            // TODO: get real data
            Boolean kidsPresent = true;

            // Initial height of map
            double mapHeight = 300.0;

            // coordinates of Beuth Hochschule, Haus Gauss
            double latitude = 52.543100;
            double longitude = 13.351450;

            // Show/hide kidsList (listView)
            //Boolean showKidsList = false;
            _showKidsList = false;

            // Define toggleButton
            Button toggleButton = new Button();
            toggleButton.Text = "Verstecke Liste";

            toggleButton.Clicked += new EventHandler(OnClickEvent);

            if(kidsPresent == true) 
            {
                toggleButton.IsVisible = true;
                mapHeight = 200.0;
                _showKidsList = true;
            } else 
                {
                    toggleButton.IsVisible = false;
                    mapHeight = 300.0;
                    _showKidsList = false;
                }

            // Mockup some kids
            Position pos1 = new Position(latitude + 0.002, longitude + 0.002);
            Position pos2 = new Position (latitude - 0.002, longitude - 0.002);
            kidsList.Add(new KidsViewModel{Name="Tim", ActualPositon=pos1, DistanceToEducator=5.4});
            kidsList.Add(new KidsViewModel{Name="Sabine", ActualPositon=pos2, DistanceToEducator=20.4});

            _listView = new ListView();
            _listView.ItemsSource = kidsList;
            //listView.VerticalOptions = LayoutOptions.FillAndExpand;
            _listView.ItemTemplate = new DataTemplate (typeof(KidsCustomCell));
            _listView.RowHeight = 50;

            if (_showKidsList == false) {
                _listView.IsVisible = false;
            } else {
                _listView.IsVisible = true;
            }

            // Define mapView
            var kidsMap = new KidsMap ();
            kidsMap.MapType = MapType.Street;
            kidsMap.WidthRequest = 960;
            kidsMap.HeightRequest = mapHeight;
            kidsMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(latitude,longitude), Distance.FromMiles(0.3)));

            // Set label of pins with kids names,
            foreach (KidsViewModel kvm in kidsList) {
                Pin pin = new Pin() {
                    Label = kvm.Name,
                    Position = kvm.ActualPositon
                };
                    kidsMap.Pins.Add(pin);
            }

You should use GetLocation and declare the permissions necessary to use the LocationServices 您应该使用GetLocation并声明使用LocationServices所需的权限

[assembly: UsesPermission(Manifest.Permission.AccessFineLocation)]
[assembly: UsesPermission(Manifest.Permission.AccessCoarseLocation)]

This is not strictly necessary for obtaining the GPS coordinates of the device, but this example will attempt to provide a street address for the current location: 这对于获取设备的GPS坐标不是绝对必要的,但是此示例将尝试提供当前位置的街道地址:

[assembly: UsesPermission(Manifest.Permission.Internet)]

Add a method called InitializeLocationManager to activity 向活动添加一个名为InitializeLocationManager的方法

void InitializeLocationManager()
{
_locationManager = (LocationManager) GetSystemService(LocationService);
Criteria criteriaForLocationService = new Criteria
{
Accuracy = Accuracy.Fine
};
IList<string> acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);

if (acceptableLocationProviders.Any())
{
_locationProvider = acceptableLocationProviders.First();
}
 else
{
_locationProvider = string.Empty;
}
Log.Debug(TAG, "Using " + _locationProvider + ".");
}

The LocationManager class will listen for GPS updates from the device and notify the application by way of events. LocationManager类将侦听来自设备的GPS更新,并通过事件通知应用程序。 In this example we ask Android for the best location provider that matches a given set of Criteria and provide that provider to LocationManager. 在此示例中,我们向Android请求与给定条件集匹配的最佳位置提供程序,并将该提供程序提供给LocationManager。

For more details how to get current location using Xamarin Forms, follow this link: https://developer.xamarin.com/recipes/android/os_device_resources/gps/get_current_device_location/ 有关如何使用Xamarin表单获取当前位置的更多详细信息,请访问以下链接: https : //developer.xamarin.com/recipes/android/os_device_resources/gps/get_current_device_location/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM