Flutter谷歌街景展示插件flutter_google_street_view的使用

发布于 1周前 作者 yibo5220 来自 Flutter

Flutter谷歌街景展示插件 flutter_google_street_view 的使用

flutter_google_street_view 是一个用于在 Flutter 应用中展示 Google 街景的插件,支持 Web、Android 和 iOS 平台。

开始使用

获取 API Key

  1. 访问 Google Cloud Platform 获取 API Key。
  2. 启用 Google Maps SDK:
    • 登录 Google Developers Console
    • 选择项目并导航到“Google Maps”菜单下的“APIs”部分。
    • 启用“Maps SDK for Android”和“Maps SDK for iOS”。

更多详情请参阅 Getting started with Google Maps Platform

Web 配置

web/index.html 中添加你的 API Key:

<head>
  <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
</head>

Android 配置

android/app/src/main/AndroidManifest.xml 中添加你的 API Key:

<manifest ...>
  <application ...>
    <meta-data android:name="com.google.android.geo.API_KEY"
               android:value="YOUR KEY HERE"/>
  </application>
</manifest>

iOS 配置

ios/Runner/AppDelegate.mios/Runner/AppDelegate.swift 中添加你的 API Key:

Objective-C:

#import "AppDelegate.h"
#import "GeneratedPluginRegistrant.h"
#import "GoogleMaps/GoogleMaps.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GMSServices provideAPIKey:@"YOUR KEY HERE"];
  [GeneratedPluginRegistrant registerWithRegistry:self];
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end

Swift:

import UIKit
import Flutter
import GoogleMaps

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GMSServices.provideAPIKey("YOUR KEY HERE")
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

控制街景视图

你可以通过 StreetViewController 来控制街景视图,该控制器会在 onStreetViewCreated 回调中返回。

示例代码

以下是一个简单的示例,展示了如何初始化 FlutterGoogleStreetView

class StreetViewPanoramaInitDemo extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Street View Init Demo'),
          leading: IconButton(
            icon: Icon(Icons.arrow_back),
            onPressed: () => Navigator.pop(context),
          ),
        ),
        body: SafeArea(
          child: Stack(
            children: [
              FlutterGoogleStreetView(
                initPos: LatLng(25.0780892, 121.5753234),
                initSource: StreetViewSource.outdoor,
                initBearing: 30,
                onStreetViewCreated: (StreetViewController controller) async {
                  // 使用 controller 进行控制
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

完整示例应用

完整的示例应用可以在 GitHub 上找到。以下是完整示例应用的主页面代码:

import 'package:flutter/material.dart';
import 'demo/street_view_panorama_events.dart';
import 'demo/street_view_panorama_navigation.dart';
import 'demo/street_view_panorama_in_listview.dart';
import 'demo/street_view_panorama_init.dart';
import 'demo/street_view_panorama_options.dart';

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

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();
  }

  Future<void> initPlatformState() async {
    if (!mounted) return;
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(debugShowCheckedModeBanner: false, home: HomePage());
  }
}

class HomePage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Street View Example')),
      body: SafeArea(
        child: ListView(
          children: [
            ListTile(
              title: Text("Street View Panorama init"),
              subtitle: Text("An example of street view init."),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => StreetViewPanoramaInitDemo()),
                );
              },
            ),
            Divider(height: 1, thickness: 1),
            ListTile(
              title: Text("Street View Panorama events"),
              subtitle: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text.rich(
                    TextSpan(children: [
                      TextSpan(text: "An example of street view event handling."),
                      TextSpan(text: " Include invalid panorama event.", style: TextStyle(fontWeight: FontWeight.bold)),
                    ]),
                  ),
                  SizedBox(height: 8),
                  DefaultTextStyle(
                      style: TextStyle(color: Colors.redAccent, fontWeight: FontWeight.bold),
                      child: Row(
                        children: [
                          Expanded(child: Text("Notice! Developers should care this demo and learn how to receive event.")),
                          Text("🙏"),
                        ],
                      )),
                ],
              ),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => StreetViewPanoramaEventsDemo()),
                );
              },
            ),
            Divider(height: 1, thickness: 1),
            ListTile(
              title: Text("Street View Panorama navigation"),
              subtitle: Text("An example to show how to use navigation related function."),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => StreetViewPanoramaNavigationDemo()),
                );
              },
            ),
            Divider(height: 1, thickness: 1),
            ListTile(
              title: Text("Street View Panorama options"),
              subtitle: Text("A example to inactive/active options."),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => StreetViewPanoramaOptionsDemo()),
                );
              },
            ),
            Divider(height: 1, thickness: 1),
            ListTile(
              title: Text("Street View Panorama in ListView"),
              subtitle: Text("A example to show how to feed touch event when street view is a child of ListView."),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => StreetViewPanoramaInListViewDemo()),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

更多关于Flutter谷歌街景展示插件flutter_google_street_view的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter谷歌街景展示插件flutter_google_street_view的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用 flutter_google_street_view 插件在 Flutter 应用中展示谷歌街景的示例代码。

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

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

然后运行 flutter pub get 来获取依赖。

接下来,在你的 Flutter 应用中使用 StreetViewPanoramaWidget 来展示谷歌街景。以下是一个完整的示例:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Google Street View Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: StreetViewDemo(),
    );
  }
}

class StreetViewDemo extends StatefulWidget {
  @override
  _StreetViewDemoState createState() => _StreetViewDemoState();
}

class _StreetViewDemoState extends State<StreetViewDemo> {
  final String apiKey = 'YOUR_GOOGLE_MAPS_API_KEY'; // 请替换为你的谷歌地图API密钥
  final String panoramaId = 'YOUR_PANORAMA_ID'; // 请替换为你想要展示的街景ID

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Google Street View Demo'),
      ),
      body: Center(
        child: StreetViewPanoramaWidget(
          apiKey: apiKey,
          panoramaId: panoramaId,
          onStreetViewPanoramaCameraChange: (StreetViewPanoramaCamera camera) {
            // 当街景视角改变时调用
            print('Camera position changed: ${camera.targetLatLng}');
          },
          onError: (StreetViewPanoramaError error) {
            // 当发生错误时调用
            print('StreetView error: ${error.message}');
          },
        ),
      ),
    );
  }
}

在这个示例中:

  1. 添加依赖:在 pubspec.yaml 中添加 flutter_google_street_view 依赖。
  2. 替换API密钥和街景ID:在代码中,用你自己的谷歌地图API密钥替换 YOUR_GOOGLE_MAPS_API_KEY,用你想要展示的街景ID替换 YOUR_PANORAMA_ID
  3. 使用 StreetViewPanoramaWidget:在 StreetViewDemo 组件中,使用 StreetViewPanoramaWidget 来展示谷歌街景。
  4. 处理视角变化和错误:通过 onStreetViewPanoramaCameraChangeonError 回调来处理街景视角变化和错误情况。

确保你已经启用了谷歌地图街景API,并且在谷歌云平台上为你的项目配置了相应的API密钥。此外,请遵守谷歌地图API的使用条款和条件。

回到顶部