Displaying Multiple Locations Using TomTom's Maps SDK
John Odey·Mar 28, 2019

Displaying Multiple Locations Using TomTom's Maps SDK

John OdeyJohn Odey
John Odey
John Odey is a front-end software developer who has a strong passion for bringing conceptual ideas into real software solutions.
Mar 28, 2019 · 9 min read

Explore different ways in which TomTom’s SDK API can be leveraged to show the location of several entities on a map at once. This blog demonstrates how to enhance map usage by with additional features and API calls.  

The TomTom Maps SDK allows for location-based application development on web apps, iOS, and Android. It provides easy access to millions of data points collected by TomTom, maps functions for web apps, location search, and more, and is compatible with both web-based and native mobile app platforms.

In this article, we walk through using the TomTom Maps SDK by exploring some ways in which its SDK API call can be leveraged to show the location of several entities on a map at once. The article also demonstrates how best to enhance map usage by leveraging additional features and API calls available on the app development portal. It also explains the process of customizing map vector style and features so that you can start building location-based apps.

Getting started

It is both free and easy as a developer to sign up to use the TomTom API and SDK. Simply visit the TomTom for Developers site and register by clicking the link in the top right corner of the page. The developer dashboard grants access to create new apps and API keys, and several apps can be created at once.

Merely adding an application and requesting access to the Maps Display API product will prompt TomTom to provide a non-expiring API key for use with the Map Display API. Users receive 2,500 free API transactions per day to support the application and have access to free maps and traffic flow tiles when using Mobile Maps SDK for Android™ and iOS. (Note, if 2,500 API transactions per day is not enough, more transactions can be purchased by visiting My Credits screen in the developer dashboard.)

Download the Map SDK

The TomTom Maps SDK is available for download for free on the TomTom for Developers portal. Unzip it and save it in the project folder. You can also use our CDN by adding the following snippet in the HEAD section of your HTML file.

<head>
    <link rel='stylesheet' type='text/css' href='https://api.tomtom.com/maps-sdk-for-web/cdn/6.x/6.4.0/maps/maps.css'>
    <script src="https://api.tomtom.com/maps-sdk-for-web/cdn/6.x/6.4.0/maps/maps-web.min.js"></script>
</head>

Displaying a map

To get our feet wet with the map SDK, let’s start with something simple: Displaying a map on an application, with no particular place in the map focus. Below is the code to do this (note that you’ll first need the app to have been created on the developer portal because the API key created will be required).

var map = tt.map({
            key: "<your maps api key>",
            container: "map"
        });

As shown below, the script shows a map of the world from zoom 0.

Every map should focus on a particular point to add more context to the map. For this example, the coordinate HQ is placed on the map.

Geo coordinates can be added as an array of latitudes and longitudes. A zoom option level of 15 is also included. Here’s a sample:

var HQ = { lat: 9.0548, lng: 7.4856 }
var map = tt.map({
   key: '<your-api-key>'
   container: 'map',
   center: HQ,
   zoom: 15
});
multiple2

Adding a Marker to a Map

Markers are used to indicate the location of particular coordinates on a map.TomTom provides a simple API to enable developers to add attributes to a map. The marker also helps to give more detailed information about points in pop-ups:

var marker = new tt.Marker().setLngLat(HQ).addTo(map);
var popup = new tt.Popup({ anchor: 'top' }).setText('HeadQuarters')
marker.setPopup(popup).togglePopup()
multiple3

The same process can be repeated to add multiple locations to a map, as you can see in the following image.

multiple4

Continuing the process, you can add more points.

Getting important details

Location and geo-coordinates

TomTom provides an API to obtain the geo-coordinates of any location. The simplest way to obtain these coordinates is through TomTom’s API Explorer. The Fuzzy Search API section helps to retrieve location coordinates using the common address.

Take the sample address 2311 North Los Robles Avenue, Pasadena, California, USA and place it in a query field; clear other pre-populated fields when this query is executed. The response data returns coordinates in the following format.

<position>
    <lat>37.36729</lat>
    <lon>-121.91595</lon>
</position>

Please note that you should not use special HTML characters (like '$','?',&','#') in any address.

Loading multiple coordinates at once

In a production environment, it would not be practical to add every new location to a map with a new line of code. The coordinate can be added in a loop and added to the map.

            var companyAssets = [
                { lat: 52.373627, lng: 4.902642 },
                { lat: 52.3659, lng: 4.927198 },
                { lat: 52.347878, lng: 4.893488 },
                { lat: 52.349447, lng: 4.858433 }];
            companyAssets.forEach(function (child) {
                new tt.Marker().setLngLat(child).addTo(map);
            });

Dark mode map display

The default maps come in several themes. You can switch between different modes using ‘style’ in the map initialization. Check the following sample in the Developer Portal to see how to configure the URL when choosing a new style.

For example, changing to a night mode would look like this:

       var map = tt.map({
            key: <your-api-key>
            container: 'map',
            center: HQ,
            style: 'https://api.tomtom.com/style/1/style/20.4.5-*/?map=basic_night&poi=poi_main',
            zoom: 15
        });
multiple5

Styling the map

TomTom Vector maps properties such as fill colors, line styles, thickness, etc., are defined in an editable JSON file. More detailed documentation on available properties can be found here. Rather than edit manually, generating the style using the TomTom Map Styler is an easier approach.

Vector maps are made up of tiles and schema ; a tile is used to serve data on the map and the schema determines how the data is structured. The client determines how to present this data to the end-user using a style (for example, use of color and features like 2D areas, roads, ocean, and more.

Using the TomTom Map Styler, developers can customize and view map features. (For example, you could change an ocean background to red in place of the conventional blue.)

Getting started with map customization

To start creating your custom style, you can go to the link of the TomTom Map Styler above. The default theme is loaded by default. You’ll be required to add your TomTom API key if you’re not logged in.

multiple6

The next step is to open a new JSON file containing a style definition to the TomTom Map Styler. Click on the "Open" button.

multiple7

And select the “Night + Traffic Incidents” Style.

multiple8

Once the map style is loaded, the picture above shows a customized map where the water background has been changed to dark blue.

The left-hand side of the TomTom Map Styler shows the map’s feature layers, with applicable customizations. You’ll also see the properties that can be customized. The right-hand side shows the live preview of the changes.

At any point, the newly customized style can be exported from the editor and tested: Just click “Export” from the menu and give it a new name.

You can test the style here. Upload the modified style (click on the "Choose File" button) and view the results.

Putting it all together: Real-world mapping example

In production, an API endpoint may be created to return the list of coordinates for every asset owned by the company and intended to be rendered on the map.

var AbujaZone = [
    {Address:"HQ",Coordinate: [9.0548, 7.4856]},
    {Address:"SUB HQ",Coordinate: [9.0600, 7.4899 ]},
    {Address:"ABUJA A",Coordinate: [9.0509, 7.4931 ]},
    {Address:"ABUJA B",Coordinate: [9.046, 7.4873 ]}
    {Address:"ABUJA C", Coordinate: [9.0530, 7.4793 ]}
    {Address:"NEW CONSTRUCTION",Coordinate:[9.0650, 7.4924 ]},
    {Address:"ABUJA E", Coordinate: [9.0650, 7.4734 ]}
]

Each entity returned is an object of address and coordinate. It is possible to return a more detailed object like the status of the machine or asset, opening time, etc. depending on what is required for the project.

AbujaZone.forEach(function (child) {
    new tt.Marker().setLngLat(child.Coordinate).addTo(map);
});

The project in the screenshot switches between two different locations: Lagos and the Abuja zone. To specify the marker icon for each location, you need to update the DOM element fort he marker. Check this example in the TomTom Developer Portal.

Here is a snippet of the code to create a custom marker:

function createMarker(icon, position, color, popupText) {
            var markerElement = document.createElement('div');
            markerElement.className = 'marker';

            var markerContentElement = document.createElement('div');
            markerContentElement.className = 'marker-content';
            markerContentElement.style.backgroundColor = color;
            markerElement.appendChild(markerContentElement);

            var iconElement = document.createElement('div');
            iconElement.className = 'marker-icon';
            iconElement.style.backgroundImage =
                'url(../assets/images/custom-markers/' + icon + ')';
            markerContentElement.appendChild(iconElement);

            var popup = new tt.Popup({offset: 30}).setText(popupText);
            // add marker to map
            new tt.Marker({element: markerElement, anchor: 'bottom'})
                .setLngLat(position)
                .setPopup(popup)
                .addTo(map);
        }

Note the URL of the iconElement. The background comes from assets that you can add to your application.

Summary

This article has explored ways to add multiple locations to a map and customize the map view, and it has examined the use of markers and vector map feature displays. The official TomTom documentation provides a complete list of available features and options.

The TomTom API offers a full location-based toolbox, with loads of features to build fully functional location-based apps, including:

  • Traffic API: Traffic information can be displayed via the Traffic API in different styles and flavors. Traffic Flow or Traffic Incident information can be overlaid on top of TomTom maps to visualize the congestion level, traffic jams, road work, blocked roads, closures, and more.

  • Map Display API: The Map Display API enables static and interactive maps to be displayed in any mobile and/or web application. TomTom real-time map-making technology provides users with the most accurate and up-to-date maps.

  • Routing API: The Routing API enables planning a route from A to B, considering both historical and real-time traffic conditions. As a result, applications can provide users with highly accurate travel times and live updated travel information and route instructions for multiple transportation types, such as car, truck, bicycle, and pedestrian.

  • Search API: The Search API enables geocoding and searching for an address or place. By using fuzzy matching algorithms and auto-completion, the Search API provides an excellent query interface for interacting directly with end-users.

Whether you're developing for a GPS data-based enterprise-level mobile application similar to Uber, Google Maps, Yelp, FourSquare, or Pokemon Go, or a new app in the dating, weather, social media, augmented reality, or fitness category, this can be a very useful set of tools.

Sign up for a free API key on our developer portal and get building today.

Get the developer newsletter.
No marketing fluff. Tech content only.

* Required field. By submitting your contact details to TomTom, you agree that we can contact you about marketing offers, newsletters, or to invite you to webinars and events. We could further personalize the content that you receive via cookies. You can unsubscribe at any time by the link included in our emails. Review our privacy policy.