如何在 Flutter 中使用地理编码从地址获取坐标? [已关闭]

问题描述 投票:0回答:2

有人可以教我如何在 flutter 中使用地理编码获取给定地址的经度和纬度吗?

我想获取坐标以将它们用作地图上的标记。

更新:这是我的代码:

类 _PlaceInfoState 扩展状态 {

  late double _latitude;
  late double _longitude;

  @override
  void initState(){
    getLatLon();
    super.initState();
  }

  Future <void> getLatLon() async {
    GeoCode geoCode = GeoCode();

    try {
      Coordinates coordinates = await geoCode.forwardGeocoding(address: "${widget.packageModel.destination}");
      final lat = coordinates.latitude!;
      final lon = coordinates.longitude!;

      setState((){
        _latitude = lat;
        _longitude = lon;
      });

    } catch (e) {
      print(e);
    }
  }

这是我尝试将显示坐标放在地图上的地方,但它似乎没有显示地图,它说_纬度尚未初始化:

//Location
Container(
  padding: EdgeInsets.only(top: 20),
  height: MediaQuery.of(context).size.height / 2.5,
  width: MediaQuery.of(context).size.width,
  child: GoogleMap(
    scrollGesturesEnabled: true,
    mapType: MapType.normal,
    initialCameraPosition: CameraPosition(
      target: LatLng(_latitude, _longitude),
      zoom: 14
    )
  ),
),
flutter dart geocoding
2个回答
0
投票

来自文档的示例:

import 'package:geocode/geocode.dart';

void main() async {
  GeoCode geoCode = GeoCode();

  try {
    Coordinates coordinates = await geoCode.forwardGeocoding(
        address: "532 S Olive St, Los Angeles, CA 90013");

    print("Latitude: ${coordinates.latitude}");
    print("Longitude: ${coordinates.longitude}");
  } catch (e) {
    print(e);
  }
}

-2
投票

geocode/geocode.dart 包需要公司提供的 api 密钥

© www.soinside.com 2019 - 2024. All rights reserved.