You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter版Google Maps中显示加油站?求代码或实现思路

实现Flutter加油站地图展示方案

核心思路

  • 选用google_maps_flutter官方插件作为地图基础,支持原生Google Maps的所有核心功能
  • 自定义加油站标记图标,替换默认红色大头针,还原目标视觉风格
  • 通过位置API(或自有后端接口)获取加油站的经纬度、名称、油价等数据
  • 实现标记点击交互,弹出加油站详情信息
  • 大量加油站场景下,用标记集群插件优化界面拥挤问题

代码实现示例

1. 添加依赖

在pubspec.yaml中添加所需依赖:

dependencies:
  flutter:
    sdk: flutter
  google_maps_flutter: ^2.5.0
  geolocator: ^10.1.0

2. 主页面代码

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';

class GasStationMap extends StatefulWidget {
  const GasStationMap({super.key});

  @override
  State<GasStationMap> createState() => _GasStationMapState();
}

class _GasStationMapState extends State<GasStationMap> {
  late GoogleMapController _mapController;
  final Set<Marker> _markers = {};
  BitmapDescriptor? _gasStationIcon;

  // 模拟加油站数据,实际项目替换为API请求结果
  final List<Map<String, dynamic>> _gasStations = [
    {
      'id': '1',
      'name': 'XX加油站',
      'lat': 39.9042,
      'lng': 116.4074,
      'price': '7.5元/L',
      'distance': '0.8km'
    },
    {
      'id': '2',
      'name': 'YY加油站',
      'lat': 39.9151,
      'lng': 116.4039,
      'price': '7.3元/L',
      'distance': '1.2km'
    },
  ];

  @override
  void initState() {
    super.initState();
    _loadCustomMarker();
    _getCurrentLocation();
  }

  // 加载自定义加油站标记图标
  Future<void> _loadCustomMarker() async {
    _gasStationIcon = await BitmapDescriptor.fromAssetImage(
      const ImageConfiguration(size: Size(40, 40)),
      'assets/gas_station_icon.png', // 替换为你的图标路径
    );
    setState(() {});
  }

  // 获取当前位置并移动地图视角
  Future<void> _getCurrentLocation() async {
    bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      // 提示用户开启定位服务
      return;
    }

    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        return;
      }
    }

    Position position = await Geolocator.getCurrentPosition();
    _mapController.moveCamera(
      CameraUpdate.newLatLngZoom(
        LatLng(position.latitude, position.longitude),
        14.0,
      ),
    );
    _addGasStationMarkers();
  }

  // 添加所有加油站标记
  void _addGasStationMarkers() {
    if (_gasStationIcon == null) return;

    _markers.clear();
    for (var station in _gasStations) {
      final marker = Marker(
        markerId: MarkerId(station['id']),
        position: LatLng(station['lat'], station['lng']),
        icon: _gasStationIcon!,
        infoWindow: InfoWindow(
          title: station['name'],
          snippet: '${station['price']} | ${station['distance']}',
        ),
        onTap: () {
          // 自定义点击后的弹窗,展示详细信息
          showDialog(
            context: context,
            builder: (ctx) => AlertDialog(
              title: Text(station['name']),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('油价:${station['price']}'),
                  Text('距离:${station['distance']}'),
                  const SizedBox(height: 10),
                  const Text('地址:北京市东城区XX街道'),
                ],
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(ctx),
                  child: const Text('关闭'),
                ),
              ],
            ),
          );
        },
      );
      _markers.add(marker);
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('附近加油站')),
      body: GoogleMap(
        onMapCreated: (controller) => _mapController = controller,
        initialCameraPosition: const CameraPosition(
          target: LatLng(39.9042, 116.4074), // 默认北京坐标
          zoom: 12.0,
        ),
        markers: _markers,
        myLocationEnabled: true,
        myLocationButtonEnabled: true,
      ),
    );
  }
}

额外优化建议

  • 标记集群:如果加油站数量超过50个,使用flutter_map_marker_cluster插件将近距离标记合并,提升地图加载性能和可读性
  • 实时数据:对接第三方POI搜索接口,获取实时的加油站位置、油价信息
  • 路线规划:集成地图导航SDK,实现从当前位置到选中加油站的路线规划

内容的提问来源于stack exchange,提问作者AXP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 08:57:34