Add Map Items

The HERE SDK allows you to add several types of items to the map, such as map polylines and markers. They are explained in detail in the sections below. Currently, the following map items are supported:

  • Map polylines: Non-moveable rendered lines.
  • Map arrows: A convenient way to show arrow indicators on the map.
  • Map polygons: Non-moveable rendered shapes.
  • Map circles: Non-moveable rendered circles that can be defined as geo polygons.
  • Map markers: Images that can be pinned to 'mark' specific spots on the map.
  • Map marker clustering: A group of map markers that can be clustered dependent on zoom level.
  • Embedded POIs: Pickable preconfigured and embedded POI objects (carto POIs) on the map such as public transit stations, restaurants, ATMs and other facilities.
  • Map markers 3D: 3D shapes rendered on the map at the specified geographic coordinates.
  • Flat map markers: Flat map markers that rotates and tilt together with the map.
  • Location indicator Predefined assets to indicate the current device location on the map.
  • Map view pins: A convenient way to show native iOS UIView layouts on the map.

Polylines, polygons and circles, will adjust their size based on the current zoom level, while markers and pins remain unchanged when zooming.

All map items provide a convenient way to pick them from the map.

Add Map Polylines

Polylines can be useful to render, for example, a route geometry on the map. They can be created as shown below:

private func createMapPolyline() -> MapPolyline {
    let coordinates = [GeoCoordinates(latitude: 52.53032, longitude: 13.37409),
                       GeoCoordinates(latitude: 52.5309, longitude: 13.3946),
                       GeoCoordinates(latitude: 52.53894, longitude: 13.39194),
                       GeoCoordinates(latitude: 52.54014, longitude: 13.37958)]

    // We are sure that the number of vertices is greater than two, so it will not crash.
    let geoPolyline = try! GeoPolyline(vertices: coordinates)
    let lineColor = UIColor(red: 0, green: 0.56, blue: 0.54, alpha: 0.63)
    let mapPolyline = MapPolyline(geometry: geoPolyline,
                                  widthInPixels: 30,
                                  color: lineColor)
    return mapPolyline
}

A MapPolyline consists of three elements:

  • A list of two or more geographic coordinates that define where to place the polyline on the map.
  • A GeoPolyline that contains this list of coordinates.
  • Style parameters such as DashPattern or LineCap to define how to visualize the polyline.

Since a geometric line is defined by two or more points, you need to create an array, which must contain at least two GeoCoordinates. Otherwise, an exception will be thrown. To change the look of the line, its thickness in pixels and color can be set. See for an example the screenshot.

After you have created one or more map polylines, you can add them to a map scene with:

mapScene = mapView.mapScene

mapPolyline = createMapPolyline()
mapScene.addMapPolyline(mapPolyline!)

If a map polyline instance is already attached to a map scene, any further attempt to add it again will be ignored.

Screenshot: Showing a polyline.

Note, a map view allows only one scene and all map items are placed directly on it. If you want to group your map items, you may want to organize them by using an array and add or remove them individually.

You can remove a mapPolyline from the map immediately by calling:

mapScene.removeMapPolyline(line)

Note: MapPolyline items are pickable and it is possible to store the Metadata that can be retrieved when picking the item. For an example, see the section below on map markers.

By setting a list of MapMeasureRange items, the visibility for a MapPolyline can be adjusted dependent on the current zoom level.

Note: By setting a draw order, you can specify what item is rendered on top of each other. Note that as of now, setting a draw order is not having an affect in relation to other map items as it only defines the order within the same type of class.

Note that map polylines can be also rendered dashed. Use MapPolyline.DashImageRepresentation to set a dashed pattern style.

Add Map Arrows

Map arrows behave similar to MapPolyline items, they consist of a polyline with an arbitrary number of points, but show an arrow tip at its end. Map arrows are only visible on zoom levels above 13. They can be useful do indicate directions on the map - for example, when rendered on parts of a route geometry.

private func createMapArrow() -> MapArrow {
    let coordinates = [GeoCoordinates(latitude: 52.53032, longitude: 13.37409),
                       GeoCoordinates(latitude: 52.5309, longitude: 13.3946),
                       GeoCoordinates(latitude: 52.53894, longitude: 13.39194),
                       GeoCoordinates(latitude: 52.54014, longitude: 13.37958)]

    // We are sure that the number of vertices is greater than two, so it will not crash.
    let geoPolyline = try! GeoPolyline(vertices: coordinates)
    let lineColor = UIColor(red: 0, green: 0.56, blue: 0.54, alpha: 0.63)
    let mapArrow = MapArrow(geometry: geoPolyline,
                            widthInPixels: 30,
                            color: lineColor)
    return mapArrow
}

A MapArrow consists of three elements:

  • A list of two or more geographic coordinates that define where to place the polyline on the map.
  • A GeoPolyline that contains this list of coordinates.
  • Style parameters such as color or widthInPixels to define how to visualize the arrow.

Since a geometric line is defined by two or more points, you need to create an array, which must contain at least two GeoCoordinates. Otherwise, an exception will be thrown. To change the look of the line, its thickness in pixels and color can be set. See for an example the screenshot.

After you have created one or more map arrows, you can add them to a map scene with:

mapScene = mapView.mapScene

mapArrow = createMapArrow()
mapScene.addMapArrow(mapArrow!)

If a map arrow instance is already attached to a map scene, any further attempt to add it again will be ignored.

Screenshot: Showing a map arrow.

Note, a map view allows only one scene and all map items are placed directly on it. If you want to group your map items, you may want to organize them by using an array and add or remove them individually.

You can remove a mapArrow from the map immediately by calling:

mapScene.removeMapArrow(arrow)

Note: MapArrow items are pickable and it is possible to store the Metadata that can be retrieved when picking the item. For an example, see the section below on map markers.

Add Map Polygons

A MapPolygon is a shape that consists of at least three coordinates, otherwise it cannot be rendered. Similar to MapPolyline, the coordinates are connected. Polygons can be useful to highlight an area on the map.

Note: The order of the coordinates do matter.

See the example below on how a polygon can be created. The coordinates are connected based on their clockwise order in the list. The resulting shape can be filled with a color:

private func createMapPolygon() -> MapPolygon {
    // Note that a polygon requires a clockwise order of the coordinates.
    let coordinates = [GeoCoordinates(latitude: 52.54014, longitude: 13.37958),
                       GeoCoordinates(latitude: 52.53894, longitude: 13.39194),
                       GeoCoordinates(latitude: 52.5309, longitude: 13.3946),
                       GeoCoordinates(latitude: 52.53032, longitude: 13.37409)]

    // We are sure that the number of vertices is greater than three, so it will not crash.
    let geoPolygon = try! GeoPolygon(vertices: coordinates)
    let fillColor = UIColor(red: 0, green: 0.56, blue: 0.54, alpha: 0.63)
    let mapPolygon = MapPolygon(geometry: geoPolygon, color: fillColor)

    return mapPolygon
}

A MapPolygon consists of three elements:

  • A list of three or more geographic coordinates that define where to place the polygon on the map.
  • A GeoPolygon that contains this list of coordinates.
  • A Color to define the fill color of the polygon area.

Since a polygon is defined by three or more points, you need to create an array, which must contain at least three GeoCoordinates. Otherwise, an exception will be thrown. See for an example the screenshot.

Map polygons can be used to create complex filled or unfilled shapes. However, a self-intersecting polygon can lead to undesired results as the coordinates are connected in the order of the list. As an alternative you can add multiple polygons - or make sure to add the coordinates as they appear on the outline of the desired shape.

Please note that, unlike a map polyline, the outline of a map polygon is connected automatically between the last coordinate and the first coordinate of the list.

After you have created one or more map polygons, you can add them to a map scene with:

mapPolygon = createMapPolygon()
mapScene = mapView.mapScene
mapScene.addMapPolygon(mapPolygon!)

If a map polygon is already attached to a map scene, any further attempt to add it again will be ignored.

Screenshot: Showing a polygon.

Note that a map view allows only one scene and all map items are placed directly on it. If you want to group your map items, you may want to organize them by using an array and add or remove them individually.

A mapPolygon can be removed immediately from the map by calling:

mapScene.removeMapPolygon(area)

Note: MapPolygon items are pickable and it is possible to store Metadata that can be retrieved when picking the item. For an example, see the section below on map markers.

By setting a list of MapMeasureRange items, the visibility for a MapPolygon can be adjusted dependent on the current zoom level.

Note: By setting a draw order, you can specify what item is rendered on top of each other. Note that as of now, setting a draw order is not having an affect in relation to other map items as it only defines the order within the same type of class.

Add Map Circles

A circular shape can be useful to highlight areas on the map, draw a location accuracy halo - or to mark a distinct spot on the map. Circles are technically rendered as a sequence of triangular polygon shapes.

Consequently, circles can be created as a MapPolygon instance using a GeoCircle:

private func createMapCircle() -> MapPolygon {
    let geoCircle = GeoCircle(center: GeoCoordinates(latitude: 52.530932, longitude: 13.384915),
                              radiusInMeters: 300.0)

    let geoPolygon = GeoPolygon(geoCircle: geoCircle)
    let fillColor = UIColor(red: 0, green: 0.56, blue: 0.54, alpha: 0.63)
    let mapPolygon = MapPolygon(geometry: geoPolygon, color: fillColor)

    return mapPolygon
}

Since a circle is a special shape of a polygon, you can add (or remove) a circle to (or from) a map scene as already shown above in the MapPolygon section.

Screenshot: Showing a circle.

Add Map Markers

You can use map markers to precisely point to a location on the map. Map markers will always be drawn on top of anything else that is rendered on the map.

The following code will add a map marker to the map:

guard
    let image = UIImage(named: "here_car.png"),
    let imageData = image.pngData() else {
        print("Error: Image not found.")
        return
}

let mapImage = MapImage(pixelData: imageData,
                        imageFormat: ImageFormat.png)
let mapMarker = MapMarker(at: geoCoordinates,
                          image: mapImage)

mapView.mapScene.addMapMarker(mapMarker)

In this example, we create a UIImage from a PNG ("here_car.png") and convert it to a MapImage. This MapImage can then be set to a MapMarker instance.

Above we load the image with its default pixel size. By using MapImage(imageData: Data, imageFormat: ImageFormat, width: UInt32, height: UInt32) you can set a custom size.

Note

The HERE SDK for iOS supports PNG resources with or without transparency (alpha channel) - as well as all other common bitmap resources that are natively supported by UIImage including vector graphics such as PDF. An overloaded constructor allows to load graphics in the SVG Tiny format.

In opposition to static image assets, SVG assets can be also useful to show varying content - as only the XML content of the SVG assets needs to be updated. Static image assets and SVG assets can be updated on the fly. As an alternative, for more complex content, consider to use MapViewPins (see below).

To see the image, we must add the MapMarker to a map scene. Please note that the MapImage will be displayed centered on the provided geoCoordinates.

Screenshot: Showing randomly placed map images. The red map circle on top marks the location of the marker.

You can also update the geoCoordinates after the marker is added to the map: It will instantly appear at the new location once the mapMarker.coordinates property is updated.

Note

The chronological order in which map markers are added to the map determines what marker is rendered first. This can be adjusted by setting an explicit draw order. Note that as of now, setting a draw order is not having an affect in relation to other map items as it only defines the order within the same type of class.

If you want to remove a MapMarker, simply call:

mapView.mapScene.removeMapMarker(mapMarker)

You can also remove a list of map markers of type [MapMarker]() at once:

mapView.mapScene.removeMapMarkers(mapMarkers)

Likewise, you can add multiple map markers in a batch call via addMapMarker(mapMarkers).

The HERE SDK offers also highly customizable animation support for MapMarker items. A fade in-out animation can be applied with one line of code:

// Optionally, enable a fade in-out animation.
let durationInSeconds: TimeInterval = 3
mapMarker.fadeDuration = durationInSeconds

Whenever the marker is added or removed to the MapView, the animation will fade-in or fade-out the marker. The animation will also play when a marker was moved back to the viewport, ie. when the marker becomes visible again by panning the map.

Advanced custom animations, like moving markers, are possible with the MapMarkerAnimation class.

By setting a list of MapMeasureRange items, the visibility for a MapMarker can be adjusted dependent on the current zoom level.

On top, more features are available, for example, you can also make a marker transparent by setting an opacity value.

Retina Support for Different Resolutions

Whereas SVG images can be scaled without loosing the quality of your images, for pixel-based image formats such as PNGs, the iOS platform offers retina support natively by inserting @-annotations:

  • poi.png - Default. Asset size, for example: 100 x 100 pixels. Alternatively, you can also insert @1x.
  • poi@2x.png - For retina displays. Asset size doubled: 200 x 200 pixels.
  • poi@3x.png - For retina HD displays. Asset size tripled: 300 x 300 pixels.
  • ...

Note that this does not require any specific HERE SDK code: iOS will load the correct image dependent on the device screen and the file name. In your app you will load the image natively with UIImage(named: "poi.png") - as also shown above for the MapMarker code snippet, so you omit the @-annotation and iOS will load the correct asset. The resulting image will have the same size on screen, but with a higher quality asset on bigger screens. Take a look at the MapItems example app for a usage example - the various resolutions can be found in the poi.imageset assets folder. Note that such an effort makes sense if you have created assets that show more details for higher resolutions. If you omit resolution dependent assets, iOS can scale the asset which may look blurry on bigger screens.

Anchored POI Markers

By default, each image is centered on the location provided, and you may want to change this for some types of markers. An example is the POI marker, which usually points to the location with its bottom-middle position.

Therefore, the location of where the image is rendered must be shifted. The default center lies at (0.5, 0.5). If the bottom-right corner of the view should point to the set GeoCoordinates location, then the anchor point must be set to (1, 1).

Anchor points provide a convenient way to specify the location where a marker should be rendered: The top-left corner equals an anchor point of (0, 0) while the bottom-right corner equals an anchor point of (1, 1). Independent of how large the view is, the point that is half the width or height will always be 0.5 - this is similar to the concept of normalized texture UV-coordinates.

Illustration: Normalized anchor points can specify any location within or outside a map marker.

If you want to shift the POI to point to the location, you can keep the default middle location (0.5), but you must shift the image upwards by 1. 1 is just as long as the height of the image. Note that you can also specify values greater than 1 or less than 0, so that you can shift the image to any possible location. 2 would represent twice the height of the image and so on.

To add an anchored POI marker to the map, see the example below:

guard
    let image = UIImage(named: "poi.png"),
    let imageData = image.pngData() else {
        print("Error: Image not found.")
        return
}

// The bottom, middle position should point to the location.
// By default, the anchor point is set to 0.5, 0.5.
let anchorPoint = Anchor2D(horizontal: 0.5, vertical: 1)
let mapMarker = MapMarker(at: geoCoordinates,
                          image: MapImage(pixelData: imageData,
                                          imageFormat: ImageFormat.png),
                          anchor: anchorPoint)

mapView.mapScene.addMapMarker(mapMarker)

For the example above, a custom POI image called "poi.png" is added in different resolutions to the project's asset catalog. The iOS platform will choose the appropriate image resolution based on the device's display density. See the accompanying example app on how this can be done.

Screenshot: Showing randomly placed map markers. The red map circle marks the anchored location of the marker.

Unlike polylines, each MapImage will keep its size - regardless of how much the map is zoomed in or out.

Pick Map Markers

After you have added the map markers onto the map, you can use a tap gesture delegate to find out if a user tapped on a map marker:

// Conform to the TapDelegate protocol.
func onTap(origin: Point2D) {
    mapView.pickMapItems(at: origin, radius: 2, completion: onMapItemsPicked)
}

// Completion handler to receive picked map items.
func onMapItemsPicked(pickedMapItems: PickMapItemsResult?) {
    guard let topmostMapMarker = pickedMapItems?.markers.first else {
        return
    }

    showDialog(title: "Map marker picked:", message: "Location: \(topmostMapMarker.coordinates)")
}

Our class must then conform the TapDelegate protocol and we need to set our class as delegate to receive tap events. Once a tap gesture is recognized, we need to set a completion handler to pick a potential item.

Note

By convention, the HERE SDK uses protocols for reoccurring events such as gesture events. Single events, that must be handled only one time, require a callback function in form of a completion handler.

As soon as the tap gesture is detected, we can use the view coordinates of the tapped location on the screen to ask the map view for any map markers around that location. In most cases, specifying a radius of two pixels is adequate. Then the PickMapItemsResult provides access to the map items found, such as a MapPolyline or a MapMarker.

Note

When picking items of the same type, you can compare the instances using the ===-operator.

Adding Metadata

In many cases, users may want to interact with the shown markers - for example, by tapping on a search result to see more details about a restaurant. For this purpose, a MapMarker can hold an instance of the Metadata class, so it is possible to attach various types of data to it - even custom types are supported.

Metadata can hold several key/value pairs. Below, we create a new key named "key_poi" and set a String as the value containing the information about the type of the marker:

let metadata = Metadata()
metadata.setString(key: "key_poi", value: "This is a POI.")
mapMarker.metadata = metadata

Certainly, you can set any information you may need. The moment we want to read the contents of a Metadata instance, we simply ask for the data stored for a key, which is "key_poi" in our example:

if let message = topmostMapMarker.metadata?.getString(key: "key_poi") {
    showDialog(title: "Map Marker picked", message: message)
    return
}

A MapMarker instance, by default, does not contain Metadata and topmostMapMarker.metadata may be nil. The data accessed by a key can be nil as well, if the Metadata object does not contain such information.

If it does, we look for the String stored for our key "key_poi" and call a helper method to present the contained String to the user. You can choose any string as a key based on your preference, but use a unique key, or you will otherwise overwrite the content stored for a different data item. To see the full example's source code, please check the MapMarker example app.

Note

You can also store custom objects into the Metadata using the CustomMetadataValue interface. An example can be found in the Search section where a search result data object is stored as a whole.

Add Map Marker Cluster

Depending on zoom level, multiple MapMarker items can overlap. With the MapMarkerCluster class you can group multiple MapMarker items to a group that can reduce the visual clutter. Markers that are overlapping will be replaced by a single image representation. Such a cluster image can be picked and contains only the markers that are contained within.

The code below shows how a cluster containing multiple MapMarker items can be created:

guard
    let image = UIImage(named: "green_square.png"),
    let imageData = image.pngData() else {
        print("Error: Image not found.")
        return
}

let clusterMapImage = MapImage(pixelData: imageData,
                               imageFormat: ImageFormat.png)

// Defines a text that indicates how many markers are included in the cluster.
var counterStyle = MapMarkerCluster.CounterStyle()
counterStyle.textColor = UIColor.black
counterStyle.fontSize = 40
counterStyle.maxCountNumber = 9
counterStyle.aboveMaxText = "+9"

let mapMarkerCluster = MapMarkerCluster(imageStyle: MapMarkerCluster.ImageStyle(image: clusterMapImage),
                                        counterStyle: counterStyle)
mapView.mapScene.addMapMarkerCluster(mapMarkerCluster)
mapMarkerClusters.append(mapMarkerCluster)

var index = 1
for _ in 1...10 {
    let indexString = String(index)
    mapMarkerCluster.addMapMarker(marker: createRandomMapMarkerInViewport(indexString))
    index = index + 1
}

You can set a MapImage that should be used to represent a cluster of two or more overlapping map markers.

Note that MapMarker items can be added or removed to a MapMarkerCluster that is already shown on the map. If you want the remove the cluster including all markers call:

mapView.mapScene.removeMapMarkerCluster(mapMarkerCluster)

MapMarker items contained in a cluster are not part of pickMapItemsResult.markers. Therefore, we can pick them separately with the code as shown below - after we have received the pick result from our pickMapItems() call (see MapMarker section):

if let groupingList = pickedMapItems?.clusteredMarkers {
    handlePickedMapMarkerClusters(groupingList)
}

...

private func handlePickedMapMarkerClusters(_ groupingList: [MapMarkerCluster.Grouping]) {
    guard let topmostGrouping = groupingList.first else {
        return
    }

    let clusterSize = topmostGrouping.markers.count
    if (clusterSize == 0) {
        // This cluster does not contain any MapMarker items.
        return
    }
    if (clusterSize == 1) {
        let metadata = getClusterMetadata(topmostGrouping.markers.first!)
        showDialog(title: "Map Marker picked", message: "This MapMarker belongs to a cluster. Metadata: \(metadata)")
    } else {
        var metadata = ""
        for mapMarker in topmostGrouping.markers {
            metadata += getClusterMetadata(mapMarker)
            metadata += " "
        }
        let metadataMessage = "Contained Metadata: " + metadata + ". "
        showDialog(title: "Map marker cluster picked",
                   message: "Number of contained markers in this cluster: \(clusterSize). \(metadataMessage) Total number of markers in this MapMarkerCluster: \(topmostGrouping.parent.markers.count)")
    }
}

private func getClusterMetadata(_ mapMarker: MapMarker) -> String {
    if let message = mapMarker.metadata?.getString(key: "key_cluster") {
         return message
    }
    return "No metadata."
}

With this code you can detect if a cluster was picked and inform the user of the contained markers. You can also identify a single MapMarker instance if the markers list is containing only one item.

Several map marker cluster. The number indicates the contained marker.

Usually, only a single MapMarkerCluster instance is needed and above we handle only the topmost cluster.

Depending on the distance of the markers, multiple cluster images can appear for the same MapMarkerCluster instance - each containing a subset of the total number of clustered markers.

See the MapItems app for an example on GitHub.

Pick Embedded POIs

Embedded POIs are carto POI marker that are already preconfigured and shown on the MapView, by default. Unlike MapMarker items, their content and visual appearance cannot be changed without using the HERE Style Editor. However, it is possible to tap on such an icon and retrieve information such as location, PlaceCategory and the name of the POI.

Embedded POIs can be picked in parallel to other MapMarker items shown on the map, unless they are currently hidden by another map item.

// Conforming to TapDelegate protocol.
func onTap(origin: Point2D) {
    // You can also use a larger area to include multiple carto POIs.
    let rectangle2D = Rectangle2D(origin: origin,
                                  size: Size2D(width: 1, height: 1))
    mapView.pickMapContent(inside: rectangle2D, completion: onMapItemsPicked)
}

// Completion handler to receive picked map items.
func onMapItemsPicked(pickedMapContent: PickMapContentResult?) {
    guard let pickedMapContent = pickedMapContent else {
        // Pick operation failed.
        return
    }

    let cartoPOIList = pickedMapContent.pois
    if cartoPOIList.count == 0 {
        // No results found at pick location.
        return
    }

    let topmostCartoPOI = cartoPOIList.first!
    let name = topmostCartoPOI.name
    let lat = topmostCartoPOI.coordinates.latitude
    let lon = topmostCartoPOI.coordinates.longitude
    ...
}

Note that extended place details are only available for the Navigate Edition.

Control the Visibility of Embedded POIs

The visibility of embedded POIs on the map can be controlled with MapScene.setPoiVisibility(...) that allows to set a VisibilityState for a list of POI categories.

Note that not all POI categories are available for all map schemes.

A list of supported categories can be found in the documentation of the HERE Style Editor.

On top, the Explore Edition does not support all PlaceCategory fields to be shown as embedded POI. For example, eatAndDrink and shopping are only visible when using the Navigate Edition.

Note that the following embedded POI category groups currently do not appear on the MapView of the Explore Edition:

  • Accommodation
  • Automotive
  • Eat & Drink
  • Shopping

Add 3D Map Markers

The HERE SDK allows to add custom 3D models onto the map. Optionally, these models can be textured together with a blend Color. The common .obj file format is used to specify the geometry of the 3D model. You can generate it with common 3D modeling software - for example, with the free Three.js online editor.

The obstacle.obj 3D object we will use for this example.

The obj file format specifies the vertices, normals, texture coordinates and faces to define how the model will be rendered. The resulting model can be moved around the map by updating its coordinates. Its orientation can be changed by updating its bearing, pitch and roll.

Note that the HERE SDK does not support material files (*.mtl) and multi texturing.

Once you have a model defined in the obj format and a texture to wrap around the model, add both files to an assets directory in your project via drag & drop.

The obstacle_texture.png texture we will use for this example.

Use iOS's Bundle to get the path to a resource:

private func getResourceStringFromBundle(name: String, type: String) -> String {
    let bundle = Bundle(for: ViewController.self)
    let resourceUrl = bundle.url(forResource: name,
                                 withExtension: type)
    guard let resourceString = resourceUrl?.path else {
        fatalError("Error: Resource not found!")
    }

    return resourceString
}

With this you will get an exception when the file does not exist at the expected file location.

Now you can use the following code to add a MapMarker3D to the map:

let geometryFile = getResourceStringFromBundle(name: "obstacle", type: "obj")
let textureFile = getResourceStringFromBundle(name: "obstacle_texture", type: "png")

let mapMarker3DModel = MapMarker3DModel(geometryFilePath: geometryFile, textureFilePath: textureFile)
let mapMarker3D = MapMarker3D(at: geoCoordinates, model: mapMarker3DModel)
mapMarker3D.scale = 6
mapMarker3D.isDepthCheckEnabled = true

mapView.mapScene.addMapMarker3d(mapMarker3D)

Above, we pass both asset files to the MapMarker3DModel constructor that defines the model. Similarly, like we have already seen for MapImage elements, you can pass the model to one of the available MapMarker3D constructors. Note that we also set a scale factor to let the model appear 6x bigger. Since the obj model is defined in a 3D coordinate space, it does not contain length units.

You can add and remove MapMarker3D items like other map items via MapScene.

Note

Tip: The texture must be at least of 1 pixel in size. If you add a transparent pixel as texture image, you can blend the untextured model with a Color that can be passed as third parameter to the MapMarker3DModel constructor.

Below you can see an example of how it may appear. The model will be centered on the provided geographic coordinates. The center of the model is defined by the origin of its coordinate system.

Two custom 3D map markers shown on a tilted map.

The property isDepthCheckEnabled determines whether the depth of the 3D marker's vertices is considered during rendering and it is set to false by default.

  • MapMarker3D items are always rendered on top of anything else that is visible on the map if isDepthCheckEnabled is enabled to false.
  • If isDepthCheckEnabled is set to true then the 3D marker might be occluded by other map objects like extruded buildings. The method isDepthCheckEnabled is helpful to depict complex 3D objects like a torus which has outer as well as inner areas.

Like 2D MapMarker items, a MapMarker3D will not change its size when the map is zoomed in or out, but it will rotate together with map.

What to do if you want the 3D marker to scale with the map?

For this, simply use the convenience constructor for MapMarker3D that accepts a RenderSize.Unit. For example, use densityIndependentPixels to prohibit scaling and the resulting marker is created with a fixed size - independent of zoom level. Use RenderSize.Unit with meters to allow scaling.

By setting a list of MapMeasureRange items, the visibility for a MapMarker3D can be adjusted dependent on the current zoom level.

If you want to change the transparency of a MapMarker3D, you can specify an opacity factor: The factor is applied to the alpha channel of the texture of the marker. By setting the renderInternalsEnabled flag you can specify whether to render the internal geometry occluded by its front facing polygons.

Add Flat Map Markers

By default, MapMarker items do not rotate with the map - nor get tilted when the map is tilted. This can be changed by using a MapMarker3D to become flat. In fact, flat map markers are a special case of MapMarker3D items that contain a 0 length on the z-axis in 3D space.

You can create flat MapMarker3D objects by using the convenience constructor that accepts a MapImage parameter. Use RenderSize.Unit with densityIndependentPixels to prohibit scaling. The resulting marker is created with a fixed size - independent of zoom level. Use RenderSize.Unit with meters to allow scaling.

The resulting flat marker will tilt with the map and it will also rotate when the map is rotated.

guard
  let image = UIImage(named: "poi.png"),
  let imageData = image.pngData() else {
      print("Error: Image not found.")
      return
}

// The default scale factor of the map marker is 1.0. For a scale of 2, the map marker becomes 2x larger.
// For a scale of 0.5, the map marker shrinks to half of its original size.
let scaleFactor: Double = 0.5

let mapImage:MapImage = MapImage(pixelData: imageData, imageFormat: ImageFormat.png)

// With densityIndependentPixels, the map marker will have a constant size on the screen regardless if the map is zoomed in or out.
let mapMarker3D: MapMarker3D = MapMarker3D(at: geoCoordinates, image: mapImage, scale: scaleFactor, unit: RenderSize.Unit.densityIndependentPixels)

mapView.mapScene.addMapMarker3d(mapMarker3D)

In this example, we load a PNG ("poi.png") from the resources and create a MapImage out of it. This MapImage can then be set to a MapMarker instance.

To see the image, we must add the MapMarker to a map scene. Note that the MapImage will be displayed centered on the provided geoCoordinates.

What to do if you want the flat 3D marker to scale with the map?

Create a flat map marker using MapMarker3D and use RenderSize.Unit with meters to allow scaling when zoomed in and out.

How To Create a Flat 2D Map Marker From a 2D Model

In the next paragraph, we show how a 2D model can be created from a handwritten obj file. As a result, we can create the same flat map marker as in the prevous section.

Below you see a 2D example for a plane, that is 2 units large on the x- and y-axis. Since 3D objects can be easily scaled, the size of the model is not important. The origin of the coordinate system in our example lies at the bottom of the plane. This way we can wrap a POI marker asset as texture that points to the provided geographic coordinates.

# A 2 x 2 square, centered upon origin.

v -1 2 0
v 1 2 0
v -1 0 0
v 1 0 0
# 4 vertices

vt 0 1
vt 1 1
vt 0 0
vt 1 0
# 4 texture vertices

vn 0 0 1
vn 0 0 1
vn 0 0 1
vn 0 0 1
# 4 vertex normals

f 1/1/1 3/3/3 2/2/2
f 3/3/3 4/4/4 2/2/2
# 2 faces

For this example, we store the above model definition of a plane into a text file called "plane.obj".

The plane.obj 3D model we will use for this example.

Since the plane is a square, we extend the size of the POI image on the left and right side with a transparent area, so that the image becomes a square. As our original image is a rectangle and not a square it would get distorted when it would be wrapped onto the plane.

Once you have a model defined in the obj format and a texture to wrap around the model, add both files to an assets directory in your project via drag & drop.

The poi_texture.png texture we will use for this example.

Use the following code to add a flat marker to the map:

let geometryFile = getResourceStringFromBundle(name: "plane", type: "obj")

// The POI texture is a square, so we can easily wrap it onto the 2 x 2 plane model.
let textureFile = getResourceStringFromBundle(name: "poi_texture", type: "png")

let mapMarker3DModel = MapMarker3DModel(geometryFilePath: geometryFile, textureFilePath: textureFile)
let mapMarker3D = MapMarker3D(at: geoCoordinates, model: mapMarker3DModel)
// Scale marker. Note that we used a normalized length of 2 units in 3D space.
mapMarker3D.scale = 70

mapView.mapScene.addMapMarker3d(mapMarker3D)

The code for the getResourceStringFromBundle(name:type:) method can be seen in the previous section.

Note that we used a normalized length of 2 units in 3D space, therefore we scale the model to be 60x bigger. The result can be seen in the screenshot below.

Flat map markers - rotated and tilted together with the map.

We have added a red circle to indicate the location to which the flat marker is pointing to.

Flat map markers rotate along with the map - and the map marker will also be tilted when the map is tilted, allowing for a 3D-like effect, although its 2D model is flat. Please note that, by default, flat map markers will not change their scale value together with the zoom level of the map: For example, when zooming out the map, a map marker will still be visible - same as for an unflattened MapMarker.

If you want the marker to scale with the map, create a flat map marker as shown in the previous section.

Add a Location Indicator

Another type of 3D map items is the LocationIndicator. Usually, only one instance is added to the map to indicate the current location of the user's device on the map - including a heading direction.

Unlike other map items, a LocationIndicator implements the MapViewLifecycleDelegate protocol, as it's lifecycle is managed by the MapView once it is added.

The HERE SDK provides predefined 3D assets for various use cases. If desired, these can be replaced by setting your own customized MapMarker3DModel for each of the predefined styles.

As all map markers, also a LocationIndicator will not be scaled when the zoom level of the map view will change. However, if the map is tilted, the LocationIndicator will get smaller when it is moved farther to the horizon.

Let's see an example how to add a LocationIndicator onto the map:

private func addLocationIndicator(geoCoordinates: GeoCoordinates,
                                  style: LocationIndicator.IndicatorStyle) {
    let locationIndicator = LocationIndicator()
    locationIndicator.locationIndicatorStyle = style

    // A LocationIndicator is intended to mark the user's current location,
    // including a bearing direction.
    // For testing purposes, we create a Location object. Usually, you may want to get this from
    // a GPS sensor instead.
    var location = Location(coordinates: geoCoordinates)
    location.time = Date()
    location.bearingInDegrees = getRandom(min: 0, max: 360)

    locationIndicator.updateLocation(location)

    // A LocationIndicator listens to the lifecycle of the map view,
    // therefore, for example, it will get destroyed when the map view gets destroyed.
    mapView.addLifecycleDelegate(locationIndicator)
}

As you can see above, no asset is required. Instead an IndicatorStyle is set:

  • LocationIndicator.IndicatorStyle.navigation: An asset designed for navigational use cases.
  • LocationIndicator.IndicatorStyle.pedestrian: An asset designed for handheld usage, ie. while sitting or walking.

Note

Note that the halo of the asset is not yet showing the actual horizontal accuracy of the provided Location. This is planned for one of the next HERE SDK updates.

Both styles indicate the current bearing - which represents the direction the user is heading to. In the example, we set a random bearing value between 0° and 360° degrees. A bearing of 0° degress is indicating North-up, and thus, the arrow is pointing up - as the map is also pointing North-up, by default.

A location indicator for navigation use case.

During navigation, a common UX approach is to rotate the map into the direction the user is driving, so that the direction arrow keeps pointing up, although the bearing may change. Usually, during navigation the arrow is expected to point into the direction of the road the user is traveling on.

For a pedestrian use case, the focus lies on the current location of the user. Therefore, the direction is indicated by a much smaller arrow.

A location indicator for pedestrian use case.

It depends on the application how the bearing value is utilized. Note that the bearing value as derived from the Location object indicates the direction of movement, while alternatively an application may choose to set the bearing in relation to true north (compass mode). If you want the arrow to point to true North, then instead change the bearing value to 0°. Note that such adaptions must be done each time when you receive a new Location update from a location source (see below).

Usually, only one instance of a LocationIndicator is set to the map. By calling updateLocation() its location can be updated and by calling setLocationIndicatorStyle() its style can be updated on-the-fly.

Each style has several associated MarkerType values that define different states, such as a gray state when the GPS signal is lost. When a LocationIndicator is customized, it is important to set all types, otherwise changing a state will have no effect.

The following code snippet shows how to switch between a predefined gray type - indicating an inactive state - and the default state:

let isActive = locationIndicator.isActive
// Toggle between active / inactive state.
locationIndicator.isActive = !isActive

A LocationIndicator implements the MapViewLifecycleDelegate protocol, therefore it's coupled with the lifecyle of the MapView.

As a benefit - to support the most common use case - you can add the LocationIndicator to the map once and then its lifecycle will be automatically managed by the MapView. However, if you want to remove the LocationIndicator on your own, call:

mapView.removeLifecycleDelegate(locationIndicator)

Note

The LocationIndicator is not yet pickable and it's always drawn on top of everything else without the need to set a draw order.

For most uses cases, the LocationIndicator should get updated based on frequent Location updates. You can see an isolated usage example as part of the MapItems example app.

Note

The LocationIndicator is always rendered at a fixed altitude near 0. Changing the MapCamera to look at geographic coordinates with an altitude that is higher can cause a problem: If the MapCamera angle is tilted and altitude is too high, the LocationIndicator can disappear from the viewport due to the new perspective.

Note

The NavigationCustom example app shows how to switch to a custom LocationIndicator and to a different marker type when navigation has stopped.

How to use the MapViewLifecycleListener

The MapViewLifecycleListener can be implemented by any class that wants to listen to the lifecycle of the MapView. As an example, for the LocationIndicator, this interface is already implemented. The implementation takes care to react on the following events:

  • onAttach(to mapView: MapViewBase): Called when adding the implementing object to the map view.
  • onPause(): Called when the map view to which the implementing object is attached gets paused (usually, when the app goes into background).
  • onResume(): Called when the map view to which the implementing object is attached gets resumed (usually, when the app goes into foreground).
  • onDetach(from mapView: MapViewBase): Called when removing the implementing object from the map view.
  • onDestroy(): Called when the map view to which the implementing object is attached to is destroyed.

You can attach and remove the implementing object like so:

  • Attach an object to the MapView lifecycle: mapView.addLifecycleDelegate(myObject)
  • Remove an object from the MapView lifecycle: mapView.removeLifecycleDelegate(myObject)

Note

In case of the LocationIndicator, the methods onPause() and onResume() do nothing. The attach / remove implementation takes care to add the indicator to the MapView to make it visible or to remove it.

How to pick map items from a MapView

Below table demonstrates how to pick the map items that are currently pickable:

MapItems
How to pick
MapPolyline _mapView.pickMapItems(at: origin, radius: 2, completion: onMapItemsPicked)
MapPolygon mapView.pickMapItems(at: origin, radius: 2, completion: onMapItemsPicked)
MapMarker mapView.pickMapItems(at: origin, radius: 2, completion: onMapItemsPicked)
MapMarkerCluster.Grouping mapView.pickMapItems(at: origin, radius: 2, completion: onMapItemsPicked)
Embedded POIs mapView.pickMapContent(inside: rectangle2D, completion: onMapItemsPicked)
MapViewPin UITapGestureRecognizer(target: self, action: #selector(onMapViewPinTapped))

Add Map View Pins

While map markers offer a seamless way to place items on the map, map pins can be used to pin a native UIView to the map. This can be useful to show information pop-up bubbles (or animated info bubbles), annotations, or customized controls. For example, when tapping on a map marker you can show a map overlay with additional information about the marker location.

Map pins can be composed out of multiple UIViews, and each of them can be used just like any other UIView, following user-defined Auto-Layout constraints, animations, and even native gesture handling, allowing the use of, for example, UITapGestureRecognizers.

Note

A view pin is attached to a map view, but not part of the map itself, since it is composed out of native views. Therefore, when panning the map view, the pins will move together with the map view, but with a slight delay. If you want to avoid this, consider to use MapMarker instances instead - especially, if you want to show multiple instances at once.

As is the custom, you can define your views in an Interface Builder layout file and connect them to your ViewController - or generate the desired view content programmatically. For example:

let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(onMapViewPinTapped))
let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
textView.textAlignment = .center
textView.isEditable = false
textView.backgroundColor = UIColor(red: 72/255, green: 218/255, blue: 208/255, alpha: 1)
textView.textColor = .white
textView.font = .systemFont(ofSize: 17)
textView.text = "Centered ViewPin"
textView.addGestureRecognizer(tapRecognizer)

You can set a tap gesture listener by adding a UITapGestureRecognizer to the UITextView as shown above. Then add the handler for UITAPGestureRecognizer as shown below:

    @objc func onMapViewPinTapped() {
        print("Tapped on MapViewPin.")
    }

The UITextView is a descendant of UIView, it can be used directly as a pin. Now, all we need to do is to add our view to the map. Note that pins can be added directly to the map - unlike other map items such as polygons or markers:

let viewPin = mapView.pinView(view: textView, at: geoCoordinates)

Note that this method returns a proxy object that can be used to control the pinning, for example, to specify an anchor point.

Once added to the mapView, the view - including all nested sub-views - will appear centered on the provided geoCoordinates location and its location will automatically adjust to the given geographical location when the map is moved.

Try to remove the line starting with textView.isEditable. What will happen? Since the ViewPin makes sure that the real view is rendered on the provided location, this will enable the default behavior of an UITextView and therefore become editable.

Screenshot: A map pin showing an UITextView. By default, the view is centered on the provided location.

It is also possible to apply animations to the view or attach some other interaction listeners. After a view is attached to the map view, it will behave like any other iOS UIView - except that it stays fixed on the map and moves along with it when panning or zooming. Note, the ViewPin does not rotate when you rotate the map - similar to map polylines and map markers.

You can add as many map pins as you like, but you should take performance into consideration. For example, if you want to indicate multiple search results on the map, then map pins are less performant than map markers.

To remove a pin from the map, simply call:

mapView.unpinView(view: textView)

If you have added multiple ViewPin instances, you can access all pins from the mapView object by calling:

let viewPins = mapView.viewPins

Usually, map pins are the best choice for showing additional dynamic content for a specific location on the map.

Anchored Map Pins

By default, the map pins will be centered on the provided location. But if you want to use a pin without covering the area underneath, what can you do?

For this purpose, you can specify an anchor point - just like you do for any UIView:

textView.layer.anchorPoint = CGPoint(x: 0.5, y: 1)

This will place the view centered horizontally on the location, while the bottom of the view is matching the provided coordinate. As visualized in the screenshot below, the map pin sits on a map circle object that indicates the provided center location of the map pin.

Screenshot: An anchored map pin.

Anchor points provide a convenient way to specify the location where the view should be rendered: Independent of how large the view is, the point that is half the width or height will always be 0.5 - this is similar to the concept of normalized texture UV-coordinates.

By default, the anchor point is (0.5, 0.5), which will render the view centered on the location. Since a view can be of any size, the maximum width and height will have a value of 1. The dimension of the view is calculated after it is fully inflated. If you know the exact dimensions of your view, you can easily calculate a specific point inside the view in relation to the maximum value of 1.

Note: While offsets allows you to specify the translation along the x- and y-axis, an anchor point defines the relative position of the top-left corner of a rectangle such as a view. In relation to the view's boundaries, it defines the point where the view is centered on the provided GeoCoordinates location.

results matching ""

    No results matching ""