Reputation: 95
I need to create some Marker in my app, I get the latitude and longitude by API. How can I will show these markers?
My getPosts code:
Future<List<Orders>> getPosts() async {
Response response = await http.get(url);
//print(response.body);
if(response.statusCode == 200){
List<dynamic> body = jsonDecode(response.body);
List<Orders> orders = body.map((dynamic item) => Orders.fromJson(item)).toList();
return orders;
} else {
throw "Can't get orders";
}
My class Order:
class Orders {
final String id;
final String nameRestaurant;
final String address;
final String lat;
final String long;
final bool delivered;
final String orderId;
final String phone;
Orders({@required this.id, @required this.nameRestaurant, @required this.address, @required this.lat,
@required this.long, @required this.delivered, @required this.orderId, @required this.phone});
factory Orders.fromJson(Map<dynamic, dynamic> json){
return Orders(
id: json['id'] as String,
nameRestaurant: json['nameRestaurant'] as String,
address: json['address'] as String,
lat: json['lat'] as String,
long: json['long'] as String,
delivered: json['delivered'] as bool,
orderId: json['orderId'] as String,
phone: json['phone'] as String
);
}
}
I followed some tutorials but all of them add marker in onTap function but it don't works to me
Upvotes: 6
Views: 14472
Reputation: 160
First of all create a map of markers as follows:
Map<MarkerId, Marker> markers = <MarkerId, Marker>{MarkerId('marker_id_1'):Marker(
markerId: MarkerId('marker_id_1'),
position: LatLng(30.0444, 31.235),
infoWindow: InfoWindow(title: 'marker_id_1', snippet: '*'),
onTap: () {
//_onMarkerTapped(markerId);
print('Marker Tapped');
},
onDragEnd: (LatLng position) {
print('Drag Ended');
}, )};
Then add googleMap anywhere you want as follows
GoogleMap(
mapType: MapType.normal,
//initialCameraPosition: cairo,
markers: Set<Marker>.of(markers.values),
//onMapCreated: (GoogleMapController controller) {
// _controller.complete(controller);
//},
)
Upvotes: 2
Reputation: 2757
To add a list of simple markers, first create a list of markers:
List<Marker> _markers = <Marker>[];
Then add Marker to this list:
_markers.add(
Marker(
markerId: MarkerId('SomeId'),
position: LatLng(38.123,35.123),
infoWindow: InfoWindow(
title: 'The title of the marker'
)
)
);
Consider that in infoWindow
you can also add subtitle and other stuff.
Finally add the google map widget:
GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(38.9647,35.2233),
zoom: 9.0,
),
mapType: MapType.normal,
markers: Set<Marker>.of(_markers),
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
)
Upvotes: 20