在Flutter中实现高德地图仿微信选址功能,可以通过高德地图Flutter插件(amap_flutter_map)结合自定义UI组件实现。以下是核心实现步骤和代码示例:
1. 环境配置
pubspec.yaml 添加依赖:
dependencies:
amap_flutter_map: ^x.x.x # 使用最新版本
provider: ^6.0.0 # 状态管理
Android配置:
AndroidManifest.xml 添加权限和API Key:
<application>
<meta-data
android:name="com.amap.api.v2.apikey"
android:value="您的高德地图Key"/>
</application>
2. 核心实现代码
class LocationPicker extends StatefulWidget {
@override
_LocationPickerState createState() => _LocationPickerState();
}
class _LocationPickerState extends State<LocationPicker> {
final AmapController _mapController = AmapController();
LatLng _center = LatLng(39.909187, 116.397451); // 初始位置(北京)
String _address = "";
// 地图移动完成回调
void _onMapMoveEnd(LatLng position) async {
setState(() => _center = position);
// 逆地理编码获取地址
List<ReGeocodeResult> results = await _mapController.getReGeocode(
position.latitude,
position.longitude,
);
if (results.isNotEmpty) {
setState(() => _address = results.first.formatAddress ?? "");
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
// 地图层
Amap(
onMapCreated: (controller) => _mapController = controller,
onCameraMoveEnd: (position) => _onMapMoveEnd(position.target),
),
// 微信样式定位图标
Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.location_pin, size: 40, color: Colors.red),
Container(height: 40) // 留出底部空间
],
),
),
// 底部地址卡片
Align(
alignment: Alignment.bottomCenter,
child: Card(
margin: EdgeInsets.all(16),
child: Padding(
padding: EdgeInsets.all(16),
child: Row(
children: [
Icon(Icons.location_on),
SizedBox(width: 10),
Expanded(child: Text(_address.isEmpty ? "获取中..." : _address)),
TextButton(
onPressed: () => Navigator.pop(context, _address),
child: Text("确认位置"),
)
],
),
),
),
)
],
),
);
}
}
3. 关键功能说明
- 地图控制:通过
AmapController实现地图交互和逆地理编码
- 实时定位:监听
onCameraMoveEnd事件获取中心坐标
- 地址解析:使用
getReGeocode将经纬度转换为具体地址
- UI布局:Stack叠加地图、定位图标和地址卡片
4. 扩展建议
- 添加搜索框:结合
amap_flutter_search插件实现地点搜索
- 增加定位按钮:调用
_mapController.moveCamera()返回当前位置
- 使用Provider管理状态,实现跨组件数据共享
注意事项
- 需要申请高德地图Key并配置到项目中
- iOS需在
Info.plist中配置NSLocationWhenInUseUsageDescription
- 建议对逆地理编码请求做防抖处理,避免频繁调用API
通过以上实现,即可在Flutter中完成类似微信的高德地图选址功能,支持拖动地图选点并实时显示地址信息。