102 lines
3.3 KiB
Dart
102 lines
3.3 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:google_maps_flutter/google_maps_flutter.dart';
|
|
import 'package:geolocator/geolocator.dart';
|
|
import 'package:flutter_hooks/flutter_hooks.dart';
|
|
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
|
|
|
class TestMapX extends HookConsumerWidget {
|
|
@override
|
|
Widget build(BuildContext context, WidgetRef ref) {
|
|
final mapController = useState<GoogleMapController?>(null);
|
|
final currentPosition = useState<LatLng?>(null);
|
|
final isLocationSet = useState<bool>(false);
|
|
final customIcon = useState<BitmapDescriptor>(BitmapDescriptor.defaultMarker);
|
|
|
|
final center = const LatLng(-7.566957, 110.8080284);
|
|
|
|
useEffect(() {
|
|
Future<void> _loadCustomMarker() async {
|
|
final icon = await BitmapDescriptor.asset(
|
|
const ImageConfiguration(size: Size(100, 100)),
|
|
'images/custom_marker1.png',
|
|
);
|
|
customIcon.value = icon;
|
|
}
|
|
|
|
_loadCustomMarker();
|
|
return null;
|
|
}, []);
|
|
|
|
Future<void> _getCurrentLocation() async {
|
|
try {
|
|
bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
|
|
if (!serviceEnabled) return;
|
|
|
|
LocationPermission permission = await Geolocator.checkPermission();
|
|
if (permission == LocationPermission.denied) {
|
|
permission = await Geolocator.requestPermission();
|
|
if (permission == LocationPermission.deniedForever ||
|
|
permission == LocationPermission.denied) {
|
|
return;
|
|
}
|
|
}
|
|
|
|
Position position = await Geolocator.getCurrentPosition(
|
|
desiredAccuracy: LocationAccuracy.high,
|
|
);
|
|
|
|
currentPosition.value = LatLng(position.latitude, position.longitude);
|
|
isLocationSet.value = true;
|
|
|
|
if (mapController.value != null) {
|
|
mapController.value!.animateCamera(
|
|
CameraUpdate.newLatLng(currentPosition.value!),
|
|
);
|
|
}
|
|
} catch (e) {
|
|
print('Error: $e');
|
|
}
|
|
}
|
|
|
|
return Scaffold(
|
|
appBar: AppBar(
|
|
title: Text('Google Maps Flutter Web'),
|
|
backgroundColor: Colors.green[700],
|
|
),
|
|
body: Stack(
|
|
children: <Widget>[
|
|
GoogleMap(
|
|
onMapCreated: (controller) => mapController.value = controller,
|
|
initialCameraPosition: CameraPosition(
|
|
target: center,
|
|
zoom: 11.0,
|
|
),
|
|
markers: isLocationSet.value && currentPosition.value != null
|
|
? {
|
|
Marker(
|
|
markerId: MarkerId('current_location'),
|
|
position: currentPosition.value!,
|
|
icon: customIcon.value,
|
|
infoWindow: InfoWindow(
|
|
title: 'Posisi : ${currentPosition.value!.latitude}, ${currentPosition.value!.longitude}',
|
|
snippet:
|
|
'${currentPosition.value!.latitude}, ${currentPosition.value!.longitude}',
|
|
),
|
|
),
|
|
}
|
|
: {},
|
|
),
|
|
Positioned(
|
|
bottom: 20,
|
|
left: 20,
|
|
child: ElevatedButton(
|
|
onPressed: _getCurrentLocation,
|
|
child: Text('Current Location'),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
}
|