flutter高德定位 (fluttermap中地图加载慢)

flutter导航布局,flutter高德定位

在Flutter中实现地图定位和导航,可以使用一些第三方插件,如`google_maps_flutter`用于显示地图,`location`用于获取当前位置,以及`flutter_polyline_points`和`google_maps_directions`用于绘制导航路线。以下是一个基本的实现步骤:

1. **添加依赖**:

在`pubspec.yaml`文件中添加所需的插件依赖。

dependencies:

flutter:

sdk: flutter

google_maps_flutter: ^2.0.6 # 使用时请检查最新版本

location: ^4.3.0 # 使用时请检查最新版本

flutter_polyline_points: ^1.0.0 # 使用时请检查最新版本

google_maps_directions: ^1.0.0 # 使用时请检查最新版本

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

2. **导入包**:

在你的Dart文件中导入所需的包。

import 'package:google_maps_flutter/google_maps_flutter.dart';

import 'package:location/location.dart';

import 'package:flutter_polyline_points/flutter_polyline_points.dart';

import 'package:google_maps_directions/google_maps_directions.dart';

3. **获取当前位置**:

使用`Location`插件来获取用户的当前位置。

Location location = new Location();

bool _serviceEnabled;

PermissionStatus _permissionGranted;

LocationData _locationData;

_getLocation() async {

_serviceEnabled = await location.serviceEnabled();

if (!_serviceEnabled) {

_serviceEnabled = await location.requestService();

if (!_serviceEnabled) {

return;

}

}

_permissionGranted = await location.hasPermission();

if (_permissionGranted == PermissionStatus.denied) {

_permissionGranted = await location.requestPermission();

if (_permissionGranted != PermissionStatus.granted) {

return;

}

}

_locationData = await location.getLocation();

}

4. **显示地图**:

使用`GoogleMap`小部件来显示地图,并设置初始位置。

GoogleMap(

initialCameraPosition: CameraPosition(

target: LatLng(_locationData.latitude, _locationData.longitude),

zoom: 14.4746,

),

markers: {

Marker(

markerId: MarkerId('currentLocation'),

position: LatLng(_locationData.latitude, _locationData.longitude),

),

},

)

5. **绘制导航路线**:

使用`PolylinePoints`和`Directions`插件来获取导航路线并绘制在地图上。

void getDirections() async {

// 创建PolylinePoints对象

PolylinePoints polylinePoints = PolylinePoints();

// 获取起点和终点的坐标

LatLng origin = LatLng(_locationData.latitude, _locationData.longitude);

LatLng destination = LatLng(目标地点的纬度, 目标地点的经度);

// 获取方向

Directions directions = Directions();

var results = await directions.getDirections(origin, destination);

var route = results['routes'][0];

// 转换坐标点

List<LatLng> polylineCoordinates = [];

var points = polylinePoints.decodePolyline(route['overview_polyline']['points']);

for (var point in points) {

polylineCoordinates.add(LatLng(point.latitude, point.longitude));

}

// 添加到polyline的集合中

setState(() {

polylines.add(Polyline(

polylineId: PolylineId('route'),

color: Colors.blue,

points: polylineCoordinates,

width: 3,

));

});

}

6. **构建UI**:

根据需要构建用户界面,可能包括地图、当前位置标记、导航路线、起点和终点输入等。

注:上述代码仅提供了一个基本的实现框架,实际应用中可能需要更多的功能和错误处理。此外,由于Google Maps API可能需要API密钥,并可能涉及费用,因此请确保你有一个有效的API密钥,并根据Google Maps API的使用条款进行操作。

在开发过程中,建议查阅各个插件的官方文档以获取更详细的信息和指导。