DEV Community

Cover image for How to integrate TomTom API in React application
Takumon for TIS Ventures, Inc.

Posted on

How to integrate TomTom API in React application

Last month, I challenged DeveloperWeek Hackathon 2020 in SanFrancisco.
Our team built a React application using TomTom which is APIs of Maps, Directions, Places, and Traffic for mobile application.
If you are interested in the Hackathon's project, please see Devpost.

In this article, based on my experience in the hackathon, I explain how to build a React application using TomTom APIs in the following steps.
Let's dive in!
Alt Text

Show a Map

At first, you should import javascript and css file of TomTom APIs from CDN in index.html

<!DOCTYPE html>
<html lang="en">
<head>
  (snip)
  <link rel='stylesheet' type='text/css' href='https://api.tomtom.com/maps-sdk-for-web/cdn/5.x/5.45.0/maps/maps.css'>
  <link rel='stylesheet' type='text/css' href='https://api.tomtom.com/maps-sdk-for-web/cdn/5.x/5.45.0/maps/css-styles/routing.css'/>
  <link rel='stylesheet' type='text/css' href='https://api.tomtom.com/maps-sdk-for-web/cdn/5.x/5.45.0/maps/css-styles/poi.css'/>
  <link rel='stylesheet' type='text/css' href='https://api.tomtom.com/maps-sdk-for-web/cdn/5.x/5.45.0/maps/css-styles/traffic-incidents.css'/>

  <script src="https://api.tomtom.com/maps-sdk-for-web/cdn/5.x/5.45.0/maps/maps-web.min.js"></script>
  <script src="https://api.tomtom.com/maps-sdk-for-web/cdn/5.x/5.45.0/services/services-web.min.js"></script>
  (snip)
</head>
<body>
  (snip)
</body>
</html>

In a react component, you add a div that is the container for the map.

    <div id="map">

Finally, in the component, you add the following process to load a map.

  componentDidMount() {
    // snip
    const tt = window.tt

    const map = tt.map({
      key: process.env.REACT_APP_TOM_TOM_API_KEY,
      container: 'map',
      style: 'tomtom://vector/1/basic-main'
    })
    map.addControl(new tt.FullscreenControl())
    map.addControl(new tt.NavigationControl())

    this.map = map
    this.tt = tt
    this.points = [] // for management of points
    // snip
  }

If you want to specify the center of the map, you should add the following process.

  componentDidMount() {
    // snip
    const self = this
    map.on('load', () => {
      this.map.flyTo({
        center: {
          lng: longitudeValue,
          lat: latitudeValue,
        },
        zoom: 14, // you can also specify zoom level
      })
    })
    // snip
  }

Put Points on Map

You can put points on the map you created.
This process is very simple.

    new this.tt.Marker({
      color: '#2aceeb', 
      width: '20',
      height: '20'
    })
    .setLngLat([longitudeValueOfPoint, latitudeValueOfPoint])
    .addTo(this.map) // Don't forget to specify a map to be display

Show a Modal on Point

You can show modal on the points you created.
Here's an example of using the TomTom API to search for restaurants in the vicinity and putting points for the search results.

    const response = await this.tt.services.fuzzySearch({
        key: apiKey,
        center: this.map.getCenter(), // Search in the vicinity of the area indicated on the map
        query: 'restaurant',
        categorySet: '7315025', // Italian's category code,
    })
    .go()

    response.results.forEach(result => {
    const popup = new this.tt.Popup({offset: 30}).setHTML(this.createPopupContent(result));
    const marker = new this.tt.Marker()
                    .setLngLat(result.position)
                    .setPopup(popup)
                    .addTo(this.map)

    this.markers.push(marker) // Define this line so that you can control marker later.

Route Search

TomTom APIs also provides Navigation function.
Here's an example of getting a route in text format.

    const locations = `${lngOfOrigin},${latOfOrigin}:${lngOfDestination},${latOfDestination}`

    const { routes } = await this.tt.services.calculateRoute({
      locations,
      instructionsType: 'text',
      key: apiKey,
    }).go()

    const routesDirections = routes.map(route => {
      const { instructions } = route.guidance
      return instructions.map(i => {
        let result = ''

        switch (i.maneuver) {
          case 'TURN_LEFT':
            result+=''
            break
          case 'TURN_RIGHT':
            result+=''
            break
          case 'ARRIVE_RIGHT':
          case 'ARRIVE:LEFT':
          case 'WAYPOINT_REACHED':
            result+=''
            break
        }
        result += i.message.replace('waypoint','pickup area')
        return result
      })
    })
  }

TomTom APIs is feature-rich. You can make a great mobile app depending on your ideas. I hope you'll give it a try.

Top comments (0)