Flutter高德地图集成插件amap_map_fluttify的使用

Flutter高德地图集成插件amap_map_fluttify的使用

Logo

高德地图 地图组件 Flutter插件

pub package

依赖

dependencies:
  flutter:
    sdk: flutter
  amap_map_fluttify: ^x.x.x

配置

Android

  1. 注意在app/build.gradleandroid块中配置签名信息,并在buildTypes块中指定签名信息,否则将无法匹配到你在高德后台配置的appkey,例如:
android {
    signingConfigs {
        release {
            keyAlias 'amap_map_test'
            keyPassword 'amap_map_test'
            storeFile file('../amap_map_test.jks')
            storePassword 'amap_map_test'
        }
    }

    buildTypes {
        debug {
            signingConfig signingConfigs.release
        }
        profile {
            signingConfig signingConfigs.release
        }
        release {
            signingConfig signingConfigs.release
        }
    }
}

iOS

  1. 定位需要声明权限,在Info.plist中添加:
<key>NSLocationWhenInUseUsageDescription</key>
<string>需要定位权限</string>
  1. 调用高德地图需要添加白名单:
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>iosamap</string>
    <string>amapuri</string>
</array>

导入

import 'package:amap_map_fluttify/amap_map_fluttify.dart';

使用

参考wiki.

LICENSE

Copyright (C) 2022 yohom

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see https://www.gnu.org/licenses/.

示例代码

example/lib/main.dart

import 'package:amap_map_fluttify/amap_map_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';

import 'map/map.screen.dart';

Future<void> main() async {
  runApp(MyApp());

  // 开启或关闭日志输出
  await enableFluttifyLog(false);

  // 更新隐私政策同意状态
  await AmapSearch.instance.updatePrivacyAgree(true);
  
  // 更新隐私政策展示状态
  await AmapSearch.instance.updatePrivacyShow(true);

  // 初始化高德地图服务
  await AmapService.instance.init(
    iosKey: '7a04506d15fdb7585707f7091d715ef4',
    androidKey: '7c9daac55e90a439f7b4304b465297fa',
    webKey: 'e69c6fddf6ccf8de917f5990deaa9aa2',
  );
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return OKToast(
      child: MaterialApp(
        home: Scaffold(
          appBar: AppBar(title: const Text('AMaps examples')),
          backgroundColor: Colors.grey.shade200,
          body: MapDemo(), // 这里使用你自定义的地图组件
        ),
      ),
    );
  }
}

请注意,上述代码中的MapDemo()是一个示例组件,你需要根据实际情况实现自己的地图组件。


更多关于Flutter高德地图集成插件amap_map_fluttify的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter高德地图集成插件amap_map_fluttify的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter项目中集成高德地图,可以使用amap_map_fluttify插件。以下是一个简单的代码示例,展示了如何集成和使用该插件来显示一个基本的地图。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加amap_map_fluttify依赖:

dependencies:
  flutter:
    sdk: flutter
  amap_map_fluttify: ^x.y.z  # 请替换为最新版本号

然后运行flutter pub get来安装依赖。

2. 配置Android和iOS

Android

在你的android/app/src/main/AndroidManifest.xml文件中添加必要的权限和高德地图的API Key:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <!-- 添加必要的权限 -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

    <!-- 高德地图API Key -->
    <application
        ... >
        <meta-data
            android:name="com.amap.api.v2.apikey"
            android:value="你的高德地图API Key"/>
        ...
    </application>

</manifest>

iOS

在你的ios/Runner/Info.plist文件中添加高德地图的API Key:

<key>io.flutter.embedded_views_preview</key>
<true/>
<key>AMapAPIKey</key>
<string>你的高德地图API Key</string>

同时,确保在ios/Podfile中启用了Swift支持(如果还没有的话):

platform :ios, '9.0'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug': :debug,
  'Profile': :release,
  'Release': :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  config = use_native_modules!

  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))

  # Add the pods for the dependencies added to your pubspec.yaml
  pod 'amap_map_fluttify', :path => '../node_modules/amap_map_fluttify/.ios'
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['SWIFT_VERSION'] = '5.0'  # 或者更高版本
    end
  end
end

3. 使用高德地图插件

在你的Flutter项目中,创建一个新的Dart文件(例如map_page.dart),并添加以下代码来显示地图:

import 'package:flutter/material.dart';
import 'package:amap_map_fluttify/amap_map_fluttify.dart';

class MapPage extends StatefulWidget {
  @override
  _MapPageState createState() => _MapPageState();
}

class _MapPageState extends State<MapPage> {
  AmapController? _amapController;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('高德地图示例'),
      ),
      body: AmapView(
        onMapCreated: (AmapController controller) {
          _amapController = controller;
          _amapController!.moveCamera(CameraUpdate.newLatLngZoom(
            LatLng(39.9042, 116.4074), // 北京天安门坐标
            14.0,
          ));
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          if (_amapController != null) {
            _amapController!.showMarker(
              MarkerOption()
                ..position = LatLng(39.9042, 116.4074)
                ..title = "天安门"
                ..snippet = "北京的中心",
            );
          }
        },
        tooltip: '添加标记',
        child: Icon(Icons.add),
      ),
    );
  }
}

4. 在主应用中使用MapPage

最后,在你的主应用文件(例如main.dart)中引入并使用MapPage

import 'package:flutter/material.dart';
import 'map_page.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter高德地图示例',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MapPage(),
    );
  }
}

这样,你就成功地在Flutter项目中集成了高德地图,并显示了一个基本的地图界面。你可以根据需要进一步自定义和扩展地图功能。

回到顶部