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

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

问题描述

我有一个 Google 地图 API 密钥,我想用它来使用 Xamarin Forms 在我的 Android 应用程序和 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. Which library would you use to have less conflict on both OS?

推荐答案

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

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

Xamarin.Forms.GoogleMaps 功能:

Xamarin.Forms.GoogleMaps features:

  • 地图类型
  • 交通地图
  • 地图事件
  • 平移动画
  • 直接平移
  • 图钉
  • 自定义 Pin 图
  • Pin 拖拽滴
  • 多边形
  • 线条
  • 圈子
  • 自定义地图图块

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

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.

安卓.在 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 中.

添加属性 com.google.android.geo.API_KEY com.google.android.gms.version org.apache.http.legacycode> 标签内的 .

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>


可选

请求运行时位置权限

如果您的应用程序面向 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 Forms(Android 和 iOS)中实现 Google 地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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