Adding a marker to the map

A Marker identifies a location on a Map. We'll use markers to show our user their current position, and we'll also add the saved places' markers to our map. Let's look at the steps:

  1.  Create a List of markers at the top of the _MainMapState class, like this:
List<Marker> markers = [];
  1. Then, we'll add a generic method that will add a Marker to the markers list. It will take a Position, a String containing the identifier of the Marker, and another String for the title.
    The way to show information about the Marker itself to the user is the infoWindow parameter. In particular, this takes a title that contains a text that will appear whenever the user taps on the Marker itself.
  1. A Marker uses a default image, but it's also possible to choose custom images for a Marker. We'll use the default icon for this app, but we'll change the color for the marker of the current position. The default color for a Marker is red. In our app, if the MarkerId is currpos, we'll choose an azure color to help the user identify their position. For the other markers, we'll choose an orange color.
  2. Once the marker is added, we'll call the setState method to update the screen.
    Here is the code for the steps described previously—add it at the bottom of the _MainMapState class, like this:
void addMarker(Position pos, String markerId, String markerTitle ) {
final marker = Marker(
markerId: MarkerId(markerId),
position: LatLng(pos.latitude, pos.longitude),
infoWindow: InfoWindow(title: markerTitle),
icon: (markerId=='currpos') ?
BitmapDescriptor.defaultMarkerWithHue
(BitmapDescriptor.hueAzure):BitmapDescriptor
.defaultMarkerWithHue(BitmapDescriptor
.hueOrange)
);
markers.add(marker);
setState(() {
markers = markers;
});
}
  1. Now, we need to call this method after the current position has been found. So, we'll override the initState method, and, inside it, we'll call the _getCurrentLocation() method. After the result is retrieved, we'll call the addMarker method to actually show the marker on the map. In case of an error, we'll just print the error in the debug console. All of this is achieved by running the following code:
@override
void initState() {
_getCurrentLocation().then((pos){
addMarker(pos, 'currpos', 'You are here!');
}).catchError(
(err)=> print(err.toString()));
super.initState();
}
  1. The last detail for this part is adding the markers to the map. In the build() method, when we call the GoogleMap constructor, we'll add the markers as shown in the following code block:
child: GoogleMap(
initialCameraPosition: position,
markers: Set<Marker>.of(markers),

If you try the app right now, you should see your current position, as shown in the following screenshot:

Now, let's give our users the power to save their favorite places and show them on our map!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.40.32