#flutter #google-cloud-firestore #geolocation #geofirestore
#флаттер #google-cloud-firestore #геолокация #geofirestore
Вопрос:
Я хочу получить текущее местоположение пользователя на картах Google по обнаруженному телефонному устройству. Я объявлял свою позицию как геопункт в своем классе модели, чтобы получить карту координат из Google maps. поэтому я был в замешательстве, либо мне нужно объявить свою позицию как геопункт, либо тип строки.
Моей модельной задачей.
class Task {
final String noAduan;
final String sumberAduan;
final String kategori;
List<String> imageUrls = <String>[];
final DateTime dateTime;
final String verified;
final String email;
final String uid;
final String id;
final String address;
final GeoPoint position;
Task({this.address, this.position, this.id, this.noAduan, this.sumberAduan, this.kategori, this.imageUrls, this.dateTime, this.verified, this.email, this.uid});
Task.fromData(Map<String, dynamic> data)
: noAduan = data['noAduan'],
kategori = data['kategori'],
sumberAduan = data['sumberAduan'],
dateTime = data['date'],
verified = data['verified'],
email = data['email'],
uid = data['uid'],
imageUrls = data['urls'],
id = data['id'],
address = data['address'],
position = data['position'];
Map<String,dynamic> toJson(){
return{
'noAduan' : noAduan,
'kategori' : kategori,
'sumberAduan' : sumberAduan,
'date' : dateTime,
'verified': verified,
'email': email,
'uid': uid,
'url':imageUrls,
'id':id,
'address': address,
'position': position,
};
}
}
Класс службы базы данных
Future updateLocation(GeoFirePoint point, String address) async {
return addTaskCollection.document(id).updateData({
'position': point.data,
'address': address,
}).whenComplete(() {
print("Update success!");
});
}
класс Google maps
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fyp/model/Task.dart';
import 'package:fyp/service/database.dart';
import 'package:geoflutterfire/geoflutterfire.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
import 'package:geocoder/geocoder.dart' as geoCo;
class GoogleMaps extends StatefulWidget {
@override
_GoogleMapsState createState() => _GoogleMapsState();
}
class _GoogleMapsState extends State<GoogleMaps> {
StreamSubscription _streamSubscription;
GoogleMapController googleMapController;
Location _locationTracker = new Location();
Marker marker;
Circle circle;
String addressLocation;
Task task;
static final CameraPosition initialLocation = CameraPosition(
target: LatLng(4.2105, 101.9758),
zoom: 15.00,
);
void updateMarker(LocationData newLocalData ) {
LatLng latLng = LatLng(newLocalData.latitude, newLocalData.longitude);
this.setState(() {
marker = Marker(
markerId: MarkerId("Im here"),
position: latLng,
draggable: false,
icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueCyan),);
});
}
void getCurrentLocation() async {
try {
var location = await _locationTracker.getLocation();
final coordinated = new geoCo.Coordinates(location.latitude, location.longitude);
GeoFirePoint point = GeoFirePoint(location.latitude, location.longitude);
var address = await geoCo.Geocoder.local.findAddressesFromCoordinates(coordinated);
var firstAddress = address.first;
addressLocation = firstAddress.addressLine;
task = Task(
address: addressLocation,
position: point.data //in this line show the error//
);
await DatabaseService().updateLocation(point, addressLocation);
if (_streamSubscription != null) {
_streamSubscription.cancel();
}
_streamSubscription = _locationTracker.onLocationChanged.listen((newLocalData) {
if (googleMapController != null) {
googleMapController.animateCamera(
CameraUpdate.newCameraPosition(new CameraPosition(
bearing: 192.83,
target: LatLng(newLocalData.latitude, newLocalData.longitude),
tilt: 0,
zoom: 10.00)));
updateMarker(newLocalData);
}
});
} on PlatformException catch (e) {
if(e.code == 'PERMISSION_DENIED') {
debugPrint("Permission Denied");
}
}
}
@override
void dispose(){
if (_streamSubscription != null){
_streamSubscription.cancel();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Google Maps"),
backgroundColor: Colors.redAccent,
),
body: GoogleMap(
mapType: MapType.normal,
initialCameraPosition: initialLocation,
markers: Set.of((marker!= null) ? [marker] : []),
circles: Set.of((circle != null) ? [circle] : []),
onMapCreated: (GoogleMapController controller){
googleMapController = controller;
},
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.location_searching),
onPressed: (){
getCurrentLocation(); //this one also show the error//
},
),
);
}
}
Я получил исключение, подобное этому:
Unhandled Exception: type '_InternalLinkedHashMap<String, Object>' is not a subtype of type 'GeoPoint'
E/flutter (10865): #0 _GoogleMapsState.getCurrentLocation (package:fyp/maps/google_maps_address.dart:51:27)
E/flutter (10865): <asynchronous suspension>
E/flutter (10865): #1 _GoogleMapsState.build.<anonymous closure> (package:fyp/maps/google_maps_address.dart:102:11)
Есть ли что-нибудь, чего мне не хватает, или я допускаю ошибку при инициализации geofire? кто-нибудь, помогите мне, пожалуйста?