web_mercator 0.9.4+1

  • Readme
  • Changelog
  • Example
  • Installing
  • 66

web_mercator #

Dart implementation of the uber @math.gl/web-mercator javascript module.

Getting Started #

See the tests for in-depth implementation methods. Here is a basic example using the fitBounds factory with end user device informations:

import 'package:web_mercator/web_mercator.dart' show MercatorViewport

final viewport = MercatorViewport.fitBounds(width: deviceWidth, height: deviceHeight, bounds: northEastSoutWest);

With that viewport, you can now project coordinates passing a Vector to the project method. Using a Vector2 will result in a flat projection (onto a sphere) while a Vector3 will consider the z component as an altidude expressed in meters.

The example/ folder contains a sample app displaying the boudary of Martinique with interactive pitch, bearing & zoom touch interactions.

[0.9.0] - 2020/01/26 #

  • Initial release covering most of the relevant bits.

[0.9.1-dev.1] - 2020/01/26 #

  • Improving publishing score.

[0.9.1] - 2020/01/26 #

  • Passing relevant attributes of package scoring.

[0.9.2] - 2020/01/30 #

  • Add a bbox function to facilitate projection from a list of coordinates.

[0.9.3] - 2020/02/11 #

  • Change the name of Viewport to MercatorViewport so it doesn't clash with the flutter's Viewport class.
  • Strongly typing some variables as suggested by dart linter.
  • Add an example.

[0.9.4] - 2020/03/20 #

  • Add a convenient copyWith factory to clone a viewport with parameters typically reflecting user interactions.
  • Update the example accordingly…

[0.9.4+1] - 2020/06/02 #

  • Cosmetic changes tackling analysis updates.

example/lib/main.dart

import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:vector_math/vector_math_64.dart';
import 'package:web_mercator/web_mercator.dart' show MercatorViewport, bbox;

const bearingDragFactor = .25;
const pitchDragFactor = .5;
const scaleDrageFactor = .5;

void main() => runApp(MyApp());

num mapRange(num value, num minIn, num maxIn, num minOut, num maxOut) {
  return (value - minIn) / (minIn - maxIn) * (maxOut - minIn) + minIn;
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hello Mercator',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _scaling = false;
  double _pitch = .0, _bearing = .0, _zoom = .0;
  Offset _lastFocalPoint;
  MercatorViewport _viewport;
  Future<Map<String, List>> _martinique;

  @override
  void initState() {
    _martinique = _parsePolygons(context, 'json/martinique_poly.json');
    super.initState();
  }

  Future<Map<String, List>> _parsePolygons(BuildContext context, String file) async {
    final data = await DefaultAssetBundle.of(context).loadString(file);
    final dynamic map = await json.decode(data);

    List<List<Vector2>> polygons = [];
    List<List<double>> points = [];

    for (final polygon in map['geometries'][0]['coordinates']) {
      polygons.add([]);
      for (final p in polygon[0]) // don't mind holes
      {
        polygons.last.add(Vector2(p[0], p[1]));
        points.add([p[0], p[1]]);
      }
    }

    return {'polygons': polygons, 'bounds': bbox(points)};
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onScaleStart: (scale) {
        _lastFocalPoint = scale.focalPoint;
        _zoom = _viewport.zoom;
        _scaling = true;
      },
      onScaleEnd: (scale) {
        _scaling = false;
      },
      onScaleUpdate: (scale) {
        if (_scaling && _viewport != null) {
          final focalPoint = scale.focalPoint;
          if (_lastFocalPoint == null) {
            _lastFocalPoint = focalPoint;
            return;
          }

          final size = MediaQuery.of(context).size;
          final deltaOffset = focalPoint - _lastFocalPoint;

          _pitch -= deltaOffset.dy * pitchDragFactor;
          if (focalPoint.dy > size.height * .5) {
            _bearing += deltaOffset.dx * bearingDragFactor;
          } else {
            _bearing -= deltaOffset.dx * bearingDragFactor;
          }

          double zoom = _zoom * scale.scale;
          zoom = max(7, min(zoom, 15));

          setState(() {
            _viewport = MercatorViewport.copyWith(
              _viewport,
              pitch: _pitch,
              bearing: _bearing,
              zoom: zoom,
            );
          });

          _lastFocalPoint = focalPoint;
        }
      },
      child: FutureBuilder<Map<String, List>>(
        future: _martinique,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            final size = MediaQuery.of(context).size;
            if (_viewport == null) {
              _viewport = MercatorViewport.fitBounds(
                width: size.width,
                height: size.height,
                bounds: snapshot.data['bounds'],
                padding: 20,
              );
            }

            return CustomPaint(
              painter: PolygonPainter(_viewport, snapshot.data['polygons']),
            );
          } else {
            return Center(child: CircularProgressIndicator());
          }
        },
      ),
    );
  }
}

class PolygonPainter extends CustomPainter {
  final MercatorViewport viewport;
  final List<List<Vector2>> polygons;

  PolygonPainter(this.viewport, this.polygons);

  void _paintPolygon(Canvas canvas, List<Vector2> polygon) {
    for (int i = 0; i < polygon.length - 1; i++) {
      final projFrom = viewport.project(polygon[i]) as Vector2;
      final projTo = viewport.project(polygon[i + 1]) as Vector2;

      canvas.drawLine(
          Offset(projFrom[0], projFrom[1]),
          Offset(projTo[0], projTo[1]),
          Paint()
            ..color = Color.fromARGB(255, 255, 255, 255)
            ..style = PaintingStyle.stroke);
    }
  }

  @override
  void paint(Canvas canvas, Size size) {
    if (viewport == null || polygons == null || polygons.isEmpty) {
      return;
    }

    for (final polygon in polygons) {
      _paintPolygon(canvas, polygon);
    }
  }

  @override
  bool shouldRepaint(PolygonPainter oldDelegate) => true; // oldDelegate.viewport.pitch != viewport.pitch;
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  web_mercator: ^0.9.4+1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:web_mercator/web_mercator.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
33
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
66
Learn more about scoring.

We analyzed this package on Jul 7, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.13
  • Flutter: 1.17.5

Analysis suggestions

Package not compatible with SDK dart

because of import path [web_mercator] that is in a package requiring null.

Health suggestions

Format lib/geo_utils.dart.

Run flutter format to format lib/geo_utils.dart.

Format lib/mercator_viewport.dart.

Run flutter format to format lib/mercator_viewport.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
meta >=1.1.1 <2.0.0 1.1.8 1.2.1
vector_math ^2.0.8 2.0.8
Transitive dependencies
collection 1.14.12 1.14.13
sky_engine 0.0.99
typed_data 1.1.6 1.2.0
Dev dependencies
flutter_test
pedantic ^1.0.0