我在flutter中制作了一个简单的应用程序,从API中获取标记并在谷歌地图上绘制。
我用位置名称制作了一个模型,我从API获得了标记信息,并将它们添加到标记列表中。
但当我运行我的应用程序时,地图上并没有显示任何标记。
我该如何解决这个问题?
从API获取标记的我的函数:
Future<List<Location>> getLocations() async {
try {
var url = 'http://10.0.2.2/Track_App/locations.php';
final resp = await http.get(url);
final responsebody = jsonDecode(resp.body);
return responsebody; //this return a list
} catch (e) {
return [];
}
}
List<Marker> allMarkers = [];
loadLocations() async {
List<Location> locations;
locations = [];
locations = await getLocations(); //we store the response in a list
for (var i = 0; i < locations.length; i++) {
LatLng latlng;
latlng = LatLng(
double.parse(locations[i].locX),
double.parse(locations[i].locY),
);
allMarkers.add(
Marker(
markerId: MarkerId(locations[i].locId.toString()),
position: latlng,
),
);
}
setState(() {});
}
谷歌地图代码:
FutureBuilder(
future: loadLocations(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
return GoogleMap(
mapType: MapType.normal,
initialCameraPosition: _kGooglePlex,
markers: snapshot.data,
);
},
),
API的JSON数据:
[
{
loc_id: "1 ",
loc_x: "15.392567",
loc_y: "44.278188"
},
{
loc_id: "2 ",
loc_x: "15.391717",
loc_y: "44.278019"
}
]
我的型号:
class Location {
Location({
this.locId,
this.locX,
this.locY,
this.locInfo,
this.locSpd,
this.locDate,
});
String locId;
String locX;
String locY;
String locInfo;
String locSpd;
String locDate;
factory Location.fromJson(Map<String, dynamic> json) => Location(
locId: json['loc_id'],
locX: json['loc_x'],
locY: json['loc_y'],
locInfo: json['loc_info'],
locSpd: json['loc_spd'],
locDate: json['loc_date'],
);
Map<String, dynamic> toJson() => {
'loc_id': locId,
'loc_x': locX,
'loc_y': locY,
'loc_info': locInfo,
'loc_spd': locSpd,
'loc_date': locDate,
};
}
Map<MarkerId, Marker> markers = <MarkerId, Marker>{};
每当你想在这里添加制造商时,创建一个新的标记并添加到状态
Marker marker = Marker(...)
setState(() {
markers[markerId] = marker;
});
你的构建功能就像这个
child: GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: const CameraPosition(
target: LatLng(-33.852, 151.211),
zoom: 11.0,
),
markers: Set<Marker>.of(markers.values),
),
此代码对我有效,只需更改您的位置列表
Future<Offre> location_client() async{
var _loc = await _location.getLocation();
setState(() {
client_lat = _loc.client.lat;
client_lng = _loc.client.lng;
print("test test"+_loc.client.lat.toString()+','+_loc.client.lng.toString());
LatLng latlng = LatLng(client_lat,client_lng);
setState(() {
_markers.add(Marker(
markerId: const MarkerId("home"),
position: latlng,
draggable: false,
zIndex: 2,
flat: true,
anchor: const Offset(0.5, 0.5),
icon: BitmapDescriptor.defaultMarker));
});
});
}