Skip to main content

Quickstart

Getting a map on screen is the same seven steps in every language:

  1. Initialize the wrapper for your language.
  2. Create the map device — the engine.
  3. Create a coordinate system.
  4. Create a layer — one source of map data.
  5. Create a terrain — the layers, grouped.
  6. Create a viewport on your window, canvas or GL surface.
  7. Position the camera and render.

The objects, their order, and their names are identical across surfaces. What differs is how you get a drawing surface, how errors reach you, and — on the web — that step 1 is asynchronous.

note

You need MapCore installed and a raster map to point at. See Install on Windows, Install on Linux or Install for the web first.

1. Initialize​

// Reference DNMapCoreTypes and DNPIMapCoreWrapper, then:
using UnmanagedWrapper; // DNMc* factories and IDNMc* interfaces
using MapCore; // DNS* structs and DNE* enums

The web surface is the one with a real constraint here: McStartMapCore() is asynchronous, and nothing in the MapCore namespace exists until it has resolved. Every other language can call MapCore on the line after the import.

Dropping the type annotations from any TypeScript example on this page leaves valid JavaScript; reach the namespace as window.MapCore if you are not using a bundler.

2. Create the map device​

DNSInitParams initParams = new DNSInitParams();
initParams.eLoggingLevel = DNELoggingLevel._ELL_HIGH;
// Required for WPF, optional for WinForms.
initParams.bMultiThreadedDevice = true;

IDNMcMapDevice device = DNMcMapDevice.Create(initParams);

Creates a rendering device, used to create map viewports.

The thread that creates the first device becomes MapCore's main (render) thread (until a viewport is created in another thread — see the interface description); PerformPendingCalculations() and most rendering must run on that thread thereafter.

The first created device initializes the MapCore engine with the specified initialization parameters (InitParams) — with a rendering system, or without one when SInitParams::eRenderingSystem is ERS_NONE; in the latter case viewports cannot be created and GPU-based queries cannot be performed, but other queries and calculations can. The parameters are ignored when creating following devices.

The device is created with a zero reference count: call IMcBase::AddRef() to keep it, and IMcBase::Release() when done; releasing the last device tears the engine down.

Parameters:

  • ppDevice — Receives the created device.
  • InitParams — Engine initialization parameters.

Returns:

  • IMcErrors::SUCCESS on success
  • IMcErrors::INVALID_PARAMETERS if ppDevice is NULL or SInitParams::fObjectsBatchGrowthRatio is not greater than 1
  • IMcErrors::CONFIGURATION_FILE_NOT_FOUND if plugins.cfg or resources.cfg is not found (first device only)
  • IMcErrors::RESOURCE_LOCATION_NOT_FOUND if the requested rendering system is not available or a resource location from resources.cfg cannot be added (first device only)

— from Map/IMcMapDevice.h

You keep the device until shutdown, so in C++ and on the web, own it with AddRef() and Release() it last, in step 8. C# and Java need nothing here: their wrappers take that reference when they create the managed object. See Threading and lifecycle.

From here on, the C++ snippets return on failure to stay short. An application releases what it already owns before returning — from this step on, at least the device.

Every field of the init params has a default; these are the ones worth setting deliberately.

eRenderingSystem picks the GPU back-end and defaults to ERS_AUTO_SELECT. On Windows that may resolve to Direct3D; pass ERS_OPEN_GL, ERS_OPEN_GLES or ERS_OPEN_GL_3PLUS to be explicit. ERS_NONE builds a device with no rendering system at all — no viewports, no GPU queries, everything else working — which is the setting for a server or batch tool.

On Android, strConfigFilesDirectory is not optional in practice: MapCore reads plugins.cfg, resources.cfg and fxplugin.cfg from it, and there is no useful default working directory.

warning

The thread you call this on becomes MapCore's main thread — and creating a viewport later moves it again. Create the device and all viewports on the same thread. On Android that means the GLSurfaceView renderer thread, so device creation belongs in onSurfaceCreated(), not in onCreate(). See Threading and lifecycle.

3. Create a coordinate system​

If you know the EPSG code of your data, that is the shortest route:

IDNMcGridCoordinateSystem coordSys = DNMcGridGeneric.Create("EPSG:3006");

There are dedicated interfaces for the common cases: IMcGridCoordSystemGeographic for plain latitude/longitude, IMcGridUTM for a UTM zone, IMcGridGeneric for anything addressable by SRID or by an initialization string.

note

IMcGridGeneric::Create() needs the PROJ_DATA folder to be reachable — either at its default location in the installation, or at a full path given in the MCPROJ_LIB environment variable. An EPSG code that fails to resolve on an otherwise working install is usually this, not a bad code.

4. Create a layer​

The simplest layer is a raster map already converted to MapCore's format, which needs nothing but its location — a directory, or a URL:

IDNMcNativeRasterMapLayer rasterLayer =
DNMcNativeRasterMapLayer.Create(@"C:\maps\Israel\Raster");

Two things about that call, in every language:

  • The layer is created with a zero reference count. Because it is about to be handed to a terrain that will own it, that is exactly right — pass it as is. See Threading and lifecycle.
  • Tile data loads asynchronously in either case: a successful return means the layer exists, not that it is drawable, and the map fills in as tiles arrive.

A URL layer is not ready when Create() returns​

Give the same call a URL instead of a directory and the difference is bigger than where the bytes come from: the layer's own initialization is deferred. Create() still returns IMcErrors::SUCCESS, but it returns a layer that is not ready — IsInitialized() is false, and completion arrives later on IMcMapLayer::IReadCallback::OnInitialized().

Until then the layer has no coordinate system and no bounding box. So a URL source makes the read callback mandatory rather than advisable, and it moves steps 5 to 7 into the callback's wake:

let initResult = null; // set once, by OnInitialized

const CLayerReadCallback = MapCore.IMcMapLayer.IReadCallback.extend(
'IMcMapLayer.IReadCallback', {
OnInitialized: (pLayer, eStatus, strAdditionalDataString) => {
initResult = { status: eStatus, message: strAdditionalDataString };
},
OnReadError: (pLayer, eErrorCode, strAdditionalDataString) => { /* mandatory */ },
OnNativeServerLayerNotValid: (pLayer, bUpdated) => { /* mandatory */ },
});
const readCallback = new CLayerReadCallback();

All three of those methods are mandatory, whether or not your layer can trigger them.

Asynchronous results are dispatched by Render() and by IMcMapDevice::PerformPendingCalculations(). There is no viewport to render yet, so pump the device until the callback has fired:

const waitForLayer = () => {
MapCore.IMcMapDevice.PerformPendingCalculations();
if (initResult === null) {
requestAnimationFrame(waitForLayer);
} else if (initResult.status === MapCore.IMcErrors.ECode.SUCCESS) {
buildTerrainAndViewport(); // steps 5 to 7
} else {
console.error(MapCore.IMcErrors.ErrorCodeToString(initResult.status));
}
};
requestAnimationFrame(waitForLayer);

This is not a web-only rule — a URL layer behaves this way in every language. It is simply unavoidable on the web, where a URL is the only kind of source there is.

note

In C++ and on the web, a layer held across that wait has no owner yet, so take a reference on it (AddRef()), pass it to the terrain afterwards, and then Release() your reference — the terrain owns the layer from there on. C# and Java need nothing here: their wrappers take that reference when they create the managed object, so holding the managed object is holding the layer. See Language surfaces.

5. Create a terrain​

IDNMcMapLayer[] layers = new IDNMcMapLayer[] { rasterLayer };
IDNMcMapTerrain terrain = DNMcMapTerrain.Create(coordSys, layers);

Passing null for the coordinate system instead makes the terrain adopt the coordinate system of its first layer that has one — often the better choice, because it cannot disagree with the data.

That only works once the layer is initialized, though. Do it with a layer that is still loading from a URL and there is nothing to adopt: the terrain is created with no coordinate system at all, GetCoordinateSystem() returns null, and the failure surfaces one step later as a viewport that cannot be created. Either wait for OnInitialized() first, or pass the coordinate system yourself.

6. Create a viewport​

This is the step that differs most between surfaces, because "where do I draw" has a different answer on each.

DNSCreateDataMV createData = new DNSCreateDataMV(DNEMapType._EMT_2D);
createData.pDevice = device;
createData.CoordinateSystem = coordSys; // note: no 'p' prefix on this one
createData.hWnd = mapPanel.Handle;

IDNMcMapViewport viewport = null;
IDNMcMapCamera camera = null;
DNMcMapViewport.Create(ref viewport, ref camera, createData,
new IDNMcMapTerrain[] { terrain });

What goes in hWnd:

SurfaceValue
C++ / C# (WinForms)A real window handle
C# (WPF)IntPtr.Zero, plus uWidth/uHeight — then hand GetRenderSurface() to a D3DImage back buffer
Java / Android-1 (MC_HWND_CURRENT_GL_CONTEXT) with bExternalGLControl = true, plus uWidth/uHeight
JavaScript / TypeScriptThe HTMLCanvasElement itself
Any, offscreenMC_HWND_NONE with uWidth/uHeight, to render into a buffer

With no window handle you must set uWidth and uHeight, or creation fails with IMcErrors::VIEWPORT_SIZE_MISSING. The viewport's coordinate system must match the terrain's, or you get IMcErrors::COORDINATE_SYSTEMS_MISMATCH; a terrain with no layers is refused with IMcErrors::VIEWPORT_CANT_HAVE_EMPTY_TERRAIN.

The camera argument is the viewport's default camera, and you can ignore it — pass NULL/null. IMcMapViewport inherits IMcMapCamera and forwards to the active camera, so every camera call below works on the viewport directly.

7. Position the camera and render​

viewport.SetCameraPosition(new DNSMcVector3D(x, y, 0));
viewport.SetCameraScale(10);

DNMcGarbageCollector.Collect(); // before every frame - see below
viewport.Render();

SetCameraScale() is in world units per display pixel — meters of ground per pixel for a metric coordinate system — not cartographic map scale. The conversion between the two is in Rendering and cameras.

Nothing draws unless you call Render(). There is no internal timer, so you own the loop: a timer at your target frame rate, CompositionTarget.Rendering in WPF, onDrawFrame() on Android, requestAnimationFrame() on the web. To redraw only when something changed, ask HasPendingUpdates() first — and then also call IMcMapDevice::PerformPendingCalculations() regularly, because with nothing rendering it is what lets asynchronous work finish. See Threading and lifecycle.

The first frames show an incomplete map while tiles load. To bring terrain in before showing anything, call PerformPendingUpdates() once after creating the viewport; it blocks, and that is the point.

Handle resize​

Tell MapCore when its surface changes size, or the map is drawn to stale dimensions:

private void MapPanel_Resize(object sender, EventArgs e)
{
if (viewport != null)
viewport.ViewportResized();
}

ViewportResized() takes a width and height only on Android, where MapCore cannot retrieve them from the window. On every other platform both must be left at their defaults — passing a size there returns IMcErrors::INVALID_PARAMETERS.

C# and Java: driving the collector​

Both managed wrappers bridge MapCore's reference counting to their runtime's garbage collector, and both expose the same two calls — DNMcGarbageCollector in C#, McGarbageCollector in Java:

  • Collect() releases the native objects behind managed objects the runtime has already collected.
  • DisposeAll() must be the last MapCore call on the thread that used MapCore — for a desktop application, the last line of Program.Main(). It disposes what is left while the right thread is still alive. Without it, finalizers run on the runtime's own threads and dispose MapCore objects off MapCore's main thread. Nothing calls this for you, in either language.

Collect() is where they differ, and only one surface needs it by hand:

SurfaceCollect()
C# via DNPIMapCoreWrapper (current)Call it yourself, immediately before each Render()
C# via DNMapCoreWrapper (legacy C++/CLI)Render() calls it for you
JavaRender() calls it for you

Calling it anyway is harmless, so the habit costs nothing — but on the two surfaces that collect for you, per-frame code that also calls it is doing the work twice.

8. Shut down​

Release in the reverse order of creation. There is less to release than there was to create, because the viewport owns its cameras and the terrain you passed it, and the terrain owns its layers:

viewport.Dispose();
device.Dispose();
DNMcGarbageCollector.DisposeAll(); // last line of Program.Main()

Do not release the camera — the viewport owns it, and DestroyCamera() is how you remove one you created yourself. Do not release the layer or the terrain either: once passed on, they are owned by the terrain and the viewport.

Next steps​

Verified against MapCore 12.5.0

Written from Map/IMcMapDevice.h, Map/IMcMapViewport.h, Map/IMcMapTerrain.h, Map/IMcRasterMapLayer.h, Map/McMapManagement.h, Map/IMcMapCamera.h, Map/IMcMapLayer.h, Calculations/IMcGridCoordinateSystem.h, IMcErrors.h