I'm currently using GoogleMap in Flutter. I also use the clustering_google_maps package to display clusters of markers. The default behavior of this plugin is that every camera movement triggers an update of all the markers and clusters. This behavior takes into account the user zoom in/out and translation.
I added a feature where the camera moves according to the user's location whith the location package.
initPlatformState() async {
// Wait for the Completer to complete and return the GoogleMap Controler
mapController = await _controller.future;
// Set controller for the ClusteringHelper
clusteringHelper.mapController = mapController;
// Get database and update markers
clusteringHelper.database = await DBHelper().database;
clusteringHelper.updateMap();
// Set parameters for location Service
await _locationService.changeSettings(
accuracy: LocationAccuracy.HIGH, interval: 1000);
try {
bool serviceStatus = await _locationService.serviceEnabled();
print("Service status: $serviceStatus");
if (serviceStatus) {
_permission = await _locationService.requestPermission();
print("Permission: $_permission");
// If permission granted, get current location and subscribe to updates
if (_permission) {
LocationData location = await _locationService.getLocation();
final myLocationMarkerId = MarkerId("myLocationMarker");
myLocationMarker = Marker(
markerId: myLocationMarkerId,
position: LatLng(location.latitude, location.longitude),
icon: BitmapDescriptor.defaultMarker,
infoWindow: InfoWindow(
title: "My Location",
snippet: "Latitude: " +
location.latitude.toString() +
" Longitude: " +
location.longitude.toString()),
);
_locationSubscription = _locationService
.onLocationChanged()
.listen((LocationData result) async {
if (cameraUpdateToMyLocation) {
_currentCameraPosition = CameraPosition(
target: LatLng(result.latitude, result.longitude), zoom: 16);
// Safety check if mapController not null
if (mapController != null) {
mapController.animateCamera(
CameraUpdate.newCameraPosition(_currentCameraPosition));
}
}
if (mounted) {
setState(() {
_currentLocation = result;
myLocationMarker = myLocationMarker.copyWith(
positionParam: LatLng(
_currentLocation.latitude, _currentLocation.longitude),
infoWindowParam: InfoWindow(
title: "My Location",
snippet: "Latitude: " +
location.latitude.toString() +
" Longitude: " +
location.longitude.toString())
);
});
}
});
}
} else {
bool serviceStatusResult = await _locationService.requestService();
print("Service status activated after request: $serviceStatusResult");
if (serviceStatusResult) {
initPlatformState();
}
}
} on PlatformException catch (e) {
print(e);
if (e.code == 'PERMISSION_DENIED') {
error = e.message;
} else if (e.code == 'SERVICE_STATUS_ERROR') {
error = e.message;
}
}
}
I would like that this location update stops when the user moves the maps on the screen.
Unfortunately, the callback onCameraMove is triggered when the user move the map AND when the camera animation is launched.
Is it possible to trigger the inCameraMove callback, only when the user move the map ?
Thx !
EDIT It appears that onCameraMove is called in loop when I drag the map with my finger...
It's not possible to differentiate the onCameraMove callback as far as I know. What are you trying to accomplish here? Can you change the plugin to display the clusters onCameraIdle callback? Would this solve your problem?
unfortunately, the google maps flutter does not support this feature for now. you can handle it by wrapping a map in the listener and control a boolean that shows what kind of action makes the camera move. for example, I want to find out if the camera moves by click on the markers (calling on tap callback of marker moves the camera) or the user manually drags the map. every time the user touches the map I change the "dragsTheScreen" boolean to true, and in on tap function of markers I change it to false which shows the camera movement is because of markers. so you can do it for any feature you want. for example, you want to find out if the camera movement is because of calling your own Special function or the user dragging: listener changes the boolean("dragsTheScreen") to true, and that function setState it to false.
Listener(
onPointerDown: (PointerDownEvent event){
setState(() {
dragsTheScreen=false;
});
},
child: GoogleMap(
markers: markerItemsForShow.toSet(),
mapType: MapType.normal,
onMapCreated: onMapCreated,
onCameraMove: onCameraMove,
onCameraIdle: onCameraIdle,
initialCameraPosition:CameraPosition(tilt:25,target:LatLng(32.71,51.66), zoom: 5),
),
),
and in markers on tap callback when I am create them:
markerItemsForShow.add(Marker(
markerId:...,
position:...,
onTap: (){
setState(() {
dragsTheScreen=true;
});
}
));
Related
I need to get google maps autocomplete suggestion when I type a word on input.
maps.svelte
function inputChange() {
onMount(() => {
loader
.load()
.then((google) => {
const map = new google.maps.Map(document.getElementById('map'), mapOptions);
const markerPickUp = new google.maps.Marker({
position: {
lat: 14.6012,
lng: 120.975
},
map: map
});
const displaySuggestions = function (predictions, status) {
if (status != google.maps.places.PlacesServiceStatus.OK || !predictions) {
predictionsArray = [];
return;
}
predictionsArray = predictions;
console.log(predictionsArray);
};
const service = new google.maps.places.AutocompleteService();
const sessionToken = new google.maps.places.AutocompleteSessionToken();
service.getPlacePredictions(
{ input: $bookDetails.dropOffLocation, sessionToken: sessionToken },
displaySuggestions
);
})
.catch((e) => {
console.log(e);
});
});
}
$: $bookDetails.dropOffLocation, inputChange();
I tried to log $bookDetails.dropOffLocation after inputChange() just to see if it's bind on the input and it is. Also, the code works well without the onMount() but it's giving me errors on my terminal. It says windows not defined and it has to do with google maps. I think it needs to load the dom first that's why it gives error. I'm using #googlemaps/js-api-loader.
onMount registers a callback that executes when the component is mounted. It is not intended to be called multiple times and only ever will invoke the callback once during the lifecycle of a component.
If you just want to make sure that the component is already mounted when executing some logic, you can set a flag and use that as a guard. E.g.
let mounted = false;
onMount(() => mounted = true);
$: {
$bookDetails.dropOffLocation;
if (mounted) inputChange();
}
I'm trying to build an app that loads a GoogleMap(), then after getting the user latitude and longitude moves to the that specific location.
I came up with this idea (code below), but it works only if I restart the app and if I don't it gives error: animateCamera was called on null.
How is it possible ? and how can i fix it ?
Thanks for answering :D
...
var mapController;
...
GoogleMap createMap() {
var initMap = GoogleMap(
onMapCreated: onMapCreated,
initialCameraPosition:
CameraPosition(target: LatLng(47.290542, 8.322641), zoom: 6.7),
);
return initMap;
}
...
void onMapCreated(controller) {
mapController = controller;
}
...
void moveCameraToUserLocation(searchedLocation2) async {
var location = await Geocode().getLatLng(searchedLocation2);
print("moving to: $location");
mapController.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
target: location,
zoom: 20,
),
),
);
...
build(context) {
return Scaffold(
body: createMap(),
...
Based on how you describe the problem, it looks like you are only calling the animate function as the map loads.
I suggest that you create a button that would handle and trigger the animate function and move the camera to the device location whenever tapped.
The following code snippet uses a ClipOval button and inside the OnTap() event you can call the method to get the device current location which will be triggered whenever the button is tapped.
ClipOval(
child: Material(
color: Colors.green[100], // button color
child: InkWell(
splashColor: Colors.green, // inkwell color
child: SizedBox(
width: 56,
height: 56,
child: Icon(Icons.my_location),
),
onTap: () {
// Add methods here that will be called whenever the button is tapped
mapController.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(
target: LatLng(_currentPosition.latitude, _currentPosition.longitude),
zoom: 17.0)));
setState(() {
allMarkers.add(Marker(
markerId: MarkerId('Current Position'),
draggable: false,
position:
LatLng(_currentPosition.latitude, _currentPosition.longitude)));
});
},
),
),
)
Probably you are calling moveCameraToUserLocation function before map is created. From this part of the code I cannot se when you call thi function but my guess is that you call it from initstate. If you want to call this function immediately after widget is created move it to onMapCreated.
void onMapCreated(controller) {
mapController = controller;
moveCameraToUserLocation();
}
I have a SearchMapPlaceWidget that suggests me places based on my search keyword. I want to animate the camera to the suggested place I tap on. How do I do that?
Here's the SearchMapPlaceWidget that I used from search_map_place package in Flutter.
SearchMapPlaceWidget(
apiKey: myApiKey,
onSearch: (Place place) async {
try{
final geolocation = await place.geolocation;
print(geolocation);
}catch(e){
print(e);
}
},
),
From official example https://pub.dev/packages/search_map_place#example
You can use GoogleMapController and call animateCamera
return SearchMapPlaceWidget(
apiKey: YOUR_API_KEY,
// The language of the autocompletion
language: 'en',
// The position used to give better recomendations. In this case we are using the user position
location: userPosition.coordinates,
radius: 30000,
onSelected: (Place place) async {
final geolocation = await place.geolocation;
// Will animate the GoogleMap camera, taking us to the selected position with an appropriate zoom
final GoogleMapController controller = await _mapController.future;
controller.animateCamera(CameraUpdate.newLatLng(geolocation.coordinates));
controller.animateCamera(CameraUpdate.newLatLngBounds(geolocation.bounds, 0));
},
);
From Official example have all the code you need
Screen with map and search box on top. When the user selects a place through autocompletion,the screen is moved to the selected location
https://github.com/Bernardi23/search_map_place/blob/master/example/advanced_example.dart
You can directly run this example
It's too long, I just paste _mapController part
Completer<GoogleMapController> _mapController = Completer();
...
GoogleMap(
...
onMapCreated: (GoogleMapController controller) async {
_mapController.complete(controller);
...
final GoogleMapController controller = await _mapController.future;
So am using the google map marker in flutter, but it not working, instead it showing "Undefined name 'mapController'.
Try correcting the name to one that is defined, or defining the name"
Here is my code:
void _onMapCreated(GoogleMapController controller){
setState(() {
mapController = controller;
});
}
}
_addMarker() {
var marker = MarkerOptions(
position: mapController.cameraPosition.target,
icon: BitmapDescriptor.defaultMarker,
infoWindowText: InfoWindowText('Magic Marker', '🍄🍄🍄')
);
mapController.addMarker(marker);
}
These are the dependencies used:
geoflutterfire: "^2.0.2"
location: "^1.4.1"
google_maps_flutter: "^0.2.0"
What am I doing wrong?
Using Google Maps for Flutter I've placed some markers on different places on the map. I have a separate RaisedButton on my Flutter app which I need to only be visible when one or more of those markers are currently visible on the map.
How can this be achieved? I've found a somewhat similar solution for Google Maps API but I need this for google_maps_flutter on Flutter.
LatLngBounds has specific method known as contains() which works along with GoogleMapController's getVisibleRegion().
From the official docs:
contains(LatLng point) → bool
Returns whether this rectangle contains the given LatLng.
Usage:
Completer<GoogleMapController> _controller = Completer();
static final CameraPosition _positionCenter = CameraPosition(
target: LatLng(40.730610, -73.935242),
zoom: 3.5,
);
Future<LatLngBounds> _getVisibleRegion() async {
final GoogleMapController controller = await _controller.future;
final LatLngBounds bounds = await controller.getVisibleRegion();
return bounds;
}
#override
Widget build(BuildContext context) {
void checkMarkers() async {
LatLngBounds bounds = await _getVisibleRegion();
Set<Marker> markers = Set<Marker>.of(markers.values);
markers.forEach((marker) {
print('Position: ${ marker.position } - Contains: ${ bounds.contains(marker.position) }');
});
}
return GoogleMap(
mapType: MapType.normal,
markers: Set<Marker>.of(markers.values),
initialCameraPosition: _positionCenter,
onCameraIdle: () {
checkMarkers();
},
onMapCreated: (GoogleMapController controller) async {
_controller.complete(controller);
checkMarkers();
},
);
}
google_maps_flutter is a developer preview at version 0.0.3. Please hang in there a bit until more functionality is introduced.