Oto-obong Eshiett
Oto-obong Eshiett

Reputation: 1669

How to make marker in flutter google map move with camera and not with map

i watched a video in which the location marker moved with the camera and was not stuck to the map. I am not sure if this is the official google map for flutter, but if it is how was this achieved.

i tried passing the controllers camera position to the marker, but it didnt work, as i am not sure the markers position got updated with the camera movement.

 mapController.addMarker(MarkerOptions(
      icon: BitmapDescriptor.fromAsset("assets/images/marker.png"),
      position: LatLng(mapController.cameraPosition.target.latitude,mapController.cameraPosition.target.longitude),
      infoWindowText: InfoWindowText("Pick up location", "Pick up location")
    ));

Upvotes: 2

Views: 10456

Answers (3)

Ahmad Bilal
Ahmad Bilal

Reputation: 61

You can do that by creating a new marker every time the camera moves but providing the same marker id. It won't, actually, create a new marker but it will start moving the same marker according to the camera position. Here's how you can do it:

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class YourMapView extends StatefulWidget {
  @override
  _YourMapViewState createState() => _YourMapViewState();
}

class _YourMapViewState extends State<YourMapView> {
  final markers = Set<Marker>();
  MarkerId markerId = MarkerId("YOUR-MARKER-ID");
  LatLng latLng = LatLng(43.2994, 74.2179);

  @override
  void initState() {
    markers.add(
      Marker(
        markerId: markerId,
        position: latLng,
      ),
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GoogleMap(
      initialCameraPosition: CameraPosition(target: latLng,zoom: 14.34),
      markers: markers,
      onCameraMove: (position){
        setState(() {
          markers.add(Marker(markerId: markerId,position: position.target));
        });
      },
    );
  }
}

Upvotes: 6

Ricardo Chen He
Ricardo Chen He

Reputation: 326

If you want the marker just for visual purposes, you can place a "fake" marker on top of the map that is always centered and get the camera position to get the actual camera coordinates.

the other way is to update the marker onCameraMove, the marker will not perfeclty be at the center everytime and it will jerk.

Upvotes: 1

BIS Tech
BIS Tech

Reputation: 19424

you can do it using these properties.

onCameraMove: ,
onCameraIdle: ,
onCameraMoveStarted: 

,

Upvotes: 2

Related Questions