如何在颤振中使用 json API 在谷歌地图中添加标记?

Posted

技术标签:

【中文标题】如何在颤振中使用 json API 在谷歌地图中添加标记?【英文标题】:How to add marker in the google map using json API in flutter? 【发布时间】:2021-07-13 04:07:01 【问题描述】:

我正在尝试使用 http 请求基于 json API (EventData) 向我的地图添加标记。当我运行我的代码时,地图不显示标记。我想我没有正确访问列表。我只想使用这些参数:来自EventDataGPSPoint_latGPSPoint_lonAddress。有人可以帮我吗?

这是我的 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

我的代码:

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(),
              ),


          ),

    );



  

错误:

【问题讨论】:

【参考方案1】:

代码中有几处可能需要更改。

var superheros_length; 具有误导性,我起初以为它是一个整数,但根据您的 getData() 函数,它是一个映射。因此,首先将其更改为:
List<Map<String, dynamic>> super_heros_length;
我会将onMapCreated 函数更改为如下所示:
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']
              )
          )
      );    
    );
    
  

要访问lat,根据你的json,你必须像这样使用它:

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

但是由于您已经在访问 ["DeviceList"] 并将其分配给 superheroes_length,因此您不必重复自己,并使用此处发布的代码并更新发生的情况。还要发布您收到的错误。每次在 for 循环中迭代时,您还清除了您的标记,这样,如果您有多个标记,则只会显示最后一个标记,因为每次添加新标记时,您都会清除它之前的所有内容,这个这就是为什么我把它放在循环之外。

【讨论】:

不客气,法蒂玛。快乐编码! :)

以上是关于如何在颤振中使用 json API 在谷歌地图中添加标记?的主要内容,如果未能解决你的问题,请参考以下文章

用户如何在谷歌地图颤振上添加多个标记

如何使用坐标数组在谷歌地图 API 中绘制多边形?

无法在谷歌地图中添加多个标记(颤振)

如何在谷歌地图api中创建多个信息窗口

如何在谷歌地图 ios sdk 中显示多条折线

如何使用 api 在谷歌地图中仅显示一个国家或特定区域?