2.6. Setup map. Controls

March 20, 2024 · View on GitHub

Theory

A quick way to design a map with functional elements.

There are two main methods for working with controls in NgwMap: addControl and createControl.

  • addControl - adds a control suitable for the current map adapter. For example, you can add third-party controls:

    import NgwMap from "@nextgis/ngw-leaflet";
    import "leaflet.polylinemeasure";
    
    NgwMap.create({
      target: "map",
      center: [13, 56],
      osm: true,
      zoom: 6,
    }).then((ngwMap) => {
      const measureControl = new L.Control.PolylineMeasure();
      ngwMap.addControl(measureControl, "top-right");
    });
    

    Or add controls created by the createControl method.

  • createControl - generates an object that will be the correct control for the current map adapter. This method takes two arguments. The first one should contain two callback functions onAdd and onRemove. The second contains additional parameters that affect the appearance, such as bar (adds a frame) and margin (adds an indentation).

    const control = ngwMap.createControl({
      onAdd() {
        return document.createElement("div");
      },
    });
    

    There are also two quick access methods createButtonControl and createToggleControl. The first one is to create action buttons (very frequent task) and the second is to add the on/off switch.

    const toggleControl = ngwMap.createToggleControl({
      getStatus: () => webMap.isLayerVisible("any-layer-id"),
      onClick: (status) => ngwMap.toggleLayer("webmap", status),
      html: {
        on: "ON",
        off: "OFF",
      },
      title: "Toggle layer visibility",
    });
    webMap.addControl(toggleControl, "top-right");
    

You can assign names to controls to be able to configure them on map initialization. This is convenient when working on extensions. There are only two built-in name controls: ZOOM and ATTRIBUTION.

NgwMap.create({
  controls: ["ZOOM", "ATTRIBUTION"],
  controlsOptions: {
    ZOOM: { position: "top-left" },
    ATTRIBUTION: {
      position: "bottom-right",
      customAttribution: [
        '<a href="https://nextgis.com" target="_blank">©NextGIS</a>',
      ],
    },
  }
});

You can place controls in the corners of the map:

top-left------------------tor-reght
|                                 |
|              MAP                |
|                                 |
bottom-left------------bottom-right

More examples

Practice

Check the code of the lesson and examples on code.nextgis.com to find more ways to create controls.

To run this example, you need to execute these commands in the terminal:

npm i
npm start

Open http://localhost:8080.

LAUNCH in the codesandbox.io.

BACK TO CONTENT