Sorry, you need to enable JavaScript to visit this website.

Migrate from Google Maps to TomTom

Overview

This tutorial covers some very basic use cases to help you switch from Google's APIs to TomTom's as quickly as possible. It begins with the basic environment setup along with use cases accompanied by code examples. At the very bottom of the page is a recommended reading list to allow you to build on the foundations provided by this tutorial.

This tutorial covers:

Prerequisites

To start using the TomTom Maps SDK for Web, you need the following:

  • The Maps library
    The Maps SDK for Web can be used in three ways:

    • Downloaded from NPM: https://www.npmjs.com/package/@tomtom-international/web-sdk-maps
    • With a CDN: https://api.tomtom.com/maps-sdk-for-web/cdn/5.x/<version>/maps/maps-web.min.js - NOTE: include the latest version in the URL.
    • Downloaded from: Downloads.

    In this tutorial, we are using CDN as an example.

  • API Key

    Get your API Key now

    To create a new API Key you need to first register on the
    portal. Once you are logged in there is only one step remaining:

    Go to your Dashboard:

    my dashboard

    You can now click on your app - My first app and copy your API Key:

    API Key

Displaying a map

Below is a minimal HTML structure containing the JavaScript code to initialize and display a TomTom map:

        <!DOCTYPE html>
        <html class='use-all-space'>
          <head>
            <meta http-equiv='X-UA-Compatible' content='IE=Edge' />
            <meta charset='UTF-8'>
            <title>My Map</title>
            <meta name='viewport'
                  content='width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no'/>
            <!-- Replace version in the URL with desired library version -->
            <link rel='stylesheet' type='text/css' href='https://api.tomtom.com/maps-sdk-for-web/cdn/5.x/<version>/maps/maps.css'/>
          </head>
          <body>
            <div id='map' class='map' style='width:100%; height:100vh'></div>
            <!-- Replace version in the URL with desired library version -->
            <script src='https://api.tomtom.com/maps-sdk-for-web/cdn/5.x/<version>/maps/maps-web.min.js'></script>
            <script>
              tt.setProductInfo('<your-product-name>', '<your-product-version>');
              tt.map({
                key: '<your-tomtom-API-Key>',
                container: 'map',
                style: 'tomtom://vector/1/basic-main'
              });
            </script>
          </body>
        </html>
        

To run this example locally, name it index.html and save it in the sdk-tutorial. Replace ‘<your-api-key>‘ with the API Key you obtained as shown in the Prerequisites section.

Run a HTTP server

Navigate to the directory containing your file using a terminal.

For example:

        ~$ cd sdk-tutorial/
        ~sdk-tutorial$
        

Install a light-weight HTTP server (you might need to run this command with admin/root privileges):

        npm install --global http-server
        

Then just simply run the following command:

        http-server
        

Note that npm comes bundled with Node.js, so please make sure you have it installed on your machine.

So now it is time to see the results!

Open a browser and type this url in the address bar: http://localhost:8080/index.html. You should be able to see a map! If not, use developer mode (press F12 on Windows or Linux or ⌘ + ⌥ + I on Mac) to check for console errors.

Initializing a map

The following code initializes a map using a defined center point and zoom level.

Google

        var map = new google.maps.Map(document.getElementById('map'), { 
          center: { lat: 37.769167, lng: -122.478468},
          zoom: 15
        });

TomTom

        var map = tt.map({
                key: '<your-tomtom-API-key>',
                container: 'map',
                style: 'tomtom://vector/1/basic-main',
                center: [-122.478468, 37.769167],
                zoom: 15
            });

These two code blocks have some similarities:

  • Both create a variable to refer to later.
  • Both use ‘center’ and ‘zoom’ as properties.
  • Both require the ID of an element to render the map (in this example, 'map').

The TomTom Maps SDK for Web requires a ‘key’ property for your API Key. In addition, the TomTom Maps SDK for Web expresses coordinates as an array rather than an object with properties.

Displaying traffic

The next step is to add a traffic layer to the map.

Google

        var trafficLayer = new google.maps.TrafficLayer();
        trafficLayer.setMap(map); 

TomTom

TomTom provides two services that offer traffic information:

  • Traffic flow shows the difference between current and free flow speed.
    • Green indicates that the speeds are the same, meaning there are no traffic jams.
    • Red indicates that traffic is much slower than free flow, meaning that there are traffic jams.
  • Traffic incidents indicates specific traffic problems such as closed roads, rain, ice on the road, or accidents.

The following code displays both types of traffic data:

        var trafficLayerConfig = {
            key: '<your-tomtom-API-key>',
            style: 'tomtom://vector/1/basic-main',
            refresh: 30000
        };
        var trafficIncidentsConfig = {
            key: '<your-tomtom-API-key>',
            incidentDetails: false,
            incidentTiles: true
        };
        map.on('load', function() {
            map.addTier(new tt.TrafficFlowTilesTier(trafficLayerConfig));
            map.addTier(new tt.TrafficIncidentTier(trafficIncidentsConfig));,
        });

Displaying a marker

Google

        var marker = new google.maps.Marker({ 
         position: { lat: 37.768454, lng: -122.492544 },
         map: map
        });
        

TomTom

        var marker = new tt.Marker().setLngLat([-122.492544, 37.768454]).addTo(map);
        

The next step is to allow your user to interact with the map by clicking on a marker to display an information popup.

Google

        var infowindow = new google.maps.InfoWindow({ 
         content: 'my marker'
        });
        marker.addListener('click', function() { 
         infowindow.open(map, marker);
        });
        

TomTom

        marker.setPopup(new tt.Popup().setHTML('my marker'));
        

Displaying a route/directions

Here’s how to display a route from point A to point B on the map. Google's name for this service is "directions". We just call it routing (Routing API).

Google

        var directionsService = new google.maps.DirectionsService();
        var directionsDisplay = new google.maps.DirectionsRenderer();
        directionsDisplay.setMap(map);
        var request = {
          origin: new google.maps.LatLng(37.768014, -122.510601),
          destination: new google.maps.LatLng(37.769167,-122.478468),
          travelMode: 'DRIVING'
        };
        directionsService.route(request, function(response, status) {
          if (status == 'OK') {
             directionsDisplay.setDirections(response);
          }
        });
        

To display a route with Google, you are required to use two services: one to ask for a route from A to B and another to render it on the map.

TomTom

Add services library in your html

        <!-- Replace version in the URL with desired library version -->
        <script src='https://api.tomtom.com/maps-sdk-for-web/cdn/5.x/<version>/services/services-web.min.js'></script>
        

And the code:

        tt.services.calculateRoute({
            key: '<your-tomtom-API-key>',
            locations: '-122.510601,37.768014:-122.478468,37.769167'
        })
        .go()
        .then(function(response) {
            var geojson = response.toGeoJson();
            map.addLayer({
                'id': 'route',
                'type': 'line',
                'source': {
                    'type': 'geojson',
                    'data': geojson
                },
                'paint': {
                    'line-color': '#00d7ff',
                    'line-width': 8
                }
            });
            var bounds = new tt.LngLatBounds();
            geojson.features[0].geometry.coordinates.forEach(function(point) {
                bounds.extend(tt.LngLat.convert(point));
            });
            map.fitBounds(bounds, {padding: 20});
        });
        

The only required parameters for the routing call are the start and end points, separated by a colon. If more colon-separated coordinates are provided, the ones in the middle will be used as intermediate locations (waypoints). By default, the route will be calculated for a car, but this and many other parameters can be changed. See the Maps SDK For Web Documentation - Calculate Route for complete details of routing parameters and filters.

Call the routing service by executing .go() function. The result will be returned as GeoJSON containing a 'LineString' feature. This is a (poly)line that can be added to a map, with defined properties like color, opacity, and weight.

Then call 'fitBounds' to center the map on the route.

The code above generates a polyline, but no markers. Developers have a lot of freedom to display the route, but if a start and end marker are required, they can be added in the same way as the "pop-up marker" above:

        new tt.Marker().setLngLat([-122.478468,37.769167]).addTo(map);
        new tt.Marker().setLngLat([-122.510601,37.768014]).addTo(map);
        

You can find more information about markers, including how to customize them, in the Maps SDK for Web documentation.

Searching

Searching for places is very similar in both SDKs. We need to provide a query, and then work on the response provided by the service.

Google

 

        var request = {
            query: 'Golden Gate Golf Course San Francisco',
            fields: ['name', 'geometry'],
        };
        service = new google.maps.places.PlacesService(map);
        service.findPlaceFromQuery(request, function(results, status) {
            if (status === google.maps.places.PlacesServiceStatus.OK) {
                for (var i = 0; i < results.length; i++) {
                    new google.maps.Marker({
                        map: map,
                        position: results[i].geometry.location
                    });
                }
            }
        });
        

TomTom

 

        tt.services.fuzzySearch({
            key: '<your-tomtom-API-key>',
            query: 'Golden Gate Golf Course San Francisco'
        })
        .go()
        .then(function(response) {
            for (var i = 0; i < response.results.length; i++) {
                new tt.Marker().setLngLat(response.results[i].position).addTo(map);
            }
        });
        

Final result:

You can find the full HTML file here on Github.

Summary

Using this tutorial, you should have converted an application from using the Google Maps JavaScript API to using the TomTom Maps SDK for Web. Now you have a map with fresh and accurate traffic information, on which you can easily plan many kinds of routes. Pretty cool, right?

Now you're ready to explore more awesome TomTom functionality with some more advanced tutorials and examples:

You are here