Flutter地图服务插件mapmyindia_gl的使用

发布于 1周前 作者 htzhanglong 来自 Flutter

Flutter MapmyIndia GL

This Flutter plugin allows you to show embedded interactive MapmyIndia maps inside a Flutter widget. This guide will help you integrate and use the mapmyindia_gl plugin in your Flutter application.

Getting Started

To work with MapmyIndia Map in Flutter, add this to your package’s pubspec.yaml file:

dependencies:
  mapmyindia_gl: ^0.3.2

Now, in your Dart code, import this package:

import 'package:mapmyindia_gl/mapmyindia_gl.dart';

Adding MapmyIndia Keys

You must provide your keys through the MapmyIndiaAccountManager class:

MapmyIndiaAccountManager.setMapSDKKey(ACCESS_TOKEN); 
MapmyIndiaAccountManager.setRestAPIKey(REST_API_KEY); 
MapmyIndiaAccountManager.setAtlasClientId(ATLAS_CLIENT_ID); 
MapmyIndiaAccountManager.setAtlasClientSecret(ATLAS_CLIENT_SECRET);  

Add MapmyIndia Map to Your Application

Add the MapmyIndiaMap widget to your application:

MapmyIndiaMap(
  initialCameraPosition: CameraPosition(
    target: LatLng(25.321684, 82.987289),
    zoom: 14.0,
  ),
  onMapCreated: (map) => {
    mapController = map,
  },
)

Map Interactions

Zoom Controls

The map supports pinch and double-tap gestures for zooming. You can programmatically adjust the camera using the following methods:

mapController.moveCamera(CameraUpdate.newLatLngZoom(LatLng(22.553147478403194, 77.23388671875), 14));
mapController.easeCamera(CameraUpdate.newLatLngZoom(LatLng(28.704268, 77.103045), 14));
mapController.animateCamera(CameraUpdate.newLatLngZoom(LatLng(28.698791, 77.121243), 14));

Map Events

Map Click/Long Click

Set callbacks for map click and long-click events:

MapmyIndiaMap(
  initialCameraPosition: _kInitialPosition,
  onMapClick: (point, latlng) => {
    print(latlng.toString())
  },
  onMapLongClick: (point, latlng) => {
    print(latlng.toString())
  },
)

Map Overlays

Add a Marker

Add a marker on the map:

Symbol symbol = await controller.addSymbol(SymbolOptions(geometry: LatLng(25.321684, 82.987289)));

Customize a Marker

Customize a marker with an asset image:

Future<void> addImageFromAsset(String name, String assetName) async {
  final ByteData bytes = await rootBundle.load(assetName);
  final Uint8List list = bytes.buffer.asUint8List();
  return controller.addImage(name, list);
}

await addImageFromAsset("icon", "assets/symbols/custom-icon.png");
Symbol symbol = await controller.addSymbol(SymbolOptions(geometry: LatLng(25.321684, 82.987289), iconImage: "icon"));

Remove a Marker

Remove a marker from the map:

controller.removeSymbol(symbol);

Add a Polyline

Draw a polyline on the map:

Line line = await controller.addLine(LineOptions(geometry: latlng, lineColor: "#3bb2d0", lineWidth: 4));

Remove a Polyline

Remove a polyline from the map:

controller.removeLine(line);

Add a Polygon

Draw a polygon on the map:

Fill fill = await controller.addFill(FillOptions(geometry: latlng, fillColor: "#3bb2d0")); 

Remove a Polygon

Remove a polygon from the map:

controller.removeFill(fill);

Show User Location

Show the user’s current location on the map:

MapmyIndiaMap(
  initialCameraPosition: _kInitialPosition,
  myLocationEnabled: true,
  myLocationTrackingMode: MyLocationTrackingMode.NONE_COMPASS,
  onUserLocationUpdated: (location) => {
      print("Position: ${location.position.toString()}, Speed: ${location.speed}, Altitude: ${location.altitude}")  
  },
)

Complete Example Demo

Below is a complete example demonstrating how to set up and use the mapmyindia_gl plugin in a Flutter application:

import 'package:flutter/material.dart';
import 'package:mapmyindia_gl/mapmyindia_gl.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  static const String ACCESS_TOKEN = "YOUR_ACCESS_TOKEN";
  static const String REST_API_KEY = "YOUR_REST_API_KEY";
  static const String ATLAS_CLIENT_ID = "YOUR_ATLAS_CLIENT_ID";
  static const String ATLAS_CLIENT_SECRET = "YOUR_ATLAS_CLIENT_SECRET";

  @override
  Widget build(BuildContext context) {
    // Set MapmyIndia keys
    MapmyIndiaAccountManager.setMapSDKKey(ACCESS_TOKEN);
    MapmyIndiaAccountManager.setRestAPIKey(REST_API_KEY);
    MapmyIndiaAccountManager.setAtlasClientId(ATLAS_CLIENT_ID);
    MapmyIndiaAccountManager.setAtlasClientSecret(ATLAS_CLIENT_SECRET);

    return MaterialApp(
      home: MapScreen(),
    );
  }
}

class MapScreen extends StatefulWidget {
  @override
  _MapScreenState createState() => _MapScreenState();
}

class _MapScreenState extends State<MapScreen> {
  late MapmyIndiaMapController mapController;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('MapmyIndia Map')),
      body: MapmyIndiaMap(
        initialCameraPosition: CameraPosition(
          target: LatLng(25.321684, 82.987289),
          zoom: 14.0,
        ),
        onMapCreated: (controller) {
          mapController = controller;
        },
        onMapClick: (point, latlng) {
          print("Tapped at $latlng");
        },
        onMapLongClick: (point, latlng) {
          print("Long pressed at $latlng");
        },
        myLocationEnabled: true,
        myLocationTrackingMode: MyLocationTrackingMode.TRACK_USER,
        onUserLocationUpdated: (location) {
          print("User Location: ${location.position}");
        },
      ),
    );
  }
}

Replace YOUR_ACCESS_TOKEN, YOUR_REST_API_KEY, YOUR_ATLAS_CLIENT_ID, and YOUR_ATLAS_CLIENT_SECRET with your actual MapmyIndia credentials.

For further support or questions, visit MapmyIndia Support.


更多关于Flutter地图服务插件mapmyindia_gl的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter地图服务插件mapmyindia_gl的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter应用中使用mapmyindia_gl插件来实现地图服务的示例代码。这个插件是MapmyIndia提供的用于在Flutter应用中集成其地图服务的官方插件。

首先,确保你已经在pubspec.yaml文件中添加了mapmyindia_gl依赖:

dependencies:
  flutter:
    sdk: flutter
  mapmyindia_gl: ^最新版本号  # 请替换为实际的最新版本号

然后,运行flutter pub get来获取依赖。

接下来,在你的Flutter项目中,你可以按照以下步骤来集成MapmyIndia地图服务:

  1. 初始化MapmyIndia SDK

    在你的main.dart文件或任何合适的入口文件中,初始化MapmyIndia SDK并配置API密钥(你需要从MapmyIndia获取一个有效的API密钥)。

import 'package:flutter/material.dart';
import 'package:mapmyindia_gl/mapmyindia_gl.dart';

void main() {
  // 初始化MapmyIndia SDK
  MapmyIndiaGl.initialize(
    apiKey: '你的MapmyIndia API密钥', // 替换为你的API密钥
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MapScreen(),
    );
  }
}
  1. 创建地图屏幕

    创建一个新的Dart文件(例如map_screen.dart),并在其中实现地图的显示。

import 'package:flutter/material.dart';
import 'package:mapmyindia_gl/mapmyindia_gl.dart';

class MapScreen extends StatefulWidget {
  @override
  _MapScreenState createState() => _MapScreenState();
}

class _MapScreenState extends State<MapScreen> {
  late MapmyIndiaMapController _mapController;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('MapmyIndia Map Example'),
      ),
      body: MapmyIndiaMap(
        onMapCreated: (MapmyIndiaMapController controller) {
          _mapController = controller;

          // 设置初始相机位置
          _mapController.moveCamera(
            CameraUpdate.newLatLngZoom(
              LatLng(纬度, 经度), // 替换为你的初始位置坐标
              15.0, // 缩放级别
            ),
          );
        },
        options: MapOptions(
          style: MapStyle.NORMAL,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // 示例:在地图上添加一个标记
          _mapController.addMarker(
            MarkerOptions(
              position: LatLng(纬度, 经度), // 替换为你想添加标记的位置坐标
              infoWindow: InfoWindow(
                title: '示例标记',
                snippet: '这是一个示例标记',
              ),
            ),
          );
        },
        tooltip: '添加标记',
        child: Icon(Icons.add),
      ),
    );
  }
}

在上述代码中:

  • MapmyIndiaMap是用于显示地图的Widget。
  • onMapCreated回调在地图创建完成后被调用,你可以在这里获取MapmyIndiaMapController实例来控制地图。
  • moveCamera方法用于设置地图的初始视图。
  • addMarker方法用于在地图上添加标记。
  1. 运行你的应用

    确保你已经正确配置了所有必要的API密钥和依赖项,然后运行你的Flutter应用。你应该能够看到一个显示MapmyIndia地图的屏幕,并且可以通过点击浮动操作按钮在地图上添加标记。

请注意,以上代码仅作为示例,实际使用时你需要根据自己的需求调整坐标、样式等参数。同时,确保你遵守MapmyIndia的使用条款和隐私政策。

回到顶部