[英]Google Maps for Flutter - Get new position of marker after dragging
我想使用Google Google Maps for Flutter及其標記在Flutter中創建位置選擇器。 通過創建可拖動選項設置為true的標記,可以創建可拖動標記。 使用以下代碼段。
Widget _buildMap(BuildContext context) {
return GoogleMap(
options: GoogleMapOptions(
cameraPosition: CameraPosition(
target: LatLng(7.2906, 80.6337),
zoom: 7.0,
),
compassEnabled: true,
),
onMapCreated: (controller) {
_mapController = controller;
controller.addMarker(
MarkerOptions(
draggable: true,
flat: false,
position: LatLng(7.2906, 80.6337),
),
);
},
);
}
但是在拖動標記后,我找不到找到標記的新位置的方法。 我試圖通過引用MapController
markers
屬性來獲取標記的新位置,但是它返回了標記的初始位置。
_mapController.markers.forEach((marker) {
print("Pos: " + marker.options.position.toString())
});
// Prints "Pos: LatLng[7.2906, 80.63369999999998]"
我在這里做錯了什么,還是有另一種方法來完成此用例? 謝謝。
我解決此問題的方法是使用相機位置移動標記,然后使用當前相機位置獲取新坐標。 您需要重構一些代碼,以使用Google Maps 0.4版中出現的最新變化來撲朔迷離,其中包括您需要添加到代碼中的該回調:
onCameraMove: ((_position) => _updateMarker(_position)),
然后,您可以在用戶每次移動攝像機時設置標記的新狀態,並將此坐標用於您需要的任何其他目的:
void _updatePosition(CameraPosition _position) {
Position newMarkerPosition = Position(
latitude: _position.target.latitude,
longitude: _position.target.longitude);
Marker marker = markers["your_marker"];
setState(() {
markers["your_marker"] = marker.copyWith(
positionParam: LatLng(newMarkerPosition.latitude, newMarkerPosition.longitude));
});
}
告訴我是否可行!
該軟件包是開發人員預覽的版本0.0.3。 直到達到1.0,才考慮將其用於生產工作。 同時,您可能會提出問題,以將特定的優先事項告知顫振團隊。
我通過添加偵聽器和一些條件來解決此問題
mapController.addListener(() async {
final cameraCoordinates = mapController.cameraPosition.target;
if (!mapController.isCameraMoving &&
widget.selectedPlace.options.position !=
mapController.cameraPosition.target) {
mapController.updateMarker(
widget.selectedPlace, MarkerOptions(position: cameraCoordinates));
}
});
這里的mapController是GoogleMapController實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.