Flutter道路距离计算插件gmaps_by_road_distance_calculator的使用

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

Flutter道路距离计算插件gmaps_by_road_distance_calculator的使用

功能

gmaps_by_road_distance_calculator 是一个Flutter插件,用于通过Google Maps API计算两个点之间的道路距离。它支持多种出行方式,如驾车、步行、骑行等。

开始使用

要使用此插件,您需要先获取一个Google Maps Platform API密钥。您可以在Google Cloud Console中创建一个项目并启用Maps SDK for Web和Directions API来获取API密钥。此外,您还可以根据需求选择不同的出行方式。

使用方法

以下是一个完整的示例代码,展示了如何使用gmaps_by_road_distance_calculator插件来计算两个点之间的道路距离。我们将创建一个简单的Flutter应用程序,用户可以输入起点和终点的经纬度,并选择出行方式,然后点击按钮计算距离。

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '道路距离计算器',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: DistanceCalculatorPage(),
    );
  }
}

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

class _DistanceCalculatorPageState extends State<DistanceCalculatorPage> {
  final TextEditingController _startLatController = TextEditingController();
  final TextEditingController _startLngController = TextEditingController();
  final TextEditingController _destLatController = TextEditingController();
  final TextEditingController _destLngController = TextEditingController();

  String _distanceResult = '';
  TravelModes _selectedTravelMode = TravelModes.driving;

  // 创建ByRoadDistanceCalculator实例
  ByRoadDistanceCalculator _distanceCalculator = ByRoadDistanceCalculator();

  Future<void> _calculateDistance() async {
    try {
      // 获取用户输入的经纬度
      double startLat = double.parse(_startLatController.text);
      double startLng = double.parse(_startLngController.text);
      double destLat = double.parse(_destLatController.text);
      double destLng = double.parse(_destLngController.text);

      // 调用getDistance方法计算距离
      var result = await _distanceCalculator.getDistance(
        'YOUR_API_KEY', // 替换为您的Google Maps API密钥
        startLat,
        startLng,
        destLat,
        destLng,
        travelMode: _selectedTravelMode,
      );

      // 更新UI显示结果
      setState(() {
        _distanceResult = '距离: ${result.distance} 米\n时长: ${result.duration}';
      });
    } catch (e) {
      // 处理异常情况
      setState(() {
        _distanceResult = '计算失败: $e';
      });
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('道路距离计算器'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _startLatController,
              decoration: InputDecoration(labelText: '起点纬度'),
              keyboardType: TextInputType.number,
            ),
            TextField(
              controller: _startLngController,
              decoration: InputDecoration(labelText: '起点经度'),
              keyboardType: TextInputType.number,
            ),
            TextField(
              controller: _destLatController,
              decoration: InputDecoration(labelText: '终点纬度'),
              keyboardType: TextInputType.number,
            ),
            TextField(
              controller: _destLngController,
              decoration: InputDecoration(labelText: '终点经度'),
              keyboardType: TextInputType.number,
            ),
            DropdownButtonFormField<TravelModes>(
              value: _selectedTravelMode,
              onChanged: (TravelModes? newValue) {
                setState(() {
                  _selectedTravelMode = newValue!;
                });
              },
              items: TravelModes.values.map((TravelModes mode) {
                return DropdownMenuItem<TravelModes>(
                  value: mode,
                  child: Text(mode.toString().split('.').last),
                );
              }).toList(),
              decoration: InputDecoration(labelText: '出行方式'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _calculateDistance,
              child: Text('计算距离'),
            ),
            SizedBox(height: 20),
            Text(_distanceResult),
          ],
        ),
      ),
    );
  }
}

更多关于Flutter道路距离计算插件gmaps_by_road_distance_calculator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter道路距离计算插件gmaps_by_road_distance_calculator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用gmaps_by_road_distance_calculator插件来计算道路距离的详细步骤和相关代码案例。

首先,确保你已经在pubspec.yaml文件中添加了gmaps_by_road_distance_calculator依赖项:

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

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

1. 初始化插件

在你的Flutter项目的Dart文件中(例如main.dart),你需要导入插件并初始化它。由于这个插件依赖于Google Maps API,你需要提供一个API密钥。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('道路距离计算示例'),
        ),
        body: Center(
          child: DistanceCalculatorExample(),
        ),
      ),
    );
  }
}

class DistanceCalculatorExample extends StatefulWidget {
  @override
  _DistanceCalculatorExampleState createState() => _DistanceCalculatorExampleState();
}

class _DistanceCalculatorExampleState extends State<DistanceCalculatorExample> {
  final GoogleMapsDistanceCalculator _distanceCalculator = GoogleMapsDistanceCalculator(apiKey: "YOUR_GOOGLE_MAPS_API_KEY");

  String _distanceResult = "";

  void _calculateDistance() async {
    try {
      var origins = ["origin_latitude,origin_longitude"]; // 替换为实际起点坐标
      var destinations = ["destination_latitude,destination_longitude"]; // 替换为实际终点坐标
      var response = await _distanceCalculator.getDistanceMatrix(origins, destinations);
      
      // 假设我们只有一个起点和一个终点
      var distance = response.rows[0].elements[0].distance.text;
      var duration = response.rows[0].elements[0].duration.text;
      
      setState(() {
        _distanceResult = "距离: $distance, 时间: $duration";
      });
    } catch (e) {
      print(e);
      setState(() {
        _distanceResult = "计算失败: $e";
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        ElevatedButton(
          onPressed: _calculateDistance,
          child: Text('计算距离'),
        ),
        Text(_distanceResult),
      ],
    );
  }
}

2. 注意事项

  • API密钥:确保你已经从Google Cloud Platform获取了Google Maps API密钥,并将其替换为YOUR_GOOGLE_MAPS_API_KEY
  • 权限:如果你的应用需要访问用户的设备位置,你需要在AndroidManifest.xmlInfo.plist中添加相应的权限。
  • 错误处理:在实际应用中,你应该添加更详细的错误处理逻辑,以处理各种可能的异常情况,例如网络错误、API限制等。

3. 运行应用

完成上述步骤后,你应该能够运行你的Flutter应用并计算两点之间的道路距离。

这个示例展示了如何使用gmaps_by_road_distance_calculator插件的基本功能。根据你的需求,你可以进一步扩展和自定义这个示例。

回到顶部