How to add marker in the google map using json API in flutter?

Viewed 694

I'm trying to add marker to my map based on the json API (EventData) by using http request. When I run my code the map does not show the marker. I think I am not accessing the list correctly. I want just to use these parameters: GPSPoint_lat , GPSPoint_lon and Address from EventData. can someone help me?

This is my json :

    {
   "Account": "",
   "Account_desc": "",
   "TimeZone": "GMT+00:00",
   "DeviceList": [
      {
         "Device": "v19",
         "Device_desc": "541266 DACIA NOIR",
         "VehicleID": "",
         "State": "62467",
         "LastNotifyText": "",
         "LastTimestamp": "1618683994",
         "LastGPSTimestamp": 1618700203,
         "Icon": "",
         "DeviceCode": "tk12x",
         "lastEngineHours": 4.5025,
         "FuelLevel": 0.0,
         "FuelTotal": "0.0 %",
         "simPhoneNumber": "0607250761",
         "EventData": [
            {
               "Device": "v19",
               "Timestamp": 1618700203,
               "Timestamp_date": "2021/04/17",
               "Timestamp_time": "22:56:43",
               "StatusCode": 62467,
               "StatusCode_hex": "0xF403",
               "StatusCode_desc": "Moteur OFF",
               "GPSPoint": "35.74512,-5.85550",
               "GPSPoint_lat": 35.74512,
               "GPSPoint_lon": -5.85550,
               "Speed_kph": 0.0,
               "Speed": 0.0,
               "Speed_units": "Km/H",
               "Heading": 0.0,
               "Heading_desc": "N",
               "Altitude_meters": 0.0,
               "Altitude": 0,
               "Altitude_units": "meters",
               "Odometer_km": 22438.364,
               "Odometer": 22438.364,
               "Odometer_units": "Distance en Kilomètre",
               "Geozone": "",
               "Geozone_index": 0,
               "Address": "Tanger, 90045, Maroc",
               "City": "Tanger",
               "PostalCode": "90045",
               "DigitalInputMask": 62467,
               "DriverID": "",
               "EngineHours": 4.50,
               "acceleration": 0.00,
               "brakeGForce": 0.00,
               "EngineCoolantTemperature_C": 0.0,
               "EngineCoolantTemperature": 32.0,
               "EngineCoolantTemperature_units": "F",
               "ThermoAverage_C": 0.0,
               "ThermoAverage": 32.0,
               "ThermoAverage_units": "F",
               "EngineFuelUsed_Liter": 0.0,
               "EngineFuelUsed": 0.0,
               "EngineFuelUsed_units": "Litre",
               "Index": 0
            }
]
      }
],
      "consomFuelL": 0.0,
      "consomFuelPr": "0.0 %",
      "debug": "",
      "maxspeed": 0.0,
      "KM": 22129.80960258997,
      "KMtotal": 22129.80960258997,
      "minStop": 0,
      "minOn": 0,
      "minMarche": 0,
      "Costfuel": 0.0
}

My code :

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:http/http.dart' as http;
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Maps (title: 'Flutter Demo Home Page'),
    );
  }
}

class Maps extends StatefulWidget {
  @override
  _MapsPageState createState() => _MapsPageState();
}

class _MapsPageState extends State<Maps> {
  String data;
  var superheros_length;
  String ValRet;
 int index;


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
   // setCustomMarker();
    getData();
  }



  Set<Marker> _markers = {};
//worked
  void _onMapCreated(GoogleMapController controller) async{
    final googleOffices = await getData();
    setState(() {
      for (final dnn in googleOffices.jsonDecode(data)['DeviceList']) {
      _markers.clear();
      _markers.add(
          Marker(markerId: MarkerId(dnn.jsonDecode(data)['DeviceList']['Device']),
              position: LatLng(35.77561, -5.80351),
              // icon: mapMarker,
              infoWindow: InfoWindow(
                  title: dnn.jsonDecode(data)['DeviceList']['Device'],
                  snippet: dnn.jsonDecode(data)['DeviceList'][index]['address']
              )
          )
      );
    }
    });
  }


  getData() async {
    const googleLocationsURL = 'myAPIPrivate';

    // Retrieve the locations of Google offices
    final response = await http.get(googleLocationsURL);
    if (response.statusCode == 200) {
      data =response.body;
      superheros_length= jsonDecode(data)['DeviceList'];
      print (superheros_length.length);
    } else {
      throw HttpException(
          'Unexpected status code ${response.statusCode}:'
              ' ${response.reasonPhrase}',
          uri: Uri.parse(googleLocationsURL));
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: Text('Maps Sample App'),
            leading: IconButton(
              icon: Icon(Icons.arrow_back, color: Colors.white),
              onPressed: () => Navigator.of(context).pop(),
            ),
            // backgroundColor: Colors.green[700],
          ),
          body:
              GoogleMap(

                // mapType: _currentMapType,
                onMapCreated: _onMapCreated,
                markers: _markers,
                initialCameraPosition: CameraPosition(
                 target: const  LatLng(35.77561,-5.80351),
                 // target: _center,
                 // target: const  LatLng(0,0),
                  zoom: 11.0,
                ),
                // markers: _markers.values.toSet(),
              ),


          ),

    );

}

}  

error: enter image description here

1 Answers

There are a few things that should probably be changed in the code.

  • var superheros_length; is misleading, I thought it was an integer at first, but based on your getData() function, it's a map. So, first off change it to:
List<Map<String, dynamic>> super_heros_length;
  • I would change the onMapCreated function to be something like this:
void _onMapCreated(GoogleMapController controller) async{
    await getData();
    _markers.clear();
    
      for (final dnn in super_heros_length) {
    
    setState(() {
      
      _markers.add(
          Marker(markerId: MarkerId(dnn['Device']),
              position: LatLng(dnn["EventData"][0]["GPSPoint_lat"], dnn["EventData"][0]["GPSPoint_lon"]),
              // icon: mapMarker,
              infoWindow: InfoWindow(
                  title: dnn['Device'],
                  snippet: dnn["EventData"][0]['address']
              )
          )
      );    
    });
    }
  }

To access the lat, based on your json, you have to use it like this:

["DeviceList"][0]["EventData"][0]["GPSPoint_lat"]

But since you are already accessing ["DeviceList"] and assigning it to superheroes_length, you don't have to repeat yourself, and use the code posted here, and update on what happens. Also post what errors you are recieving. You were also clearing your markees for every time you iterate in your for-loop, this way, if you had multiple markers, only the last marker will show, because every time you add a new marker, you were clearing everything before it, this is why I put it outside the loop.

Related