如何在Xamarin表单(Android和iOS)中实现Google地图? [英] How to implement Google maps in Xamarin Forms (Android and iOS)?

查看:86
本文介绍了如何在Xamarin表单(Android和iOS)中实现Google地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Google Map API密钥,我想用它在我的Android应用程序和使用Xamarin Forms的iOS应用程序中显示地图.

I have a Google map API key and I want to use that to show maps in my Android app and iOS app using Xamarin Forms.

推荐答案

使用NuGet的一种简单实现方法 Xamarin.Forms.GoogleMaps

An easy way to implement that is using the NuGet Xamarin.Forms.GoogleMaps

Xamarin.Forms.GoogleMaps功能:

Xamarin.Forms.GoogleMaps features:

  • 地图类型
  • 交通地图
  • 地图事件
  • 通过动画平移
  • 直接摇动
  • 别针
  • 自定义图钉
  • 图钉拖放放下
  • 多边形
  • 圆圈
  • 自定义地图图块
  • Map types
  • Traffic map
  • Map events
  • Panning with animation
  • Panning directly
  • Pins
  • Custom Pins
  • Pin drag & drop
  • Polygons
  • Lines
  • Circles
  • Custom map tiles

请按照以下步骤在您的项目中设置地图:

Follow the next steps to set up maps in your project:

  1. 在所有项目中安装NuGet包Xamarin.Forms.GoogleMaps.

  1. Install the NuGet package Xamarin.Forms.GoogleMaps in all projects.

Android .通过OnCreate方法在MainActivity.cs中初始化库:

Android. Initialize the library in your MainActivity.cs in the OnCreate method:

    protected override void OnCreate(Bundle savedInstanceState)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;
    
        base.OnCreate(savedInstanceState);
    
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
        Xamarin.FormsGoogleMaps.Init(this, savedInstanceState); //Initialize GoogleMaps here
        LoadApplication(new App());
    }

  1. 在您的AndroidManifest.xml中.

在标签<application>内添加属性com.google.android.geo.API_KEY com.google.android.gms.version org.apache.http.legacy.

Add the properties com.google.android.geo.API_KEY com.google.android.gms.version org.apache.http.legacy inside the tag <application>.

还添加了所需的权限ACCESS_COARSE_LOCATION ACCESS_FINE_LOCATION.

Also adds the required permissions ACCESS_COARSE_LOCATION ACCESS_FINE_LOCATION.

如果要使用地理位置,请添加一些使用功能.

Add some uses-feature if you will use geolocation.

您的AndroidManifest.xml应该如下所示:

Your AndroidManifest.xml should look like this:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="yvan.eht.nioj" android:installLocation="auto">
        <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
        <application android:label="YourApp.Android">
            <meta-data android:name="com.google.android.geo.API_KEY" android:value="Your_Api_Key_Here" />
            <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
            <uses-library android:name="org.apache.http.legacy" android:required="false" />
        </application>
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-feature android:name="android.hardware.location" android:required="false" />
        <uses-feature android:name="android.hardware.location.gps" android:required="false" />
        <uses-feature android:name="android.hardware.location.network" android:required="false" />
    </manifest>

  1. iOS .使用FinishedLaunching方法初始化AppDelegate.cs中的库:
  1. iOS. Initialize the library in your AppDelegate.cs in the FinishedLaunching method:

   public override bool FinishedLaunching(UIApplication app, NSDictionary options)
   {
       global::Xamarin.Forms.Forms.Init();
       Xamarin.FormsGoogleMaps.Init("Your_Api_Key_Here");
       LoadApplication(new App());

       return base.FinishedLaunching(app, options);
   }

  1. 在您的Info.plist中添加属性NSLocationAlwaysUsageDescription NSLocationWhenInUseUsageDescription NSLocationAlwaysAndWhenInUseUsageDescription

    <? xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
      <dict>
        <!--Your other Permissions may be on top -->
        <!-- Just add the Permissions below -->

        <key>NSLocationAlwaysUsageDescription</key>
        <string>Can we use your location at all times?</string>
        <key>NSLocationWhenInUseUsageDescription</key>
        <string>Can we use your location when your application is being used?</string>
        <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
        <string>Can we use your location at all times?</string>
      </dict>
    </plist>

完成


现在,您可以在xaml中添加地图,并在Android和iOS应用中显示它,如下所示:

DONE


Now you can add a map in your xaml and show it in your Android and iOS app like this:

    <?xml version="1.0" encoding="utf-8"?>
    <ContentPage
        xmlns="http://xamarin.com/schemas/2014/forms"
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        xmlns:d="http://xamarin.com/schemas/2014/forms/design"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:maps="clr-namespace:Xamarin.Forms.GoogleMaps;assembly=Xamarin.Forms.GoogleMaps"
        mc:Ignorable="d"
        x:Class="YourApp.MainPage">
        <ContentPage.Content>
            <Grid HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
    
                <maps:Map x:Name="map" VerticalOptions="FillAndExpand"></maps:Map>
            </Grid>
        </ContentPage.Content>
    </ContentPage>


可选

请求运行时位置权限


OPTIONAL

Request runtime location permissions

如果您的应用程序以API 23或更高版本为目标,并且需要访问用户的位置,则它必须检查运行时是否具有所需的权限,如果没有,则请求它.可以完成以下操作:

If your application targets API 23 or later and needs to access the user's location, it must check to see if it has the required permission at runtime, and request it if it does not have it. This can be accomplished as follows:

  1. 在MainActivity类中,添加以下字段:

    const int RequestLocationId = 0;
    
    readonly string[] LocationPermissions =
    {
        Manifest.Permission.AccessCoarseLocation,
        Manifest.Permission.AccessFineLocation
    };

  1. 在MainActivity类中,添加以下OnStart覆盖:

    protected override void OnStart()
    {
        base.OnStart();
    
        if ((int)Build.VERSION.SdkInt >= 23)
        {
            if (CheckSelfPermission(Manifest.Permission.AccessFineLocation) != Permission.Granted)
            {
                RequestPermissions(LocationPermissions, RequestLocationId);
            }
            else
            {
                // Permissions already granted - display a message.
            }
        }
    }

  1. (如果使用的是Xamarin Essentials,则不需要)在MainActivity类中,添加以下OnRequestPermissionsResult覆盖:

    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
    {
        if (requestCode == RequestLocationId)
        {
            if ((grantResults.Length == 1) && (grantResults[0] == (int)Permission.Granted))
                // Permissions granted - display a message.
            else
                // Permissions denied - display a message.
        }
        else
        {
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

这篇关于如何在Xamarin表单(Android和iOS)中实现Google地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆