<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[TomTom Developers - Medium]]></title>
        <description><![CDATA[We’re here to help developers build the next generation of location-based applications. - Medium]]></description>
        <link>https://medium.com/tomtom-developers?source=rss----9c5d61983c4b---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>TomTom Developers - Medium</title>
            <link>https://medium.com/tomtom-developers?source=rss----9c5d61983c4b---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 20:25:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/tomtom-developers" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[An Introduction to the new TomTom Navigation SDK]]></title>
            <link>https://medium.com/tomtom-developers/an-introduction-to-the-new-tomtom-navigation-sdk-7f9ec2372b37?source=rss----9c5d61983c4b---4</link>
            <guid isPermaLink="false">https://medium.com/p/7f9ec2372b37</guid>
            <category><![CDATA[sdk]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[location]]></category>
            <dc:creator><![CDATA[TomTom Developers]]></dc:creator>
            <pubDate>Thu, 17 Nov 2022 00:47:40 GMT</pubDate>
            <atom:updated>2022-11-17T00:47:39.973Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tqMmBN6oALfS9jr5BERi4A.jpeg" /></figure><p>TomTom provides a wide range of geotechnology solutions developers can leverage in building software that solves human problems. One such solution is the new Navigation SDK, aimed at bringing decades of experience in perfecting GPS navigation into our hands in the form of easy-to-use SDKs available on different platforms, including Android and iOS operating systems.</p><p>TomTom’s <a href="https://www.tomtom.com/products/navigation-for-mobile/">Navigation SDK</a> is a powerful and feature-rich tool provided as a set of lightweight modules that allows us to quickly integrate the parts we need into our applications. What this means is that we can readily add features like map visualization, location handling, and driver guidance into our applications without hassle. In this article, we’ll explore the Navigation SDK, its core features, and the advantages of its modular design.</p><h3>TomTom Navigation SDK</h3><p>Navigation is an integral part of the everyday lives of people all over the world. There are countless use cases where we need some form of geotechnology to aid navigation.</p><p>Imagine we’re building a food delivery app that connects drivers, restaurants, and customers. This app’s core would be an effective navigation system with driver guidance. This is because there are restaurants and customers scattered all over the city, and the drivers are required to deliver orders to the correct location as quickly as possible.</p><p>It would be impossible to meet market demands if the drivers weren’t equipped with an effective navigation system. This is an example of how much value we can get from integrating the Navigation SDK.</p><p>The Navigation SDK enables us to build professional navigation applications that are tailored to the end users, which means that we can build navigation features into a wide variety of applications targeting different domains. For example, the navigation system in a food delivery app requires turn-by-turn navigation and voice instructions. If we’re integrating navigation into a ride sharing app, we’ll also need real-time traffic information and accurate ETAs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/0*M8BZyA6LUijyGYm2.jpg" /></figure><h3>Modularization</h3><p>One of the major considerations for developers when integrating external services or adding packages to our applications is the impact of bundle size. The size of the applications we build and ship can have significant effects on performance especially for mobile applications where an end user has to download the whole pre-built binaries.</p><p>TomTom’s Navigation SDK is made of a set of modular components that are independent of each other. This means that we can pick specific components to bring into our applications depending on business and logical requirements, resulting in much less performance cost due to bundle size.</p><p>The modularization of the SDK also gives us the ability to either replace components with implementations from different sources or integrate specific components into existing implementations.</p><p>Let’s consider a scenario where we already have a navigation system baked into our application, but we just want to integrate the voice instructions feature. We can do that by adding the TomTomSDKSystemTextToSpeechEngine. In technical terms, these drop-in components are called engines and they are managed by the orchestrator. Here’s a list of engines that exist in the Navigation SDK:</p><ul><li>Map Matching Engine</li><li>Route Replanning Engine</li><li>Guidance Engine</li><li>Route Deviation Engine</li><li>Route Progress Detection Engine</li><li>Location Context Detection Engine</li><li>Arrival Detection Engine</li></ul><h3>Features of the Navigation SDK</h3><p>TomTom’s new Navigation SDK is a feature-rich toolkit that we can leverage to integrate many geotechnology solutions into the applications we build. Let’s explore some of these features and the kind of solutions we can build with them.</p><h3>Navigation Configuration</h3><p>Navigation configuration is used to customize the Navigation experience to suit your needs. This is the entry point of the integration where we can specify the navigationKey, routingService, and locationEngine parameters. Using the iOS SDK, an example of the configuration would look like this:</p><pre>let configuration = NavigationConfigurationBuilder(<br> navigationKey: &quot;&lt;NAVIGATION-KEY&gt;&quot;,<br> locationEngine: locationEngine,<br> routingService: routingService<br>)<br>.build()<br>locationEngine.start()</pre><p>We can also specify the frequency of ETA updates and the distance and time setting for arrivals. Using the initialized configuration, we can create a navigation object which will enable us to perform some actions like starting and stopping navigation, updating the route, that will enable us to perform some actions like starting and stopping navigation, updating the route, and reporting specific events and reporting specific events that happen during navigation.</p><p>Returning to the example of a food delivery app, part of the business requirements might be to allow drivers to pick up multiple orders at once. This means that at each drop-off, the navigation system will need to re-route to the next drop-off location. We can achieve this by defining a set of route plans ahead of time and then using the update method on the navigation object to change the current route plan to the next drop-off location.</p><h3>Route and Maneuver Information</h3><p>Navigation is not always a straightforward or definitive process. Multiple factors can influence the route information provided. Weather conditions could cause a road blockage, or construction work could lead to heavy traffic on the road. It’s essential to take these factors into consideration. The Continuous Replanning component gives us this ability. With it, we can perform route refreshes in the background and check for better route alternatives without sacrificing user experience.</p><p>Additionally, the Continuous Replanning component is also fully customizable, meaning we can define configuration options like automatic or manual replanning mode or even disable continuous replanning entirely, depending on the kind of behavior we require.</p><p>We can also specify the time interval between route replans and the minimum time difference between routes before deciding to use an alternative route, and specify other configuration options like the route replanning policy and providing a custom better route selector.</p><p>One important factor to consider when building certain applications that require navigation is security. In a ride sharing app, it’s necessary to be able to tell in real-time when a driver deviates from the navigated route. Developers can easily integrate this feature using the Route Deviation configuration. The ability to make these types of granular configurations makes it easy for us to build rich navigation experiences that are tailored to specific use cases.</p><h3>Maps Integration</h3><p>Navigation and maps go hand-in-hand. We can think of maps as the visual tool necessary to build a complete navigation solution because they provide more context to navigation. TomTom provides a Maps SDK as a separate toolkit, but it’s easy to combine the Maps SDK and the Navigation SDK to create a highly interactive navigation experience using built-in UI components or custom components.</p><h3>Planned or Unplanned</h3><p>The Navigation SDK provides support for both unplanned journeys and planned routes. We’ve talked about navigation in the context of pre-defined routes. In planned routes, a RoutePlan is provided to the navigation object when the start method is called, and the route plan can be constantly updated throughout navigation.</p><p>On the other hand, unplanned journeys, also known as free driving, is navigation without a route. In free driving, we can get details about the current location, such as speed limit, country code, road characteristics, and so on, by setting up a location context.</p><p>There are many cases where this type of feature would be useful. Suppose we want to add a feature to our food delivery app that allows the driver to turn on an idle mode when they’re not picking up orders but still want access to navigation information like the speed limit. This is easy to implement because we can readily switch the driving mode between turn-by-turn navigation and free driving using the update method on the navigation object.</p><h3>Instructions</h3><p>Guidance instructions are a set of detailed information about navigation. They can be in the form of text or voice messages, and the developer can relay this information to the user as they see fit. Instructions and the channel in which we relay them are vital. If we’re integrating navigation into an app for drivers, then it’s necessary to have voice instructions because we cannot compromise road safety rules by having the driver read messages from the app.</p><p>The navigation module uses text-to-speech (TTS) functionality for generating voice instructions. Using the TTS engine, we can generate voice synthesis for messages. On the iOS SDK, initializing a TTS engine using the default SystemTextToSpeechEngine would look like this:</p><pre>let languageCode = &quot;en-Gb&quot;<br>let tts = SystemTextToSpeechEngine(language: languageCode)<br>self.tts = makeTextToSpeech(ttsEngine: tts)Conclusion</pre><p>We can then call the play method to synthesize provided messages. Instructions can also be configured just like other parts of the Navigation SDK. For example, the underlying language of the engine can be changed. In the code snippet above, we specified en-Gb as the underlying language. This is particularly important for internationalization if the application we’re building will be used by people in different locations around the world.</p><h3><strong>Conclusion</strong></h3><p>In this article, we explored the new TomTom Navigation SDK at a high level. The Navigation SDK is a feature-rich toolkit that enables developers to build many different geotechnology solutions. The modular approach to designing the SDK makes it easy to integrate specific features without compromising on factors like bundle size.</p><p>You can learn more about integrating the Navigation SDK into your applications by trying <a href="https://developer.tomtom.com/ios/navigation/documentation/overview/introduction">TomTom’s Navigation SDK</a> for yourself!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f9ec2372b37" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tomtom-developers/an-introduction-to-the-new-tomtom-navigation-sdk-7f9ec2372b37">An Introduction to the new TomTom Navigation SDK</a> was originally published in <a href="https://medium.com/tomtom-developers">TomTom Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Collaborative Map Editing can keep Maps Fresh in High-growth Areas]]></title>
            <link>https://medium.com/tomtom-developers/how-collaborative-map-editing-can-keep-maps-fresh-in-high-growth-areas-c1e5045830bd?source=rss----9c5d61983c4b---4</link>
            <guid isPermaLink="false">https://medium.com/p/c1e5045830bd</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[geospatial]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[mapping]]></category>
            <category><![CDATA[location-intelligence]]></category>
            <dc:creator><![CDATA[TomTom Developers]]></dc:creator>
            <pubDate>Fri, 19 Aug 2022 20:22:34 GMT</pubDate>
            <atom:updated>2022-07-07T20:02:59.322Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d8_rhhIVb3ogo3T1E9nPxQ.jpeg" /></figure><p>The world is changing by the minute. And, thanks to localized economic development and sudden population growth, some places are changing faster than others. Keeping up with that change isn’t easy.</p><p>The emergence of boomtowns — a town that experiences rapid population and economic growth — around the world poses an ever-evolving challenge to mapmakers who aim for their maps to reflect the real world as closely as possible and keep them fresh and accurate.</p><p>Boise, located on the Boise River in southwestern Idaho, USA, is one such town. Labelled the fastest growing city in the US in 2018 by Forbes, the capital of Idaho has been drawing in tens of thousands of new residents each year due to its affordable cost of living, desirable work-life balance and proximity to nature. The boom intensified with the COVID-19 pandemic as remote working became the norm and the allure of the fast-paced big city life began to dwindle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*Y2ay6obXHW1JsiTP.jpg" /></figure><p>Drawing tens of thousands of new residents every year, Boise, Idaho, has emerged as one of the fastest growing cities in the USA.</p><p>The need to make the city more livable for its new inhabitants led to development of all kinds of new facilities, be it housing, schools, hospitals or entertainment venues. Naturally, growing cities also require an expansion of road networks to connect the growing population.</p><p>One of the first considerations to make when finding a place to live in a new city is how accessible local amenities like schools, supermarkets, public transport and healthcare centers are. Without accurate and up-to-date digital maps, acquiring local knowledge about a rapidly developing city you’ve just moved to, in this day and age, is virtually impossible.</p><p>Not only does this inconvenience residents, but also enterprise businesses operating in that area who rely on the services of mapmakers, like TomTom, to make deliveries and run their fleets of vehicles.</p><p>“Say a street in a rapidly developing city like Boise has 10 houses on it, and each of those 10 houses receives 10 deliveries a year, which are made by our customers. That’s about 100 times a year that they’re calling on our map service, and if this street isn’t accurately mapped, we’re not able to fulfill our responsibility, costing them precious time and money,” says Saul Nochumson who leads product development as part of TomTom’s Community and Partnership team.</p><p>It can be frustrating to expect a delivery, and then find it being returned or delivered to a neighbour because your address wasn’t accurately displayed on a digital map. Fresh location data is also critical when it comes to ensuring that maps can guide their users around obstacles, such as construction sites or road closures.</p><p>With the world changing so rapidly, mapmakers must determine where exactly these changes are happening, so these areas can be given special attention and mapped accordingly.</p><h3>Identifying areas that need attention</h3><p>TomTom uses a multi-source approach to detect changes in the world that need to be reflected on its maps, including data from <a href="https://www.tomtom.com/blog/maps/mobile-mapping-journey/">survey vehicles</a>, <a href="https://www.tomtom.com/blog/navigation/way-out-of-the-coronavirus-chip-shortage/">GPS traces</a>, community input, governmental sources, and vehicle sensor data among others. This doesn’t just ensure the accuracy of maps, but also that locations such as Boise don’t slip off mapmakers’ radar.</p><p>TomTom also relies on “local intelligence”, or several regional sourcing specialists who monitor factors such as population growth and migration patterns across states to predict which areas are “booming” and require more attention.</p><p>“Using city-level, sometimes even county-level analysis, we’ve seen Boise becoming very popular for West Coast migration, making it an important spot for us,” says Peter King, who leads work on sourcing operations for the western half of the USA in TomTom’s map unit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*TnxID4QPmI-WyQjM.jpg" /></figure><p>The population boom in Boise has led to subsequent urban development, requiring mapmakers to take note and ensure digital maps reflect these changes quickly and accurately.</p><p>Government data can also make for a helpful resource. For example, every month, the US Postal Service adds new addresses — now receiving mail — to its records. The monthly address update is another useful source to alert mapmakers about potential changes in the world that need to be mapped.</p><p>“The US government actively tracks migration from state to state, and individual municipalities also provide us with sources to feed into our maps,” says King. “In this case, we have been working with the state of Idaho for several years. When they released state-wide geographical data a little over two years ago, we were able to zoom in on Boise and compare the localities with what our maps recognized. As the speed of development increased, so did our focus on the area.”</p><p>Once these areas have been identified, the question of how to edit the map arises. While mapmakers generally automate map editing to make it a smooth process, it’s not always the best choice. It might not work as well in areas that develop rapidly, like Boise, as it does in what King calls “maintenance geographies” — established areas like New York City (NYC) or Amsterdam where the volume of map changes is much lower.</p><h3>Where automation fails</h3><p>Automation enables changes to be added to the base map without much human intervention. Essentially, new location data containing additions, modifications or deletions to the map comes as a data set, after which it’s lumped together and added onto the current map.</p><p>Once the data has been ingested, the map can then be cleaned up for minor inaccuracies such as misspelled street names. This works reasonably well in a city like NYC, which is already more or less established. Changes usually amount to the closure of a road or opening of a new shop at the most.</p><p>However, King explains, a map is like a patchwork quilt of data — made up from several different sources that vary significantly from each other in terms of quality but can work together with careful crafting.</p><p>To lump together sources and automate ingestion of this data by the map without analyzing the quality of each source would mean risking the degradation of data and sacrificing quality. At the same time, examining each new change for quality makes the process painfully slow, causing valuable source material to be left unused or get so old it’s no longer useful.</p><h3>One step closer</h3><p>To address the downsides of automation and help update maps for boomtowns quicker than manual processes allow, King and his colleagues created a new tool. Known as the Proactive Sourcing tool (PAS), it compares the incoming data with changes against the data currently being reflected on the map.</p><p>To put it simply, if every delivery from a source is compared to the original base map, there will always be a lot of differences, TomTom Regional Sourcing Specialist Thomas Byker tells me. So, PAS takes the newest data from a source and compares it against the last delivered version, and then you only see the smaller changes that the source provider has added within that time period. This means that the editing process can remain hyper focused on the changes that are freshly happening in a specific area.</p><p>This new approach promises faster returns than complete automation. When it comes to accuracy, maps updated by PAS using source material can only be as accurate as the source data itself, which is highly variable. In rapidly growing suburban areas especially, obstructions like tree cover combined with mountainous topography can make it difficult to quickly assess the quality of source data, according to TomTom Regional Sourcing Specialist Kurt McClure.</p><p>So, while PAS could help keep up with how fast cities like Boise expand, there is still scope to address accuracy. As it turns out, that’s possible using another in-house map editor.</p><h3>A collaborative approach to map editing</h3><p>Since October 2020, King’s team has been using Vertex, a visual map editor designed to ensure both freshness and overall quality of map data for TomTom and its partners.</p><p>“We wanted to take a more proactive approach to map editing. We saw the need for a tool to process numerous high-quality leads and sources at a faster speed. So, we provided a semi-automated solution that empowers mapmakers instead of having them depend on automated processes, especially in high-growth areas,” says Nochumson, who manages the day-to-day development of the tool.</p><p>Using a combination of local knowledge, aerial imagery and probe data, Vertex automatically proposes map updates to human editors — who then have the option to accept or reject them.</p><p>King’s team already has data from countless different sources made available for ingestion by the PAS tool. By importing it into Vertex as an editable layer, this data can act as a base for the proposed changes.</p><p>Think of it as a dish with ingredients sourced from different places. Map data prepared by PAS, when entered in what is called the Automated Road Tool (ART) layer in Vertex, results in map changes for editors to consider. Editors can also adjust the dish to their taste, by incorporating elements like missing or incorrect street names.</p><p>In a little over a year, the ART has generated over 50,000 kilometers of new road updates for editors to consider, not limited to Boise, but also including other similar geographies like Denton, Texas. This is a vast improvement from complete automation, the method mapmakers relied on earlier, which risked maps going stale in areas like Boise due to the varying quality of source data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*HpoNNUAkW0P6L_1w.jpg" /></figure><p>Boise has been developing rapidly over the past few years. Using the ART layer in Vertex, TomTom mapmakers can make map edits in a much easier and faster way.</p><p>According to TomTom Senior Project Manager David Salmon, Vertex allows for a faster turnaround due to lower barriers to entry. “We can now do away with weeks and weeks of editing training, wherein we had to prepare the map to automatically ingest not just source data, but also specific attributes such as POI data or lane attribution on roads. By adding the ART layer in Vertex, anybody within TomTom can contribute to map freshness. And since the sourcing operations team is instantly alerted of this change, they can get in the data much faster, improving the map editing cycle.”</p><p>Of course, there is the question of how efficient this process really is if each proposed change needs to be manually approved. As Salmon sees it, the updates proposed by ART are much smaller in volume than the large-scale updates made by automated processes in maintenance geographies.</p><p>“In a single city like Boise, we might only be adding 10 new streets on a given day, allowing us to really focus on the minute details.”</p><p>While the process that led to its adoption might seem complex, using Vertex to keep maps fresh and accurate is as simple as it sounds.</p><p>As the world expands and several big cities fall prey to housing crises, people are increasingly choosing to migrate to smaller towns. Using this map editing technique, TomTom mapmakers can help them make informed decisions about where to build their new life, and easily find their way around their new city.</p><h3>Learn more</h3><p>To get started mapping with TomTom Maps APIs and SDKs, <a href="http://developer.tomtom.com/">register for a free acount</a> and API key on our developer portal.</p><p>For more reading, learn more about TomTom’s <a href="https://www.tomtom.com/blog/maps/map-editing-partnership-program/">Map Editing Partnership program</a> and our <a href="https://www.tomtom.com/products/map-technology/">map technology</a>.</p><p><em>Note: This article originally appeared on the TomTom blog. The article can be found </em><a href="https://www.tomtom.com/blog/maps/how-mapmakers-keep-on-top-of-boomtowns/"><em>here</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1e5045830bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tomtom-developers/how-collaborative-map-editing-can-keep-maps-fresh-in-high-growth-areas-c1e5045830bd">How Collaborative Map Editing can keep Maps Fresh in High-growth Areas</a> was originally published in <a href="https://medium.com/tomtom-developers">TomTom Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding TomTom Maps to a Gatsby App]]></title>
            <link>https://medium.com/tomtom-developers/adding-tomtom-maps-to-a-gatsby-app-b83a2c7eef8a?source=rss----9c5d61983c4b---4</link>
            <guid isPermaLink="false">https://medium.com/p/b83a2c7eef8a</guid>
            <category><![CDATA[mapping]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[gatsbyjs]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[location]]></category>
            <dc:creator><![CDATA[TomTom Developers]]></dc:creator>
            <pubDate>Fri, 19 Aug 2022 20:21:42 GMT</pubDate>
            <atom:updated>2022-07-14T20:20:33.857Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A7EBoKf0mtfZYXHRSx6X8A.jpeg" /></figure><p>These days, maps are an essential feature of many web applications. More platforms are starting to offer services that use location technology. TomTom enables you to integrate location-based features into your web applications through its software development kits (SDKs) and APIs with just a few lines of code and minimal development time.</p><p>The TomTom Maps SDK integrates capably with many popular front-end frameworks — including Gatsby, an open-source static website generator that you can use to build progressive web apps that are secure and optimized for speed. Pairing the TomTom Maps SDK with Gatsby enables you to create optimized, interactive maps with ease.</p><p>In this tutorial, we’ll demonstrate how to integrate TomTom maps into a Gatsby site using modern React practices like <a href="https://reactjs.org/docs/refs-and-the-dom.html">refs</a>. We’ll also see how to display data from an external source on the map. Finally, we’ll explore how to build routes to and from specific destinations that can be altered based on the type of goods being transported.</p><h3>Prerequisites</h3><p>To follow this tutorial, you’ll need to have:</p><ul><li>A basic understanding of React.</li><li>Node.js installed on your computer.</li><li>A developer account with TomTom and an API key to authorize your request to use the service.</li></ul><h3>Setting Up a New Gatsby App</h3><p>To create a new Gatsby app, we need the Gatsby command-line interface (CLI) installed on your computer. This will enable you to run the commands for developing Gatsby sites.</p><p>To install the CLI, open up a terminal on your machine and run the following command. It installs the CLI globally or updates your version to the most recent release.</p><p>npm install -g gatsby-cli</p><p>Next, use the cd command to navigate to where you want to create your Gatsby site. For example:</p><p>cd Desktop</p><p>To create the Gatsby site, we’ll use a Gatsby starter template. This premade template enables us to get started with development quickly. In this tutorial, we’ll use Gatsby’s official <a href="https://www.gatsbyjs.com/starters/gatsbyjs/gatsby-starter-hello-world">hello world starter</a>.</p><p>Inside the directory for your site, run this command (replacing name-of-your-project-here with your project name):</p><pre>npx gatsby new name-of-your-project-here <a href="https://github.com/gatsbyjs/gatsby-starter-hello-world">https://github.com/gatsbyjs/gatsby-starter-hello-world</a></pre><p>When the installation is complete, you should see this message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/0*qe-MTKv0iZ2tAp0K.jpg" /></figure><p>Go to the directory you created for the site and run gatsby develop, which will launch a development server where you can preview your site. You can view it at <a href="http://localhost:8000/">http://localhost:8000</a> in a web browser. The result should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*RK3_bVZ_IA8jhT_l.jpg" /></figure><h3>Adding a TomTom Map</h3><p>With the Gatsby app now up and running, we’re set to add a TomTom map to our site. First, we’ll need the TomTom Maps Web SDK installed in our project.</p><p>In the terminal, in the root directory of the site, run the command below to install the SDK and its dependencies:</p><p>npm install @tomtom-international/web-sdk-maps</p><p>With the SDK installed, it’s time to write out the code to display a TomTom map. Open the index.js file within the src/pages folder of your Gatsby app. Clear all the code inside it and populate it with the following code:</p><pre>import * as React from &quot;react&quot;<br>import { useEffect, useRef } from &quot;react&quot;</pre><pre>// TomTom SDK<br>import * as tt from &quot;<a href="http://twitter.com/tomtom">@tomtom</a>-international/web-sdk-maps&quot;<br>import &quot;<a href="http://twitter.com/tomtom">@tomtom</a>-international/web-sdk-maps/dist/maps.css&quot;</pre><p>This imports the resources we’ll need to display a TomTom map on a React site, including the useEffect and useRef React hooks along with the TomTom maps JavaScript SDK and its default stylesheet.</p><p>Next, we define the functional component Home where the application will live.</p><pre>export default function Home() {<br>  const API_KEY = &quot;YOUR_API_KEY&quot;<br>  const AMSTERDAM = { lon: 4.896029, lat: 52.371807 }</pre><pre>const map = useRef()<br>const mapContainer = useRef()</pre><pre>useEffect(() =&gt; {<br>    map.current = tt.map({<br>      key: API_KEY,<br>      container: mapContainer.current.id,<br>      center: AMSTERDAM,<br>      zoom: 10,<br>      language: &quot;en-GB&quot;,<br>    })</pre><pre>map.current.addControl(new tt.FullscreenControl())<br>    map.current.addControl(new tt.NavigationControl())</pre><pre>return () =&gt; {<br>      map.current.remove()<br>    }<br>    //eslint-disable-next-line<br>  }, [])</pre><pre>return (<br>    &lt;div className=&quot;&quot;&gt;<br>      &lt;div className=&quot;container&quot;&gt;<br>        &lt;nav className=&quot;nav&quot;&gt;<br>          &lt;h1&gt; TomTom Maps in Gatsby&lt;/h1&gt;<br>        &lt;/nav&gt;<br>        &lt;div ref={mapContainer} className=&quot;map&quot; id=&quot;map&quot; /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>There’s quite a lot going on in the code above, so let’s break it down.</p><p>First, the variables API_KEY and AMSTERDAM store the value of the TomTom API key, which you’ll need to use the service. It also includes the longitude and latitude coordinates of Amsterdam in the Netherlands, our sample location, so the map can be centered around it.</p><p>Remember to replace YOUR_API_KEY with the API key from your TomTom developer account.</p><p>The useRef hook defines the variables map and mapContainer, which stores references to our map and the DOM element it’s embedded within. This is necessary because React works with something called the <a href="https://reactjs.org/docs/faq-internals.html#what-is-the-virtual-dom">virtual DOM</a>, which is a virtual representation of the real DOM. We can’t render a TomTom map to a piece of React’s virtual DOM — we have to work with actual DOM elements, which can only be accessed through refs.</p><p>These variables are defined as refs and not regular JavaScript variables because in React the entire component is re-rendered whenever a variable is updated, leading to data loss in the component. Since we don’t want to lose this data, we wrap them in refs so that their value persists between component re-renders and you can update their values without a re-render.</p><p>The useEffect hook initiates a TomTom map on page load by calling the tt.map function with the necessary configurations. These configurations include our API key, the container parameter that takes the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id">ID</a> of the HTML element the map is to be embedded in, and the center parameter that centers the map around Amsterdam. Note how all it takes to initialize a TomTom map is calling a function!</p><p>Finally, the return statement returns the HTML for the browser to display.</p><p>At this stage, we’ve now successfully added a TomTom map to our Gatsby site. However, the site would be a bit bleak if it were viewed right now. To solve this, we’ll create a new CSS file in the src folder called styles.css. Note that if you wish to name yours something else, you’ll need to ensure it is imported correctly into your React component.</p><p>Once we’ve created the file, we populate it with the following CSS styles:</p><pre>* {<br>  padding: 0;<br>  margin: 0;<br>  box-sizing: border-box;<br>}<br>.container {<br>  width: 100vw;<br>  height: 100vh;<br>  display: flex;<br>  flex-direction: column;<br>  justify-content: space-around;<br>  align-items: center;<br>  position: relative;<br>}</pre><pre>.nav {<br>  display: flex;<br>  justify-content: space-around;<br>  align-items: center;<br>  width: 100%;<br>  height: 10%;<br>  background-color: #000;<br>  color: #ffffff;<br>}</pre><pre>.nav h1 {<br>  padding-top: 0.3125rem;<br>  padding-bottom: 0.3125rem;<br>  margin-right: 1rem;<br>  font-size: 1.25rem;<br>  text-decoration: none;<br>  white-space: nowrap;<br>}</pre><pre>.map {<br>  width: 100%;<br>  height: 90%;<br>}</pre><p>Now, import the stylesheet at the top of the index.js file, which applies styles to make it look better than un-styled HTML.</p><pre>// CSS styles<br>import &quot;../styles.css&quot;</pre><p>With the development server running, save the new changes and go to localhost:8000 in a web browser. When the page updates, it should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/0*GOx4h5KdM8M_ur1t.jpg" /></figure><h3>Adding Markers to a TomTom Map</h3><p>TomTom lets us display a range of information on a map, including geofences, navigation routes, images, and videos. It also lets us display <a href="https://developer.tomtom.com/maps-sdk-web-js/documentation#Maps.Marker">markers</a>, which are customizable icons that add information and interactivity to our maps.</p><p>To demonstrate, let’s use markers to show the locations of some top-rated restaurants in Amsterdam. In the src folder, create a JSON file called stores.json, and enter the following code:</p><pre>[<br>{<br>&quot;coordinates&quot;: [<br>4.88427,<br>52.37243<br>],<br>&quot;address&quot;: &quot;Reestraat 8, 1016 DN Amsterdam&quot;<br>},<br>{<br>&quot;coordinates&quot;: [<br>4.87631,<br>52.36366<br>],<br>&quot;address&quot;: &quot;Eerste Helmersstraat 33, 1054 CZ Amsterdam&quot;<br>},<br>{<br>&quot;coordinates&quot;: [<br>4.94036,<br>52.36357<br>],<br>&quot;address&quot;: &quot;Javaplein 23, 1095 CJ Amsterdam&quot;<br>},<br>{<br>&quot;coordinates&quot;: [<br>4.92089,<br>52.38213<br>],<br>&quot;address&quot;: &quot;Gedempt Hamerkanaal 201, 1021 KP Amsterdam&quot;<br>},<br>{<br>&quot;coordinates&quot;: [<br>4.91191,<br>52.36619<br>],<br>&quot;address&quot;: &quot;Plantage Middenlaan 30A, 1018 DG Amsterdam&quot;<br>},<br>{<br>&quot;coordinates&quot;: [<br>4.87896,<br>52.37257<br>],<br>&quot;address&quot;: &quot;Rozengracht 133A, 1016 LV Amsterdam&quot;<br>}<br>]</pre><p>Here, we have an array of objects, where each object has the property of a coordinate. This coordinate is an array that stores the longitude and latitude coordinates of the location — here, a restaurant — and its street address. These coordinates are obtained from the Fuzzy Search service in TomTom’s <a href="https://developer.tomtom.com/search-api/api-explorer">API Explorer</a>, which returns geolocational data of an address, such as longitude and latitude coordinates and points of interest (POIs).</p><p>At the top of the index.js file, below the import statements, import the JSON file:</p><p>Import stores from &quot;../stores.json&quot;</p><p>Now, to display the markers on the page, paste the code below in the useEffect hook just above the return statement.</p><pre>stores.map((store) =&gt; {<br>      const address = store?.address<br>      const location = store?.coordinates<br>      return new tt.Marker()<br>        .setLngLat(location)<br>        .setPopup(new tt.Popup({ offset: 35 }).setHTML(address))<br>        .addTo(map.current)<br>    })</pre><p>The code above uses the JavaScript map method to iterate over the array from the JSON file that stores the details of the restaurants. For each restaurant it does the following:</p><ul><li>Retrieves its address and coordinates.</li><li>Creates a new marker by calling the tt.Marker class.</li><li>Sets that marker around the restaurant’s geographical location by passing the restaurant’s longitude and latitude coordinates to the setLngLat method.</li><li>Calls the setPopup method, which will display a cancelable popup that shows the restaurant address when the marker is clicked.</li><li>Attaches the marker to the map.</li></ul><p>Viewed in a browser, the restaurant locations are now displayed as markers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*INwZy82sQdm4ZfWD.jpg" /></figure><p>Clicking on a marker displays the popup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*chv4O41QOv-8K1mE.jpg" /></figure><h3>Routing</h3><p>Among the many features TomTom offers to developers through its SDKs, routing is one of the most valuable and easy to implement. For example, in a ride-sharing application, how can drivers identify the best routes to their destination? Or for someone working in deliveries, how can they optimize their daily route? In both of these instances, access to information on the route is vital.</p><p>TomTom’s Calculate Route service solves this with the Routing API, which determines possible routes between two locations based on specific parameters, like the type of vehicle, the load it’s carrying, and the driver’s estimated time of arrival.</p><p>To demonstrate routing with TomTom, let’s make a delivery route between two restaurants that will be altered if the vehicle is carrying hazardous kitchen products, like propane for grills.</p><p>First, we need to install TomTom’s web services SDK, which lets us integrate TomTom services on our project, as they aren’t offered by the TomTom Maps Web SDK.</p><p>In the terminal, within the root directory of your site, run this command:</p><p>npm install @tomtom-international/web-sdk-services</p><p>Once it’s installed, add this to the top of your index.js file to import it.</p><p>import * as tts from &quot;@tomtom-international/web-sdk-services&quot;</p><p>You can now start writing out the code to calculate the route.</p><p>In the Home component, just above the useEffect hook where the map is initialized, declare the function createRoute:</p><pre>function createRoute() { <br>    ...<br>}</pre><p>Next, within the function, insert the following object:</p><pre>const routeOptions = {<br>      key: API_KEY,<br>      locations: [<br>        [4.87631, 52.36366],<br>        [4.91191, 52.36619],<br>      ],<br>      travelMode: &quot;truck&quot;,<br>      vehicleEngineType: &quot;electric&quot;,<br>      vehicleCommercial: true,<br>    }</pre><p>This object contains the configurations that are being passed to the Calculate Route service, like the API key that authorizes the service, the longitude and latitude coordinates of the two restaurants the route is to be constructed around, the type of vehicle on the route (here, a truck), or the engine type of the vehicle.</p><p>Below the routeOptions object, insert this code:</p><pre>tts.services.calculateRoute(routeOptions).then(response =&gt; {<br>      console.log(response.toGeoJson())<br>      console.log(response)<br>      var geojson = response.toGeoJson()<br>      map.current.addLayer({<br>        id: &quot;route&quot;,<br>        type: &quot;line&quot;,<br>        source: {<br>          type: &quot;geojson&quot;,<br>          data: geojson,<br>        },<br>        paint: {<br>          &quot;line-color&quot;: &quot;#a51414&quot;,<br>          &quot;line-width&quot;: 8,<br>        },<br>      })</pre><pre>var bounds = new tt.LngLatBounds()<br>      geojson.features[0].geometry.coordinates.forEach(function (point) {<br>        bounds.extend(tt.LngLat.convert(point)) // creates a bounding area<br>      })<br>      map.current.fitBounds(bounds, {<br>        duration: 300,<br>        padding: 50,<br>        maxZoom: 14,<br>      }) // zooms the map to the searched route<br>    })</pre><p>Here, the tts.services.calculateRoute function calls the calculate route service, passing the routeOptions object as an argument. This creates the route, draws its path on the map, and zooms in on it.</p><p>Next, we need to be able to call the service on our site. Insert this code into the HTML that the Home component returns:</p><pre>&lt;button<br>    className=&quot;btn&quot;<br>    onClick={e =&gt; {<br>    e.preventDefault()<br>        createRoute()<br>    }}<br>    &gt;<br>      calculate route<br>&lt;/button&gt;</pre><pre>Add these CSS styles to the styles.css file:</pre><pre>.btn {<br>  position: fixed;<br>  bottom: 4rem;<br>  left: 50%;<br>  border-radius: 0.5rem;<br>  transform: translate(-50%, 0);<br>  border: none;<br>  padding: 1.2rem 1rem;<br>  background: #000;<br>  color: #fff;<br>  font-size: 1.3rem;<br>  cursor: pointer;<br>}</pre><p>Now, clicking the <strong>calculate route</strong> button will now call the Calculate Route service and construct a route between the two restaurant markers on the map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*u08Eq2RzT4x_Pn6O.jpg" /></figure><p>To prove that the route between the two markers changes based on the type of load specified in the truck, add this property to the routeOptions object:</p><p>vehicleLoadType: [&quot;otherHazmatHarmfulToWater&quot;]</p><p>This property lets you specify what type of goods are in the vehicle. Passing on that value to the array tells the Calculate Route service that the truck is loaded with goods that are water pollutants. As a result, the service constructs a different route the vehicle can take to avoid proximity to water.</p><p>Here’s the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*LIzt1ncuQCGfQZHP.jpg" /></figure><h3>Wrapping Up</h3><p>In this tutorial, we built a web application with Gatsby that displays a TomTom map and constructs an alterable route between two marker locations using TomTom’s Maps Web SDK.</p><p>If you want to integrate such features into your application, there’s no better location technology provider than TomTom. <a href="https://developer.tomtom.com/user/register">Sign up for a free developer account</a> to integrate TomTom’s location services into your application today. Happy mapping!</p><p><em>This article was originally published at </em><a href="https://developer.tomtom.com/blog">developer.tomtom.com/blog</a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b83a2c7eef8a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tomtom-developers/adding-tomtom-maps-to-a-gatsby-app-b83a2c7eef8a">Adding TomTom Maps to a Gatsby App</a> was originally published in <a href="https://medium.com/tomtom-developers">TomTom Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using the Snap to Roads API with React]]></title>
            <link>https://medium.com/tomtom-developers/using-the-snap-to-roads-api-with-react-7ab9820218ba?source=rss----9c5d61983c4b---4</link>
            <guid isPermaLink="false">https://medium.com/p/7ab9820218ba</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[developer]]></category>
            <dc:creator><![CDATA[TomTom Developers]]></dc:creator>
            <pubDate>Fri, 19 Aug 2022 17:36:45 GMT</pubDate>
            <atom:updated>2022-07-25T18:32:38.572Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mhlbne3WMpiP4DnszpXkrw.jpeg" /></figure><p>TomTom’s Snap to Roads API uses GPS data to reconstruct driver journeys. The API matches location data with road network information to determine the most probable route.</p><p>The Snap to Roads API also takes other factors into account, such as what type of vehicle is being driven, speed limits, lanes, and the amount of time it has previously taken the driver to reach various locations. These factors are sent as parameters by the REST API.</p><p>You can also record multiple point coordinates along the driver’s journey. Then, we can take these point coordinates and send them to the API, which takes the coordinates and returns relevant information about the coordinate routes. The API’s response can also include more descriptive details on the road traveled, such as names, types of roads, speed restrictions, class of road, etc.</p><p>Snap to Roads allows for smooth visualization of relevant information in ride-hailing services and on-demand delivery applications. It’s also useful for route tracking in fleet logistics and insurance applications. You can use it for information about road attributes, such as speed limit, elevation, and road ownership.</p><p>In this article, we’ll build a demo in which we’ll input two location coordinates, send this information to the Snap to Roads API, and draw the returned routes on our TomTom maps. This will provide a helpful visual representation of the new routes and how to use them.</p><h3>Getting Started</h3><p>There are many ways to spin up a React application, but it’s advisable to use the <a href="https://github.com/facebook/create-react-app">Create React App</a> (CRA) library.</p><p>Let’s jump straight to the code. To create a React app using <a href="https://github.com/facebook/create-react-app">Create React App</a>, make sure you currently have Node.js installed. You can check to see if you have Node.js installed by typing the following into your terminal:</p><pre>node -v</pre><p>If Node.js is installed, that command should return the current version. If not, go to the Node.js website and <a href="https://nodejs.org/en/download/">download the latest version</a>.</p><p>Next, go into the terminal/command prompt and initiate your app using the name.</p><pre>npx create-react-app snap-to-road</pre><p>Navigate into your project folder:</p><pre>cd snap-to-road</pre><p>You can now start the project:</p><pre>npm start</pre><p>You need to be able to send API requests with your endpoints, so you need an API key from TomTom maps. <a href="https://developer.tomtom.com/user/login">Sign in to TomTom</a>, generate an API key, and edit it to enable the Snap to Roads API:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*0tBUJHE7HKZ0lUUX.jpg" /></figure><h3>Installation</h3><p>Before you can use TomTom in your app, you’ll have to install the TomTom package and <a href="https://github.com/axios/axios">axios</a>:</p><pre>npm install @tomtom-international/web-sdk-maps -save</pre><p>Axios will allow us to make API requests to the Snap to Roads API:</p><pre>npm i axios</pre><h3>Adding the TomTom Map</h3><p>Now, let’s go into the component where we will create the map:</p><pre>1import &quot;./styles.css&quot;;</pre><pre>2import &quot;@tomtom-international/web-sdk-maps/dist/maps.css&quot;;</pre><pre>3import * as ttmaps from &quot;@tomtom-international/web-sdk-maps&quot;;</pre><pre>4import { useState, useEffect, useRef } from &quot;react&quot;;</pre><pre>5</pre><pre>6export default function App() {</pre><pre>7  const mapElement = useRef();</pre><pre>8  const [mapZoom, setMapZoom] = useState(17);</pre><pre>9  const [map, setMap] = useState({});</pre><pre>10</pre><pre>11  useEffect(() =&gt; {</pre><pre>12    let map = ttmaps.map({</pre><pre>13      key: &quot;{{TOMTOM_API_KEY}}&quot;,</pre><pre>14      container: mapElement.current,</pre><pre>15      center: [12.3, 32.992578],</pre><pre>16      zoom: mapZoom</pre><pre>17    });</pre><pre>18    setMap(map);</pre><pre>19    return () =&gt; map.remove();</pre><pre>20  }, []);</pre><pre>21</pre><pre>22  return (</pre><pre>23    &lt;div className=&quot;App&quot;&gt;</pre><pre>24      &lt;div ref={mapElement} className=&quot;mapDiv&quot;&gt;&lt;/div&gt;</pre><pre>25    &lt;/div&gt;</pre><pre>26  );</pre><pre>27}</pre><p>This imports the TomTom library and displays it in the DOM using React’s useRef.</p><p>Next, import the TomTom library and default CSS styles into App.js. You’ll also import useState and useEffect.</p><p>You need to add certain values, like the map zoom value and the map itself using useState. Then, you can initialize the map with useEffect and display it with mapElement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tvnBW_VlLOY3GCne.jpg" /></figure><h3>Using the Snap to Roads API</h3><p>Now, let’s say we’re moving from point A (4.6104, 52.3757) to point B (4.6140, 52.3834). As we send these coordinates to the API, we also send two parameters: fields and key (our API key). The fields object contains the specific information you need from the API endpoint. For this example, this appears as follows:</p><pre>1{</pre><pre>2    projectedPoints {</pre><pre>3        type,</pre><pre>4        geometry {</pre><pre>5            type,</pre><pre>6            coordinates</pre><pre>7        },</pre><pre>8        properties {</pre><pre>9            routeIndex</pre><pre>10        }</pre><pre>11    }, route {</pre><pre>12        type,</pre><pre>13        geometry {</pre><pre>14            type,</pre><pre>15            coordinates</pre><pre>16        },</pre><pre>17        properties {</pre><pre>18            id,</pre><pre>19            speedRestrictions {</pre><pre>20                maximumSpeed {</pre><pre>21                    value,</pre><pre>22                    unit</pre><pre>23                }</pre><pre>24            }</pre><pre>25        }</pre><pre>26    }</pre><pre>27}</pre><p>You can also find more nested fields sample objects in our <a href="https://developer.tomtom.com/snap-to-roads-api/api-explorer">documentation</a>.</p><p>Let’s get back to the code. Within the component, import axios and create a getSnapFunction that makes a request to the API.</p><pre>1import axios from &quot;axios&quot;</pre><pre>2</pre><pre>3const getSnapFunction = () =&gt; {</pre><pre>4    axios.get(&quot;https://api.tomtom.com/snap-to-roads/1/snap-to-roads?points=4.6104,52.3757;4.6140,52.393&amp;fields={projectedPoints{type,geometry{type,coordinates},properties{routeIndex}},route{type,geometry{type,coordinates},properties{id,speedRestrictions{maximumSpeed{value,unit}}}}}&amp;key=8h504Wc4AXL6OPndqhrtKf70AovVBL3V&quot;).then((res) =&gt;</pre><pre>5    {</pre><pre>6     console.log(res.data)</pre><pre>7     res.data.route.forEach(</pre><pre>8      (item) =&gt; {</pre><pre>9        map.addLayer({</pre><pre>10          id: Math.random().toString(),</pre><pre>11          type: &quot;line&quot;,</pre><pre>12          source: {</pre><pre>13            type: &quot;geojson&quot;,</pre><pre>14            data: {</pre><pre>15              type: &quot;FeatureCollection&quot;,</pre><pre>16              features: [</pre><pre>17                {</pre><pre>18                  type: &quot;Feature&quot;,</pre><pre>19                  geometry: {</pre><pre>20                    type: &quot;LineString&quot;,</pre><pre>21                    properties: {},</pre><pre>22                    coordinates: item.geometry.coordinates</pre><pre>23                  }</pre><pre>24                }</pre><pre>25              ]</pre><pre>26            }</pre><pre>27          },</pre><pre>28          layout: {</pre><pre>29            &quot;line-cap&quot;: &quot;round&quot;,</pre><pre>30            &quot;line-join&quot;: &quot;round&quot;</pre><pre>31          },</pre><pre>32          paint: {</pre><pre>33            &quot;line-color&quot;: &quot;#ff0000&quot;,</pre><pre>34            &quot;line-width&quot;: 2</pre><pre>35          }</pre><pre>36        });</pre><pre>37      }</pre><pre>38     )</pre><pre>39       map.setCenter([parseFloat(4.6104), parseFloat(52.3757)]);</pre><pre>40   }).catch((err) =&gt; console.log(err))</pre><pre>41  }</pre><p>This returns the reconstructed route. Then, it loops this response through the route array.</p><p>Next, we used map.addLayer to draw each property of the array on the map. It now forms the full route, taking you from the takeoff point to the destination.</p><p>Finally, map.setCenter enables us to center the map on the route. Here’s the final map:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*71B6Q6MNeHR0qLr_.jpg" /></figure><p>We’ve just covered the Synchronous Snap to Roads API. However, there’s also an Asynchronous Snap to Roads API, where users make a POST request and get back a batch ID. While making this request, we will send the several coordinate points and the query property within the body.</p><pre>1axios.post(&#39;https://api.tomtom.com/snap-to-roads/batch/1?key={TOMTOM_API_KEY}&#39;, {</pre><pre>2  {</pre><pre>3  batchItems: [</pre><pre>4    {</pre><pre>5      query: &quot;/snap-to-roads?fields={projectedPoints{type,geometry{type,coordinates},properties{routeIndex}},route{type,geometry{type,coordinates},properties{id,speedRestrictions{maximumSpeed{value,unit}},address{roadName,roadNumbers,municipality,countryName,countryCode,countrySubdivision},elementType,traveledDistance,privateRoad,partOfTunnel,frc,formOfWay,roadUse,laneInfo{numberOfLanes},heightInfo{height,chainage},trafficSign{signType,chainage},trafficLight}},distances{total,ferry,privateRoad,publicRoad,road,offRoad}}&amp;vehicleType=PassengerCar&amp;measurementSystem=imperial&quot;,</pre><pre>6      post: {</pre><pre>7        points: [</pre><pre>8          {</pre><pre>9            type: &quot;Feature&quot;,</pre><pre>10            geometry: {</pre><pre>11              type: &quot;Point&quot;,</pre><pre>12              coordinates: [</pre><pre>13                19.4389141359581,</pre><pre>14                51.78057462411982</pre><pre>15              ]</pre><pre>16            }</pre><pre>17          },</pre><pre>18          {</pre><pre>19            type: &quot;Feature&quot;,</pre><pre>20            geometry: {</pre><pre>21              type: &quot;Point&quot;,</pre><pre>22              coordinates: [</pre><pre>23                19.439257458711324,</pre><pre>24                51.78057794294989</pre><pre>25              ]</pre><pre>26            }</pre><pre>27          },</pre><pre>28          {</pre><pre>29            type: &quot;Feature&quot;,</pre><pre>30            geometry: {</pre><pre>31              type: &quot;Point&quot;,</pre><pre>32              coordinates: [</pre><pre>33                19.43963296797358,</pre><pre>34                51.78064100067553</pre><pre>35              ]</pre><pre>36            }</pre><pre>37          },</pre><pre>38          {</pre><pre>39            type: &quot;Feature&quot;,</pre><pre>40            geometry: {</pre><pre>41              type: &quot;Point&quot;,</pre><pre>42              coordinates: [</pre><pre>43                19.44012113001449,</pre><pre>44</pre><pre>45</pre><pre>46</pre><pre>47</pre><pre>48</pre><pre>49</pre><pre>50</pre><pre>5151.780690783028064</pre><pre>52              ]</pre><pre>53            }</pre><pre>54          }</pre><pre>55        ]</pre><pre>56      }</pre><pre>57    },</pre><pre>58    {</pre><pre>59      &quot;query&quot;: &quot;/snap-to-roads?fields={projectedPoints{type,geometry{type,coordinates},properties{routeIndex}},route{type,geometry{type,coordinates},properties{id,speedRestrictions{maximumSpeed{value,unit}},address{roadName,roadNumbers,municipality,countryName,countryCode,countrySubdivision},elementType,traveledDistance,privateRoad,partOfTunnel,frc,formOfWay,roadUse,laneInfo{numberOfLanes},heightInfo{height,chainage},trafficSign{signType,chainage},trafficLight}},distances{total,ferry,privateRoad,publicRoad,road,offRoad}}&amp;vehicleType=PassengerCar&amp;measurementSystem=metric&quot;,</pre><pre>60      post: {</pre><pre>61        points: [</pre><pre>62          {</pre><pre>63            type: &quot;Feature&quot;,</pre><pre>64            geometry: {</pre><pre>65              type: &quot;Point&quot;,</pre><pre>66              coordinates: [</pre><pre>67                19.4389141359581,</pre><pre>68                51.78057462411982</pre><pre>69              ]</pre><pre>70            }</pre><pre>71          },</pre><pre>72          {</pre><pre>73            type: &quot;Feature&quot;,</pre><pre>74            geometry: {</pre><pre>75              type: &quot;Point&quot;,</pre><pre>76              coordinates: [</pre><pre>77                19.439257458711324,</pre><pre>78                51.78057794294989</pre><pre>79              ]</pre><pre>80            }</pre><pre>81          },</pre><pre>82          {</pre><pre>83            type: &quot;Feature&quot;,</pre><pre>84            geometry: {</pre><pre>85              type: &quot;Point&quot;,</pre><pre>86              coordinates: [</pre><pre>87                19.4389141359581,</pre><pre>88                51.78057462411982</pre><pre>89              ]</pre><pre>90            }</pre><pre>91          },</pre><pre>92          {</pre><pre>93            type: &quot;Feature&quot;,</pre><pre>94            geometry: {</pre><pre>95              type: &quot;Point&quot;,</pre><pre>96              coordinates: [</pre><pre>97                19.439257458711324,</pre><pre>98                51.78057794294989</pre><pre>99              ]</pre><pre>100            }</pre><pre>101          },</pre><pre>102          {</pre><pre>103            type: &quot;Feature&quot;,</pre><pre>104            geometry: {</pre><pre>105              type: &quot;Point&quot;,</pre><pre>106              coordinates: [</pre><pre>107                19.43963296797358,</pre><pre>108                51.78064100067553</pre><pre>109              ]</pre><pre>110            }</pre><pre>111          },</pre><pre>112          {</pre><pre>113            type: &quot;Feature&quot;,</pre><pre>114            geometry: {</pre><pre>115              type: &quot;Point&quot;,</pre><pre>116              coordinates: [</pre><pre>117                19.44012113001449,</pre><pre>118                51.780690783028064</pre><pre>119              ]</pre><pre>120            }</pre><pre>121          }</pre><pre>122        ]</pre><pre>123      }</pre><pre>124    }</pre><pre>125  ]</pre><pre>126}</pre><pre>127})</pre><p>The response will contain a batch ID:</p><pre>1{</pre><pre>2    &quot;batchId&quot;: &quot;16178e70-8331-459f-abc8-251e708f5edb&quot;</pre><pre>3}</pre><p>We now take this batch ID and send another request to another endpoint, checking the status of our Snap API request:</p><pre>axios.get(&#39;https://api.tomtom.com/snap-to-roads/batch/1/c435cae3-c8f2-4d76-b08b-304529c967eb/status?key={TOMTOM_KEY}&#39;).then((res) =&gt; console.log(res.data)).catch((err) =&gt; console.log(err)</pre><p>If it’s ready, it will return Completed.</p><pre>1{</pre><pre>2  &quot;state&quot;: &quot;Completed&quot;,</pre><pre>3  &quot;statistics&quot;: {</pre><pre>4    &quot;totalCount&quot;: 2,</pre><pre>5    &quot;successes&quot;: 2</pre><pre>6  }</pre><pre>7}</pre><p>As the processing of batch data may take some time to complete, it is important to check the status before attempting to obtain the route data. Attempting to download route data before processing has completed will result in an error.</p><p>Once the process is complete, you can get the route data by sending a GET request to the download endpoint. This sends a response with the route data. The route data will take the shape of the query property in the body of the POST request we sent earlier.</p><pre>axios.get(&#39;https://api.tomtom.com/snap-to-roads/batch/1/c435cae3-c8f2-4d76-b08b-304529c967eb?key={TOMTOM_KEY}&#39;).then((res) =&gt; console.log(res.data)).catch((err) =&gt; console.log(err)</pre><h3>Conclusion</h3><p>Now that you know how to use TomTom’s Snap to Roads API to retrieve relevant information about a set of route coordinates, and display the route on a map in our React app, you can start using this API in your own applications. For example, you could use this API to create a fleet logistics application that analyzes delivery drivers’ routes and speed. You can use this to determine how fast delivery orders are fulfilled.</p><p>Synchronous Snap to Roads is best for analyzing single trips. If you need to analyze batches of trips in one call, try Asynchronous Snap to Roads.</p><p>To learn more about each endpoint of this API, explore the following resources:</p><ul><li>Video: <a href="https://www.youtube.com/watch?v=Kq5aPrv3SCw">Track and manage assets while on the road</a></li><li><a href="https://developer.tomtom.com/snap-to-roads-api/documentation/snap-to-roads-api/synchronous-snap-to-roads">Synchronous Snap to Roads</a></li><li>Asynchronous Snap to Roads:</li><li><a href="https://developer.tomtom.com/snap-to-roads-api/documentation/snap-to-roads-api/asynchronous-snap-to-roads-submission">Submission:</a> Send an HTTPS POST request that responds with a unique job ID</li><li><a href="https://developer.tomtom.com/snap-to-roads-api/documentation/snap-to-roads-api/asynchronous-snap-to-roads-status">Status:</a> Check the status of a submitted job</li><li><a href="https://developer.tomtom.com/snap-to-roads-api/documentation/snap-to-roads-api/asynchronous-snap-to-roads-download">Download:</a> Download the results of your submission</li></ul><p>Visit the <a href="https://developer.tomtom.com/snap-to-roads-api/documentation/snap-to-roads-api/asynchronous-snap-to-roads-download">TomTom Developer Portal</a> to learn more about TomTom Maps.</p><p><em>This article was originally published at </em><a href="https://developer.tomtom.com/blog">developer.tomtom.com/blog</a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ab9820218ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tomtom-developers/using-the-snap-to-roads-api-with-react-7ab9820218ba">Using the Snap to Roads API with React</a> was originally published in <a href="https://medium.com/tomtom-developers">TomTom Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using TomTom Data to Improve Delivery Routes]]></title>
            <link>https://medium.com/tomtom-developers/using-tomtom-data-to-improve-delivery-routes-a9d178b2863?source=rss----9c5d61983c4b---4</link>
            <guid isPermaLink="false">https://medium.com/p/a9d178b2863</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[TomTom Developers]]></dc:creator>
            <pubDate>Tue, 24 May 2022 20:59:52 GMT</pubDate>
            <atom:updated>2022-05-23T13:42:45.273Z</atom:updated>
            <content:encoded><![CDATA[<h4>TomTom’s historical data, Routing API, and Search API help find the best route</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o_WDLs6K7UWqRrRnUww1Ow.jpeg" /></figure><p>Imagine a commercial bakery delivering to dozens of stores daily along fixed routes. The grocery stores expect to receive their goods on time, while the bakery wants to optimize its delivery routes. After all, when drivers arrive at their destinations more quickly, the bakery saves money on fuel, wages, and vehicles.</p><p>Route efficiency enables the bakery to expand its customer base. However, with continuously shifting traffic, construction, and road conditions changing, finding the optimal route can be incredibly challenging. This is precisely the type of problem that a data scientist can solve.</p><p>Building a tool to find the best route requires the data scientist to obtain — you guessed it — data. Luckily, TomTom’s wealth of historical traffic data can help pinpoint the average best route for any given time of day. A data scientist can combine this historical data with TomTom’s Routing API and Search API to create an easy-to-use app and help the bakery plan its ideal delivery routes.</p><p>This Python tutorial will use the Routing API to retrieve travel routes. The Search API will come in handy for obtaining the starting and destination point coordinates. We’ll use the two APIs to create a route adviser app for the drivers based on the shortest route.</p><h3>PREREQUISITES</h3><p>You’ll need a TomTom API key to follow this tutorial. Sign up for a <a href="https://developer.tomtom.com/user/register">freemium developer account</a> to obtain your key with thousands of daily requests. You can immediately use your account for commercial apps, then pay as you grow.</p><p>You will also need access to a notebook-based editor like <a href="https://jupyter.org/">Jupyter Notebook</a> or <a href="https://research.google.com/colaboratory/">Google Colab</a>.</p><h3>USING THE SEARCH API</h3><p>The Search API helps us find a location’s exact coordinates.</p><p>First, <a href="https://developer.tomtom.com/search-api/">get the Search API</a>. Next, go to the <strong>API Explorer</strong> tab to view the endpoints. We can get our coordinates using the Fuzzy Search endpoint. We’ll pass the location in the query parameter and set the response format (ext) to JSON.</p><p>Our endpoint URL is:</p><pre><a href="https://api.tomtom.com/search/2/search/Los%20Angeles.json?minFuzzyLevel=1&amp;maxFuzzyLevel=2&amp;view=Unified&amp;relatedPois=off&amp;key=*****">https://api.tomtom.com/search/2/search/Los%20Angeles.json?minFuzzyLevel=1&amp;maxFuzzyLevel=2&amp;view=Unified&amp;relatedPois=off&amp;key=*****</a></pre><p>Experiment with entering the parameters, clicking the <strong>EXECUTE</strong> button and observing the responses. We’ll dissect the responses as we proceed through the tutorial.</p><h3>MAKING A ROUTING API ENDPOINT</h3><p>First, <a href="https://developer.tomtom.com/routing-api/">get the Routing API</a>. You can read about the API on the <strong>Documentation</strong> tab.</p><p>Next, go to the <strong>API Explorer</strong> tab to find the endpoints to receive parameters. We’ll use the first endpoint, <strong>Calculate Route</strong>, with a GET method. When you click the down arrow, you’ll see the parameters’ names and descriptions.</p><p>Enter your location’s coordinates in the locations parameter, then set the contentType to JSON, maxAlternatives to 5, and instructionsType to text. Pass the departure time in the departAt parameter. You can also use other parameters if you wish.</p><p>The endpoint URL looks like this:</p><pre><a href="https://api.tomtom.com/routing/1/calculateRoute/34.05224,-118.24334:33.68591,-117.82472/json?maxAlternatives=5&amp;instructionsType=text&amp;departAt=2022-02-10T08:00:00&amp;key=****">https://api.tomtom.com/routing/1/calculateRoute/34.05224,-118.24334:33.68591,-117.82472/json?maxAlternatives=5&amp;instructionsType=text&amp;departAt=2022-02-10T08:00:00&amp;key=****</a></pre><h3>GETTING STARTED WITH DATA</h3><p>Start by importing the modules below into your notebook. We’ll use pandas for data manipulation, urllib.parse for processing the URLs, requests for getting responses, and the rest for data visualization.</p><pre>import urllib.parse as urlparse<br>import pandas as pd<br>import requests as rq<br>import matplotlib.pyplot as plt<br>%matplotlib inline<br>import seaborn as sns</pre><p>Next, we set our API key, the two points, and departure time. We’ll pass all the variables except the API key through a user interface such as a form to make our application dynamic. The API accepts the YYYY-mm-ddHH:mm:ss time format.</p><pre>__API_KEY__ = &quot;&lt;your-api-key&gt;&quot;<br>departure_point = &#39;Los Angeles&#39;<br>delivery_point = &#39;Irvine&#39;<br>departure_time = &#39;2022-02-10T08:00:00&#39;</pre><p>Then, we create a function called search_city_coords to get the city coordinates. We pass in the location name and our key. The application gives these parameters to the endpoint URL. Then, we get the response in JSON format using the requests module.</p><pre>def search_city_coords(city, key):<br>    coordinates_base_url = &quot;https://api.tomtom.com/search/2/search/&quot;+urlparse.quote(city)+&quot;.json?minFuzzyLevel=1&amp;maxFuzzyLevel=2&amp;view=Unified&amp;relatedPois=off&amp;key=&quot;+key<br>    json_response = rq.get(coordinates_base_url).json()<br>    latitude = json_response[&#39;results&#39;][0][&#39;position&#39;][&#39;lat&#39;]<br>    longitude = json_response[&#39;results&#39;][0][&#39;position&#39;][&#39;lon&#39;]<br>    position = str(latitude)+&quot;,&quot;+str(longitude)<br>    return position</pre><p>You should get a JSON response like the screenshot below when you test the APIs. Don’t worry about the formatting. You can use any JSON formatting tool at your disposal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/0*FSJ7sZRF949pVLcO.png" /></figure><p>The application returns the result with the highest score first in the results object. The object has a position object containing latitude and longitude. We then concatenate and return the values at the end of the function.</p><h3>GETTING ROUTE INFORMATION</h3><p>We use a function called get_routes_info to obtain route information. The application passes in the parameters start (departure point), stop (destination point), departAt (departure time), and key (API key).</p><p>We’ll use these parameters in the endpoint URL to retrieve the results. The results will consist of all alternative routes that the drivers can use, so we’ll use iteration to access the routes object’s contents. We’ll then pass the contents to a data frame that the function will return.</p><pre>def get_routes_info(start, stop, departAt, key):<br>    base_url = &quot;https://api.tomtom.com/routing/1/calculateRoute/&quot;+start+&quot;:&quot;+stop+&quot;/json?maxAlternatives=5&amp;instructionsType=text&amp;departAt=&quot;+departAt+&quot;&amp;key=&quot;+key<br>    json_response = rq.get(base_url).json()<br>    routes_obj = json_response[&#39;routes&#39;]<br>    obj_length = len(routes_obj)<br>    for i in range(obj_length):<br>        if (i == 0):<br>            summary_df = pd.DataFrame([routes_obj[0][&#39;summary&#39;]])<br>        else:<br>            summary_df = summary_df.append((routes_obj[i][&#39;summary&#39;]),ignore_index=True)<br>    return summary_df</pre><p>Then, run the two functions in a new cell:</p><pre>departure_point_coords = search_city_coords(departure_point, __API_KEY__)<br>delivery_point_coords = search_city_coords(delivery_point, __API_KEY__)</pre><pre>summary_df = get_routes_info(departure_point_coords, delivery_point_coords, departure_time, __API_KEY__)</pre><p>We can access the data frame in another cell. We choose the first six columns because they contain vital information for our tutorial.</p><pre>summary_df.iloc[: , :6]</pre><p>The data frame should look similar to the screenshot below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/0*8RTnsGrW-vsyphzS.jpg" /></figure><h3>VISUALIZING DATA</h3><p>We use a Seaborn bar chart to visualize our data. Notice that the first result has the shortest travel time.</p><pre>plt.figure(figsize=(6,4))<br>plt.title(&quot;Travel time comparison&quot;)<br>sns.barplot(x=summary_df.index, y=summary_df.iloc[: , :6][&#39;travelTimeInSeconds&#39;])<br>plt.ylabel(&quot;Travel time (in seconds)&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/0*bmO8eHjtzDIw1hF8.png" /></figure><p>We can get the minimum travel time and index using the Pandas min() and idxmin() functions:</p><pre>min_travel_time = summary_df[&#39;travelTimeInSeconds&#39;].min()<br>print(&quot;Minimum travel time is: &quot;,min_travel_time,&quot; seconds&quot;)<br>min_pos = summary_df[&#39;travelTimeInSeconds&#39;].idxmin()</pre><h3>ADDING ROUTE INSTRUCTIONS</h3><p>The Routing API also returns a guidance object with step-by-step instructions on which route the drivers should take. See the screenshot below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*Z0KNmQF1LFVDDdIJ.jpg" /></figure><p>We’ll use the instructionsGroups object to access the instructions from the groupMessage item:</p><pre>def get_guidance(start, stop, departAt, position, key):<br>    guide = &#39;&#39;<br>    base_url = &quot;https://api.tomtom.com/routing/1/calculateRoute/&quot;+start+&quot;:&quot;+stop+&quot;/json?maxAlternatives=5&amp;instructionsType=text&amp;departAt=&quot;+departAt+&quot;&amp;key=&quot;+key<br>    json_response = rq.get(base_url).json()<br>    guidance_obj = json_response[&#39;routes&#39;][position][&#39;guidance&#39;][&#39;instructionGroups&#39;]<br>    obj_length = len(guidance_obj)<br>    for i in range(obj_length):<br>        if i==0:<br>            guide = guidance_obj[0][&#39;groupMessage&#39;]<br>        else:<br>            guide = guide+&quot;. &quot;+ guidance_obj[i][&#39;groupMessage&#39;]<br>    return guide</pre><p>We iterate over the instructions since there may be more than one, append them to a string, and return them.</p><p>We can then access the guidance this way:</p><pre>shortest_route = get_guidance(departure_point_coords, delivery_point_coords, departure_time,min_pos, __API_KEY__)<br>print(&quot;HELLO THERE, FOLLOW THIS ROUTE FOR A FASTER DELIVERY: &quot;, shortest_route,&quot;\n\nThank you, and have a safe ride.&quot;)</pre><p>The code will display instructions like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/0*Pq7ShFaIfrEb_qrw.png" /></figure><h3>EXAMINING ALTERNATE DEPARTURE TIMES</h3><p>Now, let’s pass in various departure times using a list to get a route with the shortest travel time. In each loop, we get the data frame for that time and append it to the agg_df dataframe.</p><pre>time_list = [&#39;2022-02-10T09:00:00&#39;, &#39;2022-02-10T05:00:00&#39;, &#39;2022-02-10T07:00:00&#39;, &#39;2022-02-10T11:00:00&#39;, &#39;2022-02-10T08:00:00&#39;]<br>agg_df = pd.DataFrame()<br># Using a for loop<br>for time in time_list:<br>    summary_df2 = get_routes_info(departure_point_coords, delivery_point_coords, time, __API_KEY__)<br>    agg_df = agg_df.append(summary_df2,ignore_index=True)</pre><pre>agg_df.iloc[: , :6]</pre><p>The returned data frame will look like the screenshot below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*JNVmVGUZyoTJj_Es.jpg" /></figure><p>We can then use a heatmap to visualize the data:</p><pre>plt.figure(figsize=(15,8))<br>plt.title(&quot;Distance and time travel comparison&quot;)<br>sns.heatmap(data=agg_df.iloc[: , :2], fmt=&#39;d&#39;, annot=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/0*C0vu2UZFNJDzodcC.png" /></figure><p>We use this code to find the minimum travel time:</p><pre>min_travel_time = agg_df[&#39;travelTimeInSeconds&#39;].min()<br>print(&quot;Minimum travel time is: &quot;,min_travel_time,&quot; seconds&quot;)</pre><p>Then, we use this code to retrieve the guidance:</p><pre>min_pos = summary_df[&#39;travelTimeInSeconds&#39;].idxmin()<br>shortest_route = get_guidance(departure_point_coords, delivery_point_coords, departure_time,min_pos, __API_KEY__)<br>print(&quot;HELLO THERE, FOLLOW THIS ROUTE FOR A FASTER DELIVERY: &quot;, shortest_route,&quot;\n\nThank you, and have a safe ride.&quot;)</pre><p>Now that the application has found the fastest route, the bakery can switch its drivers to that route. The drivers and managers will know the general route they can usually take to be most efficient. Other real-time navigation tools can then help the drivers make finer adjustments to respond to unusual daily traffic delays.</p><p>Access this tutorial’s code in <a href="https://github.com/Agusioma/tomtom-api-short-route">this GitHub repository</a>.</p><h3>BEST PRACTICES FOR USING TOMTOM APIS</h3><p>To get the best results, you must provide accurate information, such as exact coordinates. You can pass in exact coordinates using a function instead of manually. You can also use your language’s URL escape methods and tools to avoid inaccuracies while feeding the endpoints with data.</p><h3>NEXT STEPS</h3><p>We explored how to use the Routing and Search APIs, used them to retrieve data, processed and visualized the data, then finally provided route guidance to the app user. Our app can help the bakery or other businesses find the quickest route based on historical data. They may want to use this information to change the order of grocery stores they visit or split one route between multiple drivers.</p><p>You can enhance this application using other Routing API parameters. For example, you can get the route’s current traffic information (traffic), avoid certain road types (avoid), select the travel mode (car, truck, or others), avoid hilly routes that might topple the baked goods (hilliness), and more.</p><p>TomTom’s historical traffic data can also help you with other projects, such as building a prediction model. For instance, you may want to predict if a road is too hilly or is excessively winding. Use TomTom’s existing data for that supervised learning task. You simply retrieve, label, process, and predict.</p><p><a href="https://developer.tomtom.com/user/register">Sign up</a> to start using TomTom maps and data in your applications and data science projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9d178b2863" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tomtom-developers/using-tomtom-data-to-improve-delivery-routes-a9d178b2863">Using TomTom Data to Improve Delivery Routes</a> was originally published in <a href="https://medium.com/tomtom-developers">TomTom Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating and Using TomTom Geofences with Vue]]></title>
            <link>https://medium.com/tomtom-developers/creating-and-using-tomtom-geofences-with-vue-ffefdc8b917a?source=rss----9c5d61983c4b---4</link>
            <guid isPermaLink="false">https://medium.com/p/ffefdc8b917a</guid>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[geofencing]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[TomTom Developers]]></dc:creator>
            <pubDate>Mon, 23 May 2022 05:35:46 GMT</pubDate>
            <atom:updated>2022-05-23T05:35:46.885Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to use the Maps SDK and Geofencing Report service to track movement into and out of an area.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3BiMretENwCmiCk4tRFTLg.jpeg" /></figure><p>Geofences are virtual fences around a given geographical area. They enable us to monitor a site and add functionality to a map. We can determine if an object is inside or outside the area using its coordinates. A geofencing API’s reporting service can even provide the distance between the object and the geofence.</p><p>Geofences help solve many practical problems, including enabling ride-hailing apps, notifying a customer when their parcel or delivery is almost at their doorstep, detecting deviation from the route or potential theft of trucks carrying valuable cargo, and much more. So, in this tutorial, let’s explore how to add a geofence to a TomTom map within a Vue application. We’ll then use our geofence to track movement into and out of an area on the map. Our Vue application will run on Vite.</p><p>You should be familiar with JavaScript and Vue to follow this tutorial. We’ll show you how to work with TomTom’s features. You also need a <a href="https://developer.tomtom.com/user/register">TomTom developer account</a> to follow along — it’s free even for commercial use with thousands of daily requests (then you can <a href="https://developer.tomtom.com/store/maps-api">pay as you grow</a> if you need more capacity, or <a href="https://developer.tomtom.com/contact-sales">reach out to TomTom</a> for a personalized offer).</p><h3>GETTING STARTED</h3><h3>INSTALLING VITE</h3><p>Vite provides us with a fast development server. To get started with Vite, run the following command:</p><pre>npm init vite@latest geofence -- --template vue</pre><p>You can then install other external npm libraries that you might need for your project.</p><p>For a deep dive into everything you need to know about getting started, check out Vite’s complete documentation.</p><h3>INSTALLING TOMTOM MAPS SDK</h3><p>Next, we install TomTom Maps SDK to view the map on the Document Object Model (DOM) by running this command:</p><pre>npm i @tomtom-international/web-sdk-maps</pre><h3>INSTALLING AXIOS</h3><p>Then, we install Axios to handle API requests:</p><pre>npm i axios</pre><h3>ADDING A MAP</h3><p>Now, let’s add our map into our Vue component. First, let’s import all the necessary libraries inside our &lt;script&gt; tag, starting with Axios:</p><pre>import axios from &#39;axios&#39;;</pre><p>We also import onMounted, ref, and reactive into our component. We’ll use this inside our Vue composition API:</p><pre>import { onMounted, ref, reactive } from &#39;vue&#39;;</pre><p>We’ll then add the setup() method to the component to initialize and insert the map:</p><pre>export default { <br>  name: &#39;App&#39;, <br>  setup() { <br>    const mapRef = ref(null); <br>    onMounted(() =&gt; { <br>      const tt = window.tt; <br>      var map = tt.map({ <br>      key: &#39;&lt;YOUR API KEY HERE&gt;&#39;, <br>      container: mapRef.value, <br>      style: &#39;tomtom://vector/1/basic-main&#39;, <br>    }); <br>        map.addControl(new tt.FullscreenControl()); <br>        map.addControl(new tt.NavigationControl());  <br>    }) </pre><pre>    return { <br>      mapRef, <br>    }; <br>  }  <br>}</pre><p>Inside the setup() method, we used the ref function to create a variable called mapRef. Refs allow us to access the DOM element, which is how we add the map.</p><p>Next, we use our onMounted life-cycle to initialize and add the map to the DOM while the component is mounted. We set mapRef as the map’s container and add visual controls for navigation and full-screen to the map using map.addControl. In the end, we’ll return mapRef and use it in our &lt;template&gt;.</p><p>We use ref to add the map to the &lt;div&gt; element.</p><pre>&lt;div id=&quot;map&quot; ref=&quot;mapRef&quot;&gt;&lt;/div&gt;</pre><p>Let’s also add these styles:</p><pre>&lt;style&gt;<br>#app {<br>  font-family: Avenir, Helvetica, Arial, sans-serif;<br>  -webkit-font-smoothing: antialiased;<br>  -moz-osx-font-smoothing: grayscale;<br>  text-align: center;<br>  color: #2c3e50;<br>  margin-top: 60px;<br>}<br>#map {<br>  height: 60vh;<br>}<br>&lt;/style&gt;</pre><h3>CREATING THE GEOFENCE</h3><p>Our next step is to create the geofence. The geofencing service enables us to draw a virtual boundary, and we can use the Geofences creator tool to draw geofences of any shape or form. Applications can then use this virtual boundary to check if a location or object is inside or outside the enclosed space. A particular object’s coordinates — its latitude and longitude — allow us to check if it’s within the geofence.</p><p>To get these coordinates and determine the object’s location, we want a user to click on the map and have the app automatically draw a circular geofence centered on that point.</p><p>We need an Admin Key to do this. The Admin Key is one of the query parameters we need to handle the geofence’s API requests. Then, we’ll use Postman to send a POST request to TomTom’s API to register our Admin Key.</p><p>This request will include a body containing a secret phase. We’re using “my_secret_key” for this project. However, you can use another custom string.</p><pre>{<br>  &quot;secret&quot;: &quot;my_secret_key&quot;<br>}</pre><p>We’re also using our API key as a parameter, so it’s all tied to one account:</p><pre><a href="https://api.tomtom.com/geofencing/1/register?key=Your_API_Key">https://api.tomtom.com/geofencing/1/register?key=Your_API_Key</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9x1B_AwyT1SMuPmR.jpg" /></figure><p>We’ll get back a response containing our adminKey.</p><h3>CREATING A NEW PROJECT</h3><p>We now have the adminKey, but we need to create a project that connects to the geofence we’re about to draw. Every geofence is associated with a particular project.</p><p>Send another POST request to register the new project:</p><pre><a href="https://api.tomtom.com/geofencing/1/projects/project?key=${apiKey}&amp;adminKey=${adminKey}">https://api.tomtom.com/geofencing/1/projects/project?key=${apiKey}&amp;adminKey=${adminKey}</a></pre><p>Send it with the project name as the body:</p><pre>{<br>  &quot;name&quot;: &quot;Geofence map&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4MdTb1jcov0Im8BI.jpg" /></figure><p>The response contains the project id and name.</p><h3>CREATING THE GEOFENCE</h3><p>Now that we have our project, we can create the geofence in our code using its coordinates. First, let’s install Turf to help us draw on the map.</p><pre>npm i @turf/turf</pre><p>Go back inside the onMounted component and add map.on to monitor where and when the user clicks. The app will use that particular coordinate to draw our geofence. Send the request like this:</p><pre>map.on(&#39;click&#39;, function (event) {<br>const position = event.lngLat;<br>        console.log(position);<br>axios.post(&#39;https://api.tomtom.com/geofencing/1/projects/${YOUR_PRODUCT_ID}/fence?key=${YOUR_API_KEY}=${YOUR_ADMIN_KEY}&#39;,<br>            {<br>              name: `Our location ${Math.floor(Math.random() * 10000)}`,<br>              type: &#39;Feature&#39;,<br>              geometry: {<br>                radius: 85,<br>                type: &#39;Point&#39;,<br>                shapeType: &#39;Circle&#39;,<br>                coordinates: [position.lat, position.lng],<br>              },<br>            }<br>          )<br>}</pre><p>We get back a response containing information about the geofence we just created. In the response, we use turf to collect our coordinates and eventually feed them into map.addSource.</p><pre>.then((res) =&gt; {<br>            console.log(res.data);<br>            console.log(position)<br>            let _center = turf.point([position.lng,position.lat]);<br>            let _radius = 45;<br>            let _options = {<br>              steps: 80,<br>              units: &#39;kilometers&#39; // or &quot;mile&quot;<br>            };</pre><pre>            let _circle = turf.circle(_center, _radius, _options);</pre><pre>            map.addSource(&quot;circleData&quot;, {<br>              type: &quot;geojson&quot;,<br>              data: _circle,<br>            });</pre><pre>            map.addLayer({<br>              id: &quot;circle-fill&quot;,<br>              type: &quot;fill&quot;,<br>              source: &quot;circleData&quot;,<br>              paint: {<br>                &quot;fill-color&quot;: &quot;red&quot;,<br>                &quot;fill-opacity&quot;: 0.5,<br>              },<br>            });<br>            //map.setCenter([parseFloat(position.lat), parseFloat(position.lng)]);<br>          })<br>          .catch((err) =&gt; console.log(err));</pre><p>map.addLayer collects the data through map.addSource and uses it to draw the geofence directly on our map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/0*NGM9c4KXEFDAys9Q.jpg" /></figure><p>When we click any point on the map, the app takes the coordinates, creates a new geofence, and uses addLayer to draw a circular outline.</p><p>Here’s the full code inside onMounted:</p><pre>onMounted(() =&gt; {<br>      const tt = window.tt;<br>      var map = tt.map({<br>        key: &#39;{YOUR_API_KEY}&#39;,<br>        container: mapRef.value,<br>        style: &#39;tomtom://vector/1/basic-main&#39;,<br>        zoom: 5,<br>        center: [12.3, 32.992578],<br>      });<br>      map.addControl(new tt.FullscreenControl());<br>      map.addControl(new tt.NavigationControl());<br>      state.map = map;<br>      <br>      map.on(&#39;click&#39;, function (event) {<br>        const position = event.lngLat;<br>        console.log(position);<br>        axios<br>          .post(<br>            &#39;https://api.tomtom.com/geofencing/1/projects/1c2f4c1d-c1eb-43b3-a023-18e503469104/fence?key=${YOUR_API_KEY}=${YOUR_ADMIN_KEY}&#39;,<br>            {<br>              name: `Our location ${Math.floor(Math.random() * 10000)}`,<br>              type: &#39;Feature&#39;,<br>              geometry: {<br>                radius: 85,<br>                type: &#39;Point&#39;,<br>                shapeType: &#39;Circle&#39;,<br>                coordinates: [position.lat, position.lng],<br>              },<br>            }<br>          )<br>          .then((res) =&gt; {<br>            console.log(res.data);<br>            console.log(position)<br>            let _center = turf.point([position.lng,position.lat]);<br>            let _radius = 45;<br>            let _options = {<br>              steps: 80,<br>              units: &#39;kilometers&#39; // or &quot;mile&quot;<br>            };<br>            let _circle = turf.circle(_center, _radius, _options);<br>            map.addSource(&quot;circleData&quot;, {<br>              type: &quot;geojson&quot;,<br>              data: _circle,<br>            });<br>            map.addLayer({<br>              id: &quot;circle-fill&quot;,<br>              type: &quot;fill&quot;,<br>              source: &quot;circleData&quot;,<br>              paint: {<br>                &quot;fill-color&quot;: &quot;red&quot;,<br>                &quot;fill-opacity&quot;: 0.5,<br>              },<br>            });<br>            //map.setCenter([parseFloat(position.lat), parseFloat(position.lng)]);<br>          })<br>          .catch((err) =&gt; console.log(err));<br>      });<br>    });</pre><h3>HANDLING GEOFENCE NOTIFICATIONS</h3><p>TomTom maps enable us to monitor our geofence, checking if an object is within or outside it. This feature is mostly beyond the scope of this tutorial. You would need to register and track an object and connect your backend to the <a href="https://developer.tomtom.com/notifications-api/notifications-api-documentation">Notifications API</a> and <a href="https://developer.tomtom.com/geofencing-api/geofencing-api-documentation/alert-format">Geofencing Alert Service</a>. This approach would require a webhook and email where it will send notifications if the device crosses the geofence.</p><p>Instead, using its coordinates, we can use the <a href="https://developer.tomtom.com/geofencing-api/documentation/report-service/report-service">TomTom Geofencing Report service</a> to determine if an object is within or outside the geofence. Let’s first create an object’s location and add a marker for that location on the map. We make a new function directly under our onMounted component called addMarker.</p><pre>function addMarker(map) { <br>    const tt = window.tt; <br>    var location = [-12.3423, 65.67346189482023]; <br>    var popupOffset = 25; </pre><pre>    var marker = new tt.Marker().setLngLat(location).addTo(map); <br>    var popup = new tt.Popup({ offset: popupOffset }).setHTML(&quot;Your object!&quot;); <br>            marker.setPopup(popup).togglePopup(); <br>}</pre><p>Then add this code to our onMounted component:</p><pre>onMounted(() =&gt; { <br>    // [...] <br>    addMarker(map); <br>})</pre><p>This marker will display on our map, like this screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ebJkCzKLH50_4o-i.jpg" /></figure><p>We can now take our object’s coordinates and send a POST request using this endpoint. We’ll use the projectId, apiKey, adminKey, and the object’s latitude and longitude as query parameters:</p><pre><a href="https://api.tomtom.com/geofencing/1/report/$%7BprojectId%7D?key=${apiKey}&amp;adminKey=${adminKey}&amp;point=${lat,lng}">https://api.tomtom.com/geofencing/1/report/${projectId}?key=${apiKey}&amp;adminKey=${adminKey}&amp;point=${lat,lng}</a></pre><p>The response looks like this:</p><pre>{<br>    &quot;summary&quot;: {<br>        &quot;project&quot;: &quot;c2f56e6d-8395-4aa2-bf64-e36f7b7d229c&quot;,<br>        &quot;type&quot;: &quot;Point&quot;,<br>        &quot;coordinates&quot;: [<br>            41.670966,<br>            2.750529,<br>            0.0<br>        ],<br>        &quot;range&quot;: 0.0<br>    },<br>    &quot;inside&quot;: {<br>        &quot;type&quot;: &quot;FeatureCollection&quot;,<br>        &quot;features&quot;: []<br>    },<br>    &quot;outside&quot;: {<br>        &quot;type&quot;: &quot;FeatureCollection&quot;,<br>        &quot;features&quot;: [<br>            {<br>                &quot;id&quot;: &quot;0c803717-b862-4548-ab47-20bf544b2d84&quot;,<br>                &quot;name&quot;: &quot;Geofence map&quot;,<br>                &quot;distance&quot;: 3298398.0,<br>                &quot;type&quot;: &quot;Feature&quot;,<br>                &quot;geometry&quot;: {<br>                    &quot;type&quot;: &quot;Point&quot;,<br>                    &quot;coordinates&quot;: [<br>                        12.138017,<br>                        6.137388<br>                    ]<br>                },<br>                &quot;properties&quot;: {<br>                    &quot;maxSpeedKmh&quot;: 70<br>                }<br>            }<br>        ]<br>    }<br>}</pre><p>The response shows whether the point is inside or outside the app’s geofences. The response also includes the object’s distance from the geofence.</p><h3>CONCLUSION</h3><p>Congratulations on completing the tutorial! We’ve explored geofences and demonstrated how to use them to optimize mapping and tracking in your Vue application. Here’s a link to our <a href="https://github.com/Atanda1/vue-h7ncds">complete code</a>.</p><p>You can customize TomTom’s Geofencing API to handle your unique use case, from tracking flower deliveries to notifying ridesharing travelers when their lift to the airport is almost there to alerting fleet managers when their truck packed with computer equipment is not where it should be. Now that you’ve learned how to use TomTom with Vue, <a href="https://developer.tomtom.com/docs-and-tools">dive in</a> and get started adding geofencing features to your next app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffefdc8b917a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tomtom-developers/creating-and-using-tomtom-geofences-with-vue-ffefdc8b917a">Creating and Using TomTom Geofences with Vue</a> was originally published in <a href="https://medium.com/tomtom-developers">TomTom Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating and Using TomTom Geofences with React]]></title>
            <link>https://medium.com/tomtom-developers/creating-and-using-tomtom-geofences-with-react-66ccc3ef4d08?source=rss----9c5d61983c4b---4</link>
            <guid isPermaLink="false">https://medium.com/p/66ccc3ef4d08</guid>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[mapping]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[geofencing]]></category>
            <dc:creator><![CDATA[TomTom Developers]]></dc:creator>
            <pubDate>Wed, 11 May 2022 22:58:13 GMT</pubDate>
            <atom:updated>2022-05-07T03:49:49.618Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to use the TomTom Maps SDK for Web and Geofencing API to create a geofence around a point</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NcGV7BqgCIUpB2gYtv_HEg.jpeg" /></figure><p>A geofence is a virtual perimeter (fence) defined around a specific geographic location. We can work with the fence to carry out various operations when an object with internet connectivity — like a mobile phone or car — enters or leaves such an area. For example, we can notify customers when a delivery driver is near their home, match a user with the nearest rideshare driver, or send customers to the closest store location.</p><p>In this tutorial, we’ll explore how to set up and work with a geofence in a React application, using the <a href="https://developer.tomtom.com/products/maps-sdk">TomTom Maps SDK for Web</a> and the <a href="https://developer.tomtom.com/geofencing-api/geofencing-api-documentation">Geofencing API</a>, and how to set up geofences with irregular shapes using the <a href="https://developer.tomtom.com/demos/geofences-creator/index.html">Geofence Creator</a>. Our app will create a circular geofence around where a user clicks on a map. You can find the complete code and see it in action on <a href="https://codesandbox.io/s/geofencing-in-react-yviy6?file=/src/App.js">CodeSandbox</a>.</p><h3>PREREQUISITES</h3><p>To follow this tutorial, you’ll need the following:</p><p>• Node.js installed on your computer to create a React app. Don’t have Node.js installed? <a href="https://nodejs.org/en/">Download</a> the most recent version.<br>• An API key to access TomTom services. If you haven’t yet, you can <a href="https://developer.tomtom.com/user/register">sign up for a free developer account</a> to get one.<br>• A free <a href="https://www.postman.com/">Postman</a> account.<br>• Practical knowledge of React, functional components, and <a href="https://reactjs.org/docs/hooks-intro.html">Hooks</a>.</p><h3>SETTING UP</h3><p>First, create a new React app and install the libraries that’ll be used in the demo. Create a new React app with this command:</p><pre>npx create-react-app &lt;app-name&gt;</pre><p>The command creates a new folder with the essential React packages on your computer.</p><p>Navigate into the project’s directory and install the TomTom Maps SDK for Web and the <a href="https://github.com/Turfjs/turf">Turf.js</a> library:</p><pre>cd &lt;app-name&gt;<br>npm install @tomtom-international/web-sdk-maps @turf/turf</pre><p>In this tutorial, we’ll be using the HTTP client library <a href="https://axios-http.com/">Axios</a> to make HTTP requests. So, install the library with the command:</p><pre>npm install axios</pre><p>Now that React and the essential libraries have been installed, we’re set to build our application.</p><h3>DISPLAYING THE MAP</h3><p>It’s time to build the app’s user interface (UI) to display a TomTom map. We won’t create any new files to create the UI, as the project bootstrapped by the create-react-app command already includes CSS and JavaScript files. We’ll use these to build out the app.</p><p>Open App.js and populate it with the code:</p><pre>//App.js<br>import { useEffect, useState, useRef } from &quot;react&quot;;<br>import axios from &quot;axios&quot;;<br>import &quot;./App.css&quot;;<br>// TomTom SDK<br>import * as tt from &quot;@tomtom-international/web-sdk-maps&quot;;<br>// styles<br>import &quot;@tomtom-international/web-sdk-maps/dist/maps.css&quot;;</pre><pre>function App() {<br>  const [map, setMap] = useState();<br>  const mapContainer = useRef();<br>  const AMSTERDAM = { lon: 4.896029, lat: 52.371807 };<br></pre><pre>  useEffect(() =&gt; {<br>    let map = tt.map({<br>      key: &lt;Your_API_Key&gt;,<br>      container: mapContainer.current.id,<br>      center: AMSTERDAM,<br>      zoom: 10,<br>      language: &quot;en-GB&quot;,<br>    });<br>    map.addControl(new tt.FullscreenControl());<br>    map.addControl(new tt.NavigationControl());<br></pre><pre>    setMap(map);<br>    return () =&gt; {<br>      map.remove();<br>    };<br>    //eslint-disable-next-line<br>  }, []);<br></pre><pre>  return (<br>    &lt;div className=&quot;container&quot;&gt;<br>      &lt;nav className=&quot;nav&quot;&gt;<br>        &lt;h1&gt; Geofencing in React&lt;/h1&gt;<br>      &lt;/nav&gt;<br>      &lt;div ref={mapContainer} className=&quot;map&quot; id=&quot;map&quot; /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default App;</pre><p>We start by importing the TomTom Maps SDK for Web, React hooks, and the Axios and Turf libraries at the top of the file.</p><p>Below the imports, the function App is defined. This is the component where our application will live.</p><p>In the function App, the useState and useRef hooks create variables that store the map and reference’s the HTML element the map is to be embedded in.</p><p>Next, the useEffect hook initiates the map on page load by calling the tt.map constructor with the necessary configurations. These configurations include the container parameter that takes the ID of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction">DOM</a> element the map is to be embedded in, and the center parameter to center the map on Amsterdam, Netherlands, using its longitude and latitude coordinates.</p><p>Finally, the code returns the HTML for the browser to display.</p><p>Remember to replace the &lt;Your_API_Key&gt; placeholder with your API key from your TomTom developer account.</p><p>Now, paste the CSS styles below into App.css to make the app look nicer than unstyled HTML:</p><pre>/*App.css*/<br>* {<br>  padding: 0;<br>  margin: 0;<br>  box-sizing: border-box;<br>}<br>.container {<br>  width: 100vw;<br>  height: 100vh;<br>  display: flex;<br>  flex-direction: column;<br>  justify-content: space-around;<br>  align-items: center;<br>}<br>.nav {<br>  display: flex;<br>  justify-content: space-around;<br>  align-items: center;<br>  width: 100%;<br>  height: 10%;<br>  background-color: #4169e1;<br>  color: #ffffff;<br>}<br>.nav h1 {<br>  padding: 0.3125rem 0;<br>  margin-right: 1rem;<br>  font-size: 1.25rem;<br>  white-space: nowrap;<br>}<br>.map {<br>  width: 100%;<br>  height: 90%;<br>}</pre><p>Now, the app can be run locally by navigating into its directory and running the command:</p><pre>npm start</pre><p>This command launches the application and opens it in a browser. The result should look like the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/0*8XeuHC-3rZY7smHO.jpg" /></figure><h3>ENABLING GEOFENCING</h3><p>With the map displaying correctly, we can start creating geofences in our app using the TomTom Geofencing API. The Geofencing API enables us to create and manage geofences around specified geographical locations.</p><p>Before using the Geofencing API, you need to register an admin key. It provides an extra layer of security to authenticate your requests to the service.</p><p>Using <a href="https://www.postman.com/">Postman</a>, send a POST request to <a href="https://api.tomtom.com/location/1/register?&amp;key=Your_API_Key">https://api.tomtom.com/location/1/register?&amp;key=Your_API_Key</a> with a body of:</p><pre>{ <br>“secret”: &quot;your_secret&quot;, <br>}</pre><p>The body of the request contains a single property: secret. You’ll need this password to configure your account in the future, like registering a new admin key if the former is compromised. So, use a secret you can remember and ensure you don’t lose it.</p><p>A successful response will generate and log your admin key to the console:</p><pre>{ <br>adminKey: your_admin_key <br>}</pre><h3>CREATING A PROJECT</h3><p>Now that we have an admin key, we need to create a Project. This is a collection that stores and manages the geofences we create, each project identified with a unique ID. A geofence must be added to at least one project (it can be added to more) so you need to create a project before creating a geofence.</p><p>To create a project, send a POST request to the endpoint:</p><pre>https://api.tomtom.com/geofencing/1/projects/project?adminKey&lt;ADMIN_KEY&gt;=&amp;key=&lt;API_KEY&gt;</pre><p>Set the project’s name as a parameter in the request body:</p><pre>{ <br>  &quot;name&quot;: &quot;Project_Name&quot; <br>}</pre><p>The API will respond with the project name and ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*1kXGHa9NjvdOs6LW.jpg" /></figure><p>Visit <a href="https://www.postman.com/victor-codejs/workspace/tomtom-apis/request/12705763-87784c68-0ec7-473a-8c3f-9cbab1c33e32">Creating a Project</a> to check out the request on Postman if you want to try it out.</p><p>With the project created, we can create geofences around areas of interest.</p><h3>CREATING A GEOFENCE</h3><p>Let’s explore two different ways we can create geofences: using the Geofencing API, and using the Geofence Creator.</p><h3>GEOFENCING API</h3><p>Until now, Postman has been used to handle all requests to the <a href="https://developer.tomtom.com/geofencing-api/documentation/product-information/introduction">Geofencing API</a>. Now, we’ll use JavaScript to add an <a href="https://www.javatpoint.com/javascript-onclick-event">onclick</a> event handler to our TomTom map so that whenever a user clicks on the map, a circular geofence is created centered at the point where the user clicked. event handler to our TomTom map so that whenever a user clicks on the map, the handler creates a circular geofence centered at the point where the user clicked.</p><p>First, we define the function createGeofence to create the geofence:</p><pre>async function createGeofence(lng, lat) {<br>    const request = await axios({<br>      method: &quot;post&quot;,<br>      url: `https://api.tomtom.com/geofencing/1/projects/&lt;YOUR_Project_ID&gt;/fence?adminKey=&lt;YOUR_ADMIN_KEY&gt;&amp;key=&lt;YOUR_API_KEY&gt;`,<br>      headers: {<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>      },<br>      data: JSON.stringify({<br>        name: `Area ${Math.floor(Math.random() * 10000)}`,<br>        type: &quot;Feature&quot;,<br>        geometry: {<br>          radius: 200,<br>          type: &quot;Point&quot;,<br>          shapeType: &quot;Circle&quot;,<br>          coordinates: [lng, lat],<br>        },<br>      }),<br>    });<br>    const response = await request.data;<br>    return response.id;<br>  }</pre><p>The function above contains the details needed to create a fence around a location. The coordinates parameter takes the latitude and longitude of the site to be geofenced. Then, the parameter passes these coordinates to the function as the lng and lat arguments. shapeType defines the fence’s shape (a circle, in this case), and the radius parameter sets how wide the geofence should span in meters.</p><p>A post request is then made to the Geofencing API using Axios. The API creates the geofence and returns an ID.</p><p>Next, we add an on-click handler within the useEffect hook that initializes the map on page load.</p><pre>map.on(&quot;click&quot;, (e) =&gt; {<br>      const { lng, lat } = e.lngLat;<br>      <br>      // creating source data with turf.js<br>      const sourceID = `circleData ${Math.floor(Math.random() * 10000)}`;<br>      let center = turf.point([lng, lat]);<br>      let radius = 10;<br>      let options = {<br>        steps: 15,<br>        units: &quot;kilometers&quot;, // or &quot;mile&quot;<br>      };<br>      let circle = turf.circle(center, radius, options);<br>      map.addSource(sourceID, {<br>        type: &quot;geojson&quot;,<br>        data: circle,<br>      });<br></pre><pre>      //fetching and drawing the map<br>      Promise.all([createGeofence(lng, lat)]).then((result) =&gt; {<br>        axios({<br>          method: &quot;get&quot;,<br>          url: `https://api.tomtom.com/geofencing/1/fences/${result[0]}?key=&lt;YOUR_API_KEY&gt;`,<br>          headers: {<br>            &quot;Content-Type&quot;: &quot;application/json&quot;,<br>          },<br>        })<br>          .then((response) =&gt; response.data)<br>          .then((result) =&gt; {<br>            map.addLayer({<br>              id: `circle ${Math.floor(Math.random() * 10000)}`,<br>              type: &quot;fill&quot;,<br>              source: sourceID,<br>              paint: {<br>                &quot;fill-color&quot;: &quot;blue&quot;,<br>                &quot;fill-opacity&quot;: 0.6,<br>              },<br>            });<br>          });<br>      });</pre><p>The code above adds an on-click handler to the map. Then, we tap into the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Event">event object</a> to get the lnglat property. On a TomTom map, the event object has the lnglat property — the geographical coordinates of the point where the user clicks.</p><p>Next, we use the turf.js library, which is the easiest way to display a circle on a TomTom map, to create a <a href="http://geojson.org/">GeoJSON</a> circle and add it to the map as a <a href="https://api.tomtom.com/maps-sdk-for-web/6.x/6.16.0/documentation/dist/modules/Maps.html#method_addSource">styling source</a>.</p><p>Finally, the createGeofence function is called to create the geofence, passing in the lnglat property from the event object as its lat and lng arguments.</p><p>The function returns a promise and the geofence ID. We’ll tap into this promise, fetch the details of the newly-created geofence, then display it on the map.</p><p>Now, whenever the user clicks on the map, a circular geofence is created that’s centered on the point where the user clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*sHppG4FaJf3tzqXE.jpg" /></figure><h3>GEOFENCE CREATOR</h3><p>To enable developers to easily create complex-shaped geofence in their applications, TomTom introduced the <a href="https://developer.tomtom.com/demos/geofences-creator/">Geofences Creator</a>. It’s a graphical user interface to easily create and edit geofences using the Geofencing API.</p><p>Let’s see how seamless the process of setting up a geofence can be using the Geofence Creator. We’ll create a fence around Amsterdam’s most visited nature park — Amsterdam Bos which has a geometry of an irregular polygon.</p><p>To launch the Geofence Creator, visit <a href="https://developer.tomtom.com/demos/geofences-creator/indext.html">the developer portal</a> and provide your API key and admin key. Visit the Project to store the geofences you want to create. Setting up a fence with Geofence Creator can be done following the steps:</p><p>1. Move the map where you want to put the fence. In this case, Amstelveen, Netherlands.<br>2. Click on any of the icons at the top right corner. These represent the shape of the geofence you want to create. You can select a circle, rectangle, polygon, or even search for the location by clicking on the location icon and having the geofence drawn around its geometry. For this tutorial, click on the polygon icon.<br>3. A polygon is made up of vertexes. Click on the map to select the first vertex. Then, click on another point to mark the second vertex. Keep clicking to draw out the desired shape.<br>4. When you’re done, double-click to end the drawing.<br>5. A popup opens, where you can provide a name for the fence and, optionally, any additional properties. The newly created fence is now stored at the Geofencing API service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/0*TQERLRLdtqEPx-Li.jpg" /></figure><p>We’ve created a geofence in the Geofence Creator, but how do we get it to display on our applications? We reference a geofence using its ID.</p><p>Below is the code snippet to display a geofence in your applications using its ID:</p><pre>map.on(&quot;load&quot;, () =&gt; {<br>fetch(<br>&quot;https://api.tomtom.com/geofencing/1/fences/&lt;Fence_ID&gt;?key=&lt;Your_API_KEY&gt;&quot;<br>)<br>.then((response) =&gt; response.json())<br>.then((result) =&gt; {<br>console.log(result);<br>map.addLayer({<br>id: &quot;Fence &quot;,<br>type: &quot;fill&quot;,<br>source: {<br>type: &quot;geojson&quot;,<br>data: result,<br>},<br>paint: {<br>&quot;fill-color&quot;: &quot;purple&quot;,<br>&quot;fill-opacity&quot;: 0.6,<br>},<br>});<br>});<br>});</pre><p>In the Geofence Creator, right-click on the created geofence. This opens up a popup containing details about the fence like its name, ID, and any additional properties.</p><p>Copy the fence’s ID and replace the &lt;Fence_ID&gt; placeholder in the code snippet above with it. Now the fence should be displayed properly, like in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*8ksmJtAbe5qRdBNi.jpg" /></figure><p>Wasn’t that seamless? The Geofence Creator makes it simple to set up irregularly shaped geofences.</p><h3>SENDING NOTIFICATIONS WHEN GEOFENCE TRANSITIONS OCCUR</h3><p><a href="https://developer.tomtom.com/geofencing-api/geofencing-api-documentation">TomTom’s Geofencing API</a> provides an alert service to notify our app when objects with internet connectivity enter or leave a geofenced area. The service can send the notifications to a list of email addresses subscribed to the service or a collection of webhooks, such as a Slack or Microsoft Teams channel.</p><p>When the service is enabled, TomTom notifies the email address and webhook URLs whenever an object crosses the fence. Check out this article, <a href="https://developer.tomtom.com/blog/build-different/leverage-routing-geofencing-and-notifications-apis-send-eta-alerts">Leverage Routing, Geofencing, and Notifications APIs to Send ETA Alerts</a>, for a more in-depth geofencing guide.</p><p>Building out the feature enabling notifications on geofence transitions is not within this article’s scope. However, we can add the type of response that TomTom sends about a geofence crossing as stale data to our application’s state to simulate what our application would do with this data after a geofence crossing.</p><p>The data received through email after a successful geofencing crossing comes in the following format:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*2gCqyyz6FRiw8DsK.jpg" /></figure><p>Let’s break down the information in this message. “my_driver” is the object that triggers transition alerts upon entering or leaving the geofence (set by the <a href="https://developer.tomtom.com/geofencing-api/geofencing-api-documentation/objects-service">object service</a> in the Geofencing API). “my_fence” is the name of the geofence the object transitioned through, and 2021–02–10 at 00:52:49 is the time the transition occurred, expressed in the <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a> date format.</p><p>We can add an object containing this information attached as properties, to our application’s state, like so:</p><pre>const [geofenceData] = useState({<br>    object: &quot;my_driver&quot;,<br>    fenceName: &quot;my_fence&quot;,<br>    time: new Date().toISOString(),<br>  });</pre><p>Next, we can define a function to simulate geofencing transition alerts in our app using the geofenceData object as a source of mock data.</p><pre>function addMarker(lnglat) {<br>      const marker = new tt.Marker({ draggable: true })<br>        .setLngLat(lnglat)<br>        .addTo(map);<br> <br>      function onDragEnd() {<br>        var lngLat = marker.getLngLat();<br>        new tt.Popup({ closeOnClick: false })<br>          .setLngLat(lngLat)<br>          .setHTML(<br>            `&lt;div&gt;<br>            &lt;p&gt; The object &quot;${geofenceData.object}&quot; crossed &quot;${geofenceData.fenceName}&quot; at ${geofenceData.time}&lt;/p&gt;<br>          &lt;/div&gt;`<br>          )<br>          .addTo(map);</pre><pre>marker.on(&quot;dragend&quot;, onDragEnd);</pre><pre>      }</pre><p>The addMarker function creates a draggable marker centered on the point a user clicks. When the <a href="https://api.tomtom.com/maps-sdk-for-web/6.x/6.16.0/documentation/dist/modules/Maps.html#property_Marker">marker</a> is dragged and dropped, a cancelable <a href="https://api.tomtom.com/maps-sdk-for-web/6.x/6.16.0/documentation/dist/modules/Maps.html#property_Popup">popup</a> containing the mock data that we added to the application’s state is created at the point where the marker was dropped.</p><p>Lastly, we add an on-click handler to the map to call addMarker whenever the map is clicked:</p><pre>map.on(&quot;click&quot;, (e) =&gt; {<br>      addMarker(e.lngLat);<br>    });</pre><p>With that, we have an application that can create real geofences around geographical locations of interest and mimics geofencing crossing alerts. Try it out <a href="https://codesandbox.io/s/geofencing-in-react-yviy6?file=/src/App.js">on CodeSandbox</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aggg561xmWJNzxx0.jpg" /></figure><h3>NEXT STEPS</h3><p>Creating and managing a geofence is just one of the features TomTom’s Geofencing API offer. TomTom’s wide range of services enables you to track a vehicle’s location relative to a fence, get notified when a car crosses a fence, determine how long an object has been within and outside a fence, and so much more.</p><p>All Postman requests made using the Geofencing API can be found in this <a href="https://github.com/joserojas-tomtom/TrackingFamilyPostmanCollection">Postman collection</a>. Check out our blog post titled <a href="https://developer.tomtom.com/blog/decoded/what-geofencing">What is Geofencing</a>? to learn more about geofencing.</p><p>Visit TomTom’s developer portal and <a href="https://developer.tomtom.com/user/register">sign up for a free developer account</a> to start integrating our web SDK and the Geofencing API into your applications today.</p><p>Happy mapping!</p><p><em>This article was originally published at developer.tomtom.com/blog.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66ccc3ef4d08" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tomtom-developers/creating-and-using-tomtom-geofences-with-react-66ccc3ef4d08">Creating and Using TomTom Geofences with React</a> was originally published in <a href="https://medium.com/tomtom-developers">TomTom Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fresh Maps are Crucial in Urban City Centers: Here’s Why]]></title>
            <link>https://medium.com/tomtom-developers/fresh-maps-are-crucial-in-urban-city-centers-heres-why-907bbc80ac6f?source=rss----9c5d61983c4b---4</link>
            <guid isPermaLink="false">https://medium.com/p/907bbc80ac6f</guid>
            <category><![CDATA[urban]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[poi]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[developer]]></category>
            <dc:creator><![CDATA[TomTom Developers]]></dc:creator>
            <pubDate>Wed, 11 May 2022 22:57:54 GMT</pubDate>
            <atom:updated>2022-04-29T21:11:15.717Z</atom:updated>
            <content:encoded><![CDATA[<h4>Road closures are constantly shifting in urban areas. Updated map data helps keep up with changes.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JA3ngMNA71bx7UHvQdh7CA.jpeg" /></figure><p>As urban populations grow and roads are more congested, it’s becoming more challenging for commuters to reach their destination. Then, during the COVID-19 pandemic, many roads closed, triggering a whole host of route changes in a short amount of time. With these continual changes, fresh map data has become even more critical for ensuring accurate trip routing.</p><p>Let’s explore how fresh maps are critical for helping users navigate urban city centers. We’ll discuss how TomTom — one of the most widely-used mapping services — helps ensure map information is up-to-date. We’ll also explore how TomTom enables developers to guide map users to their destination.</p><h3>MAP DATA CHANGES FREQUENTLY</h3><p>There’s always something happening in the city. Traffic congestion and scheduled road maintenance are two significant challenges to anyone trying to navigate densely-populated city centers. Plus, construction often requires adjacent road closures, and a new building is always going up somewhere. Then, just when the way seems clear, suddenly there’s a traffic accident or burst water main. It’s not all bad, though. Sometimes festivals and parades close roads so city-dwellers and visitors can come together and celebrate holidays, heroes, and diversity.</p><p>There are plenty of reasons why getting around urban areas is especially challenging. Luckily, mapping companies such as TomTom keep track of all these road closures and congestion, making this recent data available to their developers. Armed with this updated information, developers can help their users find the best routes to avoid closures and arrive at their destination safe and sound. If traffic changes, the fresh information can route users around inaccessible areas in real-time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/0*MKOd5lgzoIzZNbaW.jpg" /></figure><h3>COVID-19 TRIGGERED EVEN MORE MAP CHANGES</h3><p>During COVID-19, many cities began converting roadways into outdoor dining areas to cope with indoor dining restrictions to help restaurants stay in business. Some also turned roads into parkettes to encourage residents to get out for some socially-distanced exercise and fresh air. Some cities received such positive feedback about these road conversions that they’ve extended the programs even while restrictions lift.</p><p>But these changes can come and go. For example, cities in colder climates may convert streets to restaurant patios in the summer, then re-open roads to traffic in the winter when residents are unlikely to enjoy outdoor dining. The opposite happens in hotter climates when parklets atop asphalt are too hot for citizens to enjoy safely during the height of summer, but are perfect for outdoor activities during cooler months.</p><p>As great as these programs are, they pose some challenges for anyone trying to get around the city. Outdated maps may show a wide-open street while, in reality, it’s filled with diners enjoying an evening meal. And the inverse is true as well: Old maps may continue to mark street closures when patio season is long past. Fresh map data is crucial for ensuring developers guide their users around obstacles to the most open routes, even when the situation changes daily.</p><h3>HOW TO KEEP UP WITH MAP CHANGES</h3><p>TomTom offers an integrated system to reflect map changes without delay. These updates help deal with the outrageous volume of road network changes and temporary road conditions and incidents. More than <a href="https://www.tomtom.com/blog/traffic-and-travel-information/covid-19-road-closures/">600 million drivers</a> use our real-time traffic data to get to their destination quickly, comfortably, and safely.</p><p>TomTom map services promise to provide the most up-to-date and accurate traffic data for applications and devices. This fresh data helps determine the best route for any journey. Plus, our developer tools enable software makers to integrate a mapping system into their applications seamlessly and efficiently.</p><p>Changing conditions affect how developers build map services. Bigger, more permanent infrastructure changes triggered by COVID-19 also help inform TomTom’s cumulative historical traffic — where drivers are bypassing previously popular roads with a return to office commuting and city planning changes, large changes are signified, which help inform the community of expected travel times, slowdowns, and other incidents.</p><p>Luckily, route planning with TomTom also includes traffic information. When developers use the Routing API, the routing information provides directions for cars, trucks, and electric vehicles, enhanced with historical real-time traffic and incident information.</p><p>When integrating mapping services into their applications, developers must consider several aspects of their maps to make them the most functional, accurate, and enjoyable to use. <strong>Let’s look at some things you’ll want to consider when you integrate mapping services into your application.</strong></p><h3>DISPLAY VITAL INFORMATION</h3><p>Maps need to show temporary restrictions and closures. One of the most efficient ways to reduce traffic congestion is to inform drivers of potential road blockages before they occur. Then, these drivers can find a new route quickly.</p><p>Instead of developers integrating traffic services from scratch, they can use the <a href="https://www.tomtom.com/products/road-event-reporter/">TomTom Road Event Reporter</a>. This new, free service is available for cities, road authorities, and others seeking to reduce road congestion. We designed Road Event Reporter to provide adequate information on roadwork or stoppages to millions of digital map users.</p><h3>INCLUDE ACCURATE ROUTING</h3><p>Routing is one of the most vital aspects of map integration that developers need to consider. After all, no application maker wants to give users directions they can’t follow due to new route restrictions or road closures.</p><p>The <a href="https://developer.tomtom.com/routing-api">TomTom Routing API</a> helps developers integrate mapping services into their applications seamlessly. This routing information then provides directions for cars, trucks, and electric vehicles, enhanced with real-time traffic and incidents information.</p><h3>HIGHLIGHT POINTS OF INTEREST</h3><p>While these temporary parkettes and patios can be challenging for motorists, some urban dwellers and visitors actively seek out these new spaces. Developers can provide up-to-date information, so visitors know these <a href="https://developer.tomtom.com/blog/decoded/understanding-places-and-poi-apis">points of interest</a> are active before they set out. After all, nobody wants to dress up for that popular new restaurant on a warm fall evening only to discover the temporary patio is full of cars again.</p><p>Through TomTom’s partnership with Foursquare, developers can also highlight information such as opening times, reviews, and ratings, so users can easily learn more about each destination.</p><p>Developers must frequently refresh their application’s data to ensure accurate maps and routing, especially in city centers. This fresh information ensures users can find the venues they seek and know in advance if the point of interest is operational.</p><h3>CONSIDER USER EXPERIENCE</h3><p>Don’t overlook the user experience. It’s very important when you’re integrating maps. Because mapping services work around updating fresh data almost every time, developers need to ensure the map will fulfill users’ needs and that it’s usable.</p><p>There should be a synergy between the data being displayed to the user and what the user really needs. Make sure map functionalities are easy to navigate. Asking for user feedback can be helpful, too, so you can make changes that make it easier for your users to consult the map.</p><p>For optimal user experience, consider how your maps look. You can easily <a href="https://developer.tomtom.com/blog/build-different/5-ways-create-unique-map-experience-tomtom-maps-apis">style</a> TomTom maps to suit your users’ needs and complement your application’s look by switching to night mode, changing the road color, customizing markers and vehicle icons, removing landmark labels, and more.</p><h3>CONCLUSION</h3><p>Changes to urban centers are likely to continue, and they’re accompanied by the usual road congestion, construction, festivals, and other road-limiting events. Because of this, developers need to think about how they can update their maps continually with the most up-to-date information.</p><p>TomTom helps developers find recent map data to aid map displays, routing, and points of interest. With this timely data, urban residents and visitors can enjoy the best possible user experience as accurate maps efficiently get them to their destination. To learn how TomTom can enhance your urban-focused application, <a href="https://developer.tomtom.com/">start building with TomTom maps</a> today.</p><p><em>This article was originally published at </em><a href="https://developer.tomtom.com/blog">developer.tomtom.com/blog</a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=907bbc80ac6f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tomtom-developers/fresh-maps-are-crucial-in-urban-city-centers-heres-why-907bbc80ac6f">Fresh Maps are Crucial in Urban City Centers: Here’s Why</a> was originally published in <a href="https://medium.com/tomtom-developers">TomTom Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using TomTom Maps APIs to Assist EV-Powered Food Delivery and On-Demand Services]]></title>
            <link>https://medium.com/tomtom-developers/using-tomtom-maps-apis-to-assist-ev-powered-food-delivery-and-on-demand-services-35d6f71b32a8?source=rss----9c5d61983c4b---4</link>
            <guid isPermaLink="false">https://medium.com/p/35d6f71b32a8</guid>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[mapping]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[TomTom Developers]]></dc:creator>
            <pubDate>Wed, 11 May 2022 22:57:24 GMT</pubDate>
            <atom:updated>2022-04-25T02:07:03.832Z</atom:updated>
            <content:encoded><![CDATA[<p>Tools like Along Route Search and Calculate Reachable Range help optimize electric vehicle use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_HmZ2VEO4PO0dV8Zb51AUw.jpeg" /></figure><p>Geocoding is the bedrock of any mapping or location management application, but many people don’t really know what “geocoding” means.</p><p>At its most basic, geocoding is just a search. It’s the process of taking the description of a location — an address, or a store name, or maybe just a keyword like “pizza” — and returning the latitude, longitude, and related metadata for any locations matching the search terms.</p><p>Mapping software can highlight those specific locations on a map display using those latitude and longitude values. That might mean showing all takeout pizza shops within a 5-minute walk, or it might tell a delivery driver where to deliver pizza after a customer has placed an order.</p><p>And with those map pins, a location-enabled app can help food services find the nearest delivery driver, have them pick up the pizza, and route them to the customer’s home or office to drop it off. It can even calculate an estimated time of arrival (ETA), so the customer knows when to expect a knock and a hot lunch, ready to eat.</p><p>More people, including delivery and on-demand service drivers, are adopting electric vehicles (EVs) for improved fuel economy, reduced maintenance, and environmental concerns. The International Energy Agency noted in its <a href="https://www.iea.org/reports/global-ev-outlook-2021">Global EV Outlook 2021</a>, “After a decade of rapid growth, in 2020 the global electric car stock hit the 10 million mark, a 43% increase over 2019.”</p><p>In some regions, recharging locations are still more sparsely distributed than gas stations and sometimes tricky to find — they may be in the corner of a parking lot rather than at prominent road intersections. EVs need compatible charging stations, and there may be competition for available charging stations at a given place and time. Freelance drivers hoping to optimize their time on the road can gain a crucial advantage by using software providing timely, accurate information about driving range, charging time, and available charging locations.</p><p>What do search and routing have to do with EVs, then? EVs have unique location search and routing needs due to energy capacity and range challenges.</p><p>TomTom’s flexible APIs and SDKs help you build applications that run on-demand and mobility businesses such as ridesharing, food and parcel delivery, and more. And these solutions support both traditional internal combustion vehicles and tomorrow’s EV fleets’ unique needs.</p><p>In this article, we’ll examine some of the unique search and routing needs of EVs — particularly in the context of mobility and on-demand businesses — and the TomTom services you can use to build apps that meet those needs.</p><h3>SEARCH, GEOCODING, AND ROUTING</h3><p>Location search — geocoding — is often the first step in any mapping or mobility application. This part of the application is broadly applicable to all vehicle types, whether internal combustion or EVs.</p><p>You might create an application that lets consumers find nearby stores, restaurants, or other businesses offering delivery services. Consumers search for “pizza” and get a list of nearby restaurants, displayed with pushpins on a map. Maybe touching the pushpin lets them place an order through the app.</p><p>A customer places an order and provides a delivery address. You built the store’s fulfillment application to search for and confirm the delivery address. Then it gives the address text to the delivery driver to recognize the street and number. It also provides the coordinates to display the address on a map. It might also include details such as which side of the road to park on and the location of an apartment building’s front door.</p><p>Your app also uses the delivery address’s geocoded coordinates to calculate an efficient route for the driver, taking into account information like real-time and historical traffic. You can even calculate the ETA and tell the customer when to expect their delivery.</p><p>As a developer, you might build this app using the Search API <a href="https://developer.tomtom.com/search-api/search-api-documentation-search/category-search">Category Search</a> to optimize search around a certain kind of business, like restaurants. You might also use <a href="https://developer.tomtom.com/search-api/search-api-documentation-search/geometry-search">Geometry Search</a> to limit results to a given delivery service area or <a href="https://developer.tomtom.com/search-api/documentation/search-service/along-route-search">Along Route Search</a> to find points of interest (POIs) along a specified path.</p><p>The API response provides information about a point of interest (POI) for use in your app that includes everything from address, phone number, and website to nearby intersections and more.</p><pre>&quot;poi&quot;: {<br>    &quot;name&quot;: &quot;Upper Crust Pizza &amp; Pasta&quot;,<br>    &quot;phone&quot;: &quot;+(1)-(831)-4762333&quot;,<br>    &quot;url&quot;: &quot;www.uppercrustsc.com/&quot;,<br>    &quot;brands&quot;: [<br>      {<br>        &quot;name&quot;: &quot;Upper Crust&quot;<br>      }<br>    ],<br>    ...<br>    &quot;categories&quot;: [<br>      &quot;pizza&quot;,<br>      &quot;restaurant&quot;<br>    ],<br>    &quot;openingHours&quot;: {<br>      &quot;mode&quot;: &quot;nextSevenDays&quot;,<br>      &quot;timeRanges&quot;: [<br>        {<br>          &quot;startTime&quot;: {<br>            &quot;date&quot;: &quot;2019-02-05&quot;,<br>            &quot;hour&quot;: 7,<br>            &quot;minute&quot;: 0<br>          },<br>          &quot;endTime&quot;: {<br>            &quot;date&quot;: &quot;2019-02-05&quot;,<br>            &quot;hour&quot;: 21,<br>            &quot;minute&quot;: 0<br>          }<br>        },<br>        ...<br> &quot;address&quot;: {<br>    &quot;streetNumber&quot;: &quot;2501&quot;,<br>    &quot;streetName&quot;: &quot;Soquel Dr&quot;,<br>    &quot;municipalitySubdivision&quot;: &quot;Santa Cruz, Live Oak&quot;,<br>    &quot;municipality&quot;: &quot;Santa Cruz, Live Oak&quot;,<br>    &quot;countrySecondarySubdivision&quot;: &quot;Santa Cruz&quot;,<br>    &quot;countryTertiarySubdivision&quot;: &quot;Santa Cruz&quot;,<br>    &quot;countrySubdivision&quot;: &quot;CA&quot;,<br>    &quot;postalCode&quot;: &quot;95065&quot;,<br>    &quot;extendedPostalCode&quot;: &quot;950652023&quot;,<br>    &quot;countryCode&quot;: &quot;US&quot;,<br>    &quot;country&quot;: &quot;United States Of America&quot;,<br>    &quot;countryCodeISO3&quot;: &quot;USA&quot;,<br>    &quot;freeformAddress&quot;: &quot;2501 Soquel Dr, Santa Cruz, CA 95065&quot;,<br>    &quot;countrySubdivisionName&quot;: &quot;California&quot;,<br>    &quot;localName&quot;: &quot;Santa Cruz&quot;<br>  },<br>  &quot;position&quot;: {<br>    &quot;lat&quot;: 36.98844,<br>    &quot;lon&quot;: -121.97483<br>  },</pre><p>Once you have a destination — whether for a customer placing an order or reservation or a delivery location — you’d use the Routing API <a href="https://developer.tomtom.com/routing-api/routing-api-documentation-routing/calculate-route">Calculate Route</a> endpoint, which calculates a route from a location to an endpoint. You can then display this route to the driver. The API can also return travel time, ETA, and traffic information.</p><pre>&quot;routes&quot;: [<br>    {<br>      &quot;summary&quot;: {<br>        &quot;lengthInMeters&quot;: 1147,<br>        &quot;travelTimeInSeconds&quot;: 161,<br>        &quot;trafficDelayInSeconds&quot;: 15,<br>        &quot;departureTime&quot;: &quot;2015-04-02T15:01:57+02:00&quot;,<br>        &quot;arrivalTime&quot;: &quot;2015-04-02T15:04:38+02:00&quot;,<br>        &quot;noTrafficTravelTimeInSeconds&quot;: 120,<br>        &quot;historicTrafficTravelTimeInSeconds&quot;: 157,<br>        &quot;liveTrafficIncidentsTravelTimeInSeconds&quot;: 161,<br>        &quot;batteryConsumptionInkWh&quot;: 0.155,<br>        &quot;deviationDistance&quot;: 1735,<br>        &quot;deviationTime&quot;: 127,<br>        &quot;deviationPoint&quot;: {<br>          &quot;latitude&quot;: 52.50904,<br>          &quot;longitude&quot;: 13.42912<br>        },</pre><h3>SEARCH AND ROUTING FOR EVS</h3><p>Sometimes a driver wants to find out about POIs at or near a given location. For EVs, a popular search is charging stations near the current location or along a route. Finding charging stations is an example of searching by category, rather than using the Search API and <a href="https://developer.tomtom.com/search-api/search-api-documentation-search/fuzzy-search">Fuzzy Search</a>.</p><p>As with searching for an address or store name, category search returns the geocoded results for a type of location, such as fueling stations or charging stations. These results can feed other applications, such as routing and ETA, which deliver actionable information back to the user.</p><p>For EV-specific search applications, TomTom incorporated charging station search into their Search API. The API enables developers to integrate the following information into their applications:</p><ul><li>Charging station location and availability</li><li>Charging station plug type and charge power compatibility</li></ul><p>So, drivers can find the nearby, available, and compatible charging stations from your app. The concept of a reachable range is fundamental in EV, especially for food delivery, where accepting an order outside the vehicle’s reachable range would be disastrous. Reachable range refers to the distance an EV can travel without recharging, a vital consideration when drivers busily deliver orders across the city. The Routing API supports finding this information through the <a href="https://developer.tomtom.com/routing-api/routing-api-documentation-routing/calculate-reachable-range">Calculate Reachable Range</a> service.</p><p>The Calculate Route service discussed earlier accommodates optimized routes with given route types (the fastest, the most economical, one that avoids tolls, and so on). It also enables your app to specify engine type — fuel or electric — and incorporate EV consumption into your routes.</p><p>For example, you might have noticed this data point in the API response shown earlier:</p><pre>&quot;batteryConsumptionInkWh&quot;: 0.155,</pre><p>The TomTom Routing API supports optional parameters for an <a href="https://developer.tomtom.com/routing-api/routing-api-documentation-routing/common-routing-parameters#electric-consumption">Electric Consumption</a> model that lets your app provide vehicle-specific power usage profiles to generate even more accurate and helpful routing details.</p><p>The Calculate Reachable Range endpoint can provide EV-specific routing information for your app, including limits to the vehicle’s range, based on given charge and consumption parameters.</p><p>If you’re building mobility and on-demand focused applications, the reachable range capability helps ensure drivers only volunteer for reachable locations. This information enables drivers to optimize vehicle use while considering service commitments.</p><p>Another helpful feature for route planning is the ability to configure API route requests that specify fuel economy. The Routing API services enable selecting an “eco” route type. Combined with a detailed Electric Consumption model, vehicle weight, and other details, you can help users predict travel time and the amount of energy needed.</p><h3>WRAPPING UP</h3><p>The introduction of EV changes the requirements for food delivery and other on-demand delivery or ridesharing applications. Fuel economies provided by EVs, coupled with the increasing popularity of last-mile services, are driving new business opportunities. These factors are also introducing new levels of complexity to freelance drivers, who must consider the specific issues associated with recharging EVs to achieve their service commitments.</p><p>Applications must present new factors such as reachable range to advise the driver. These applications must incorporate the data to support analyzing these ranges to address EV challenges.</p><p>These complexities create new opportunities for application development. TomTom’s APIs and SDKs offer developers the tools they need to incorporate EV location management into their on-demand and delivery applications. For more information, visit the <a href="https://developer.tomtom.com/">TomTom Developer Portal</a> and sign up for your free access today.</p><p>To learn more about EV-related topics, check out these articles:</p><ul><li><a href="https://developer.tomtom.com/blog/perspective/why-developers-should-care-about-ev-drivers">Why Developers Should Care About EV Drivers</a></li><li><a href="https://developer.tomtom.com/blog/build-different/adding-ev-routing-tomtom-web-map-understanding-apis">Adding EV Routing to a TomTom Web Map: Understanding the APIs</a></li><li><a href="https://developer.tomtom.com/blog/build-different/adding-ev-routing-tomtom-web-map-building-web-application">Adding EV Routing to TomTom Web Map: Building the Web Application</a></li></ul><p>Happy mapping!</p><p><em>This article was originally published at </em><a href="https://developer.tomtom.com/blog">developer.tomtom.com/blog</a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35d6f71b32a8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tomtom-developers/using-tomtom-maps-apis-to-assist-ev-powered-food-delivery-and-on-demand-services-35d6f71b32a8">Using TomTom Maps APIs to Assist EV-Powered Food Delivery and On-Demand Services</a> was originally published in <a href="https://medium.com/tomtom-developers">TomTom Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Real-Time Construction Fleet Planning App with TomTom Maps APIs]]></title>
            <link>https://medium.com/tomtom-developers/creating-a-real-time-construction-fleet-planning-app-with-tomtom-maps-apis-cd99e3e00d77?source=rss----9c5d61983c4b---4</link>
            <guid isPermaLink="false">https://medium.com/p/cd99e3e00d77</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[location]]></category>
            <category><![CDATA[geofencing]]></category>
            <dc:creator><![CDATA[TomTom Developers]]></dc:creator>
            <pubDate>Tue, 19 Apr 2022 21:02:57 GMT</pubDate>
            <atom:updated>2022-04-05T04:53:15.405Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to provide your application’s location-related requirements with TomTom Maps APIs.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1RacnlTI1ZNoti00reCKhw.jpeg" /></figure><p>This tutorial explores how we can seamlessly use the TomTom Maps APIs to solve our application’s location-related requirements. We’ll build a <a href="https://codesandbox.io/s/construction-fleet-app-lygy2">real-time tracking app</a> to help users manage a construction company’s vehicle fleet.</p><p>We’ll see how to use:</p><ul><li>The Routing API and its Calculate Route method to calculate the possible routes construction vehicles can take to sites based on specific parameters.</li><li>The Location History API to track the vehicle’s location.</li><li>The Geofencing API to determine when construction vehicles are close to the site so workers can prepare for their arrival.</li></ul><p>We’ll discuss each app feature requirement, why the tools are relevant to the use-case we’re solving, and how to implement them. You just need to know some JavaScript, HTML, and CSS to follow along. We’ll guide you through using TomTom’s tools.</p><p>Let’s dive in!</p><h3>PREREQUISITES</h3><p>To start using TomTom Maps API, you need an API key. This key will authorize your request to use the service.</p><p>Don’t have one yet? Visit <a href="https://developer.tomtom.com/how-to-get-tomtom-api-key">How to get a TomTom API key</a> to learn more or <a href="https://developer.tomtom.com/user/register">sign up for a developer account</a> to get one. Your free developer account provides access to thousands of daily requests and is acceptable for commercial use. Just pay-as-you-grow when your app becomes popular.</p><h3>SETUP</h3><p>First, we’ll need to initialize the map and its user interface (UI). The app will comprise two parts: a map on the right, and a sidebar with form controls on the left.</p><p>Create an index.html file in a folder on your computer. Then, open the file in a code editor and populate it with this code:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>    &lt;head&gt;<br>        &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>        &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot; /&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>        &lt;title&gt;Construction Fleet Planning App&lt;/title&gt;<br>        &lt;!-- Includes SDK&#39;s stylesheet --&gt;<br>        &lt;link href=&quot;https://api.tomtom.com/maps-sdk-for-		web/cdn/6.x/6.15.0/maps/maps.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;<br>        &lt;!-- Includes SDK&#39;s JavaScript--&gt;<br>        &lt;script src=&quot;https://api.tomtom.com/maps-sdk-for-web/cdn/6.x/6.15.0/maps/maps-web.min.js&quot;&gt;&lt;/script&gt;<br>        &lt;script src=&quot;https://api.tomtom.com/maps-sdk-for-web/cdn/6.x/6.15.0/services/services-web.min.js&quot;&gt;&lt;/script&gt;<br>        &lt;!-- CSS styles --&gt;<br>&lt;link rel=&quot;stylesheet&quot; href=&quot;./styles.css&quot; /&gt;</pre><pre>    &lt;/head&gt;<br>    &lt;body&gt;<br>        &lt;div class=&quot;container&quot;&gt;<br>            &lt;div class=&quot;control-panel&quot;&gt;<br>                &lt;h2 class=&quot;control-panel__title&quot;&gt;Construction Fleet Planing App&lt;/h2&gt;<br>                &lt;form class=&quot;control-panel__controls&quot;&gt;<br>                    &lt;fieldset&gt;<br>                        &lt;label for=&quot;start-address&quot; class=&quot;&quot;&gt;Start Address:&lt;/label&gt;<br>                        &lt;input type=&quot;text&quot; class=&quot;&quot; placeholder=&quot;san diego&quot; id=&quot;start-address&quot; /&gt;<br>                    &lt;/fieldset&gt;<br>                    &lt;fieldset&gt;<br>                        &lt;label for=&quot;end-address&quot; class=&quot;&quot;&gt;End Address:&lt;/label&gt;<br>                        &lt;input type=&quot;text&quot; class=&quot;&quot; placeholder=&quot;lily avenue&quot; id=&quot;end-address&quot; /&gt;<br>                    &lt;/fieldset&gt;<br>                    &lt;fieldset&gt;<br>                        &lt;label for=&quot;arrival-time&quot; class=&quot;&quot;&gt;Estimated Arrival Time:&lt;/label&gt;<br>                        &lt;input type=&quot;datetime-local&quot; id=&quot;arrival-time&quot; /&gt;<br>                    &lt;/fieldset&gt;<br>                    &lt;fieldset&gt;<br>                        &lt;label for=&quot;explosives-present&quot;&gt;Vehicle is carrying explosives:&lt;/label&gt;<br>                        &lt;input type=&quot;checkbox&quot; id=&quot;explosives-present&quot; value=&quot;USHazmatClass1&quot; /&gt;<br>                    &lt;/fieldset&gt;<br>                    &lt;fieldset&gt;<br>                        &lt;label for=&quot;gas-present&quot;&gt;Vehicle is carrying compressed gas:&lt;/label&gt;<br>                        &lt;input type=&quot;checkbox&quot; id=&quot;gas-present&quot; value=&quot;USHazmatClass2&quot; /&gt;<br>                    &lt;/fieldset&gt;<br>                    &lt;fieldset&gt;<br>                        &lt;label for=&quot;is-truck&quot;&gt;Vehicle is a truck:&lt;/label&gt;<br>                        &lt;input type=&quot;checkbox&quot; id=&quot;is-truck&quot; value=&quot;truck&quot; /&gt;<br>                    &lt;/fieldset&gt;<br>                    &lt;button class=&quot;control-panel__btn&quot;&gt;Track&lt;/button&gt;<br>                &lt;/form&gt;<br>            &lt;/div&gt;<br>            &lt;div id=&quot;map&quot; class=&quot;map&quot;&gt;&lt;/div&gt;<br>        &lt;/div&gt;<br>            &lt;/script&gt;<br>        &lt;script&gt;<br>            const apiKey = &quot;&lt;Your_API_Key&gt;&quot;;<br>            const SanJose = {lon: -121.867905, lat: 37.279518}<br>            const map = tt.map({<br>                key: apiKey,<br>                container: &quot;map&quot;,<br>                center: SanJose,<br>                zoom: 10,<br>            });<br>            map.addControl(new tt.FullscreenControl());<br>            map.addControl(new tt.NavigationControl());<br>&lt;/script&gt;</pre><p>Here, the tt.map constructor creates a map. The container parameter requires the ID of an HTML element containing the map. The center parameter centers the map on San Jose, California, using its longitude and latitude coordinates.<br> <br>Remember to replace &lt;Your_API_Key&gt; with your API key from your developer account.</p><p>Now, include your CSS styles in a styles.css file containing the following code. The top of the HTML file will link to this CSS file.</p><pre>*,<br>*:before,<br>*:after {<br>  box-sizing: border-box;<br>  padding: 0;<br>  margin: 0;<br>}<br>body {<br>  color: #5f5f5f;<br>  font-size: 1.1rem;<br>}<br>.container {<br>  width: 100vw;<br>  height: 100vh;<br>  display: flex;<br>}<br>.control-panel {<br>  width: 30%;<br>  box-shadow: 1px 0px 12px 0px #00000067;<br>  height: 100%;<br>  overflow-x: hidden;<br>  overflow-y: auto;<br>}<br>.control-panel::-webkit-scrollbar {<br>  width: 0px;<br>  height: 0px;<br>}<br>.control-panel__title {<br>  font-size: 1.8rem;<br>  margin: 1rem 0;<br>  padding: 1rem;<br>  text-align: center;<br>  border-bottom: 3px solid #181616;<br>  box-shadow: 0px 3px 6px 0px #00000029;<br>}<br>.control-panel__controls {<br>  display: flex;<br>  flex-flow: column nowrap;<br>  align-items: center;<br>  justify-content: space-around;<br>}<br>.control-panel__controls fieldset {<br>  width: 95%;<br>  margin: 1.2rem 0;<br>  border: 0;<br>  display: flex;<br>  align-items: center;<br>  justify-content: space-between;<br>}<br>fieldset input {<br>  min-width: 58%;<br>  outline: none;<br>  font-size: 1rem;<br>  border: 2px solid #ccc;<br>  padding: 0.8rem;<br>  border-radius: 8px;<br>}<br>fieldset input:focus {<br>  border: 2px solid #007fff;<br>}<br>.control-panel__btn {<br>  padding: 1rem;<br>  font-size: 1.3rem;<br>  outline: none;<br>  border: none;<br>  border-radius: 8px;<br>  color: #fff;<br>  background: #007fff;<br>  width: 45%;<br>}<br>.map {<br>  width: 70%;<br>  height: 100%;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*YqAPp3ejJG-c2mDL.jpg" /></figure><p>You should have a UI similar to the image above. With the setup complete, we can start implementing the app’s feature requirements.</p><h3>CALCULATING THE ROUTE</h3><p>Managers can’t identify the best routes construction vehicles should take to arrive and deliver materials on time by simply looking at the map. But early or late arrivals can ruin the materials or cause delays, so route information is vital.</p><p>TomTom’s Calculate Route service determines the possible routes between an origin and a destination location, based on specific parameters like the type of vehicle, estimated time of arrival, and the fastest route.</p><p>We can find the best routes for construction vehicles to reach the construction site using Calculate Route.</p><p>First, we add <a href="https://developer.tomtom.com/location-history-api/">markers</a> to the origin and destination points on the map, where the LngLat parameter is the longitude and latitude coordinates of these locations. We store each marker in the markers array. This information will come in handy when it’s time to call the calculate route service.</p><pre>//markers array<br>      const markers = [];<br>      // add marker<br>function addMarker(lnglat) {<br>        const marker = new tt.Marker().setLngLat(lnglat).addTo(map);<br>        markers.push(marker.getLngLat());<br>      }</pre><p>Next, the app has two input fields to get the starting and destination addresses. The app then passes these addresses to the calculate route service. getAddress gets geographical coordinates for these addresses using the <a href="https://developer.tomtom.com/search-api/search-api-documentation-search/fuzzy-search">Fuzzy Search service</a>, then passes the coordinates to the addMarker function.</p><pre>// get the lnglat coordinates of an address<br>      async function getAddress(searchValue) {<br>        let address = tt.services<br>          .fuzzySearch({<br>            key: API_KEY,<br>            query: searchValue,<br>            lon:  -121.8863286,<br>            lat: 37.3382082,<br>          })<br>          .then((cordinates) =&gt; {<br>            // add marker<br>            addMarker(cordinates.results[0].position);<br>          const { lng, lat } = cordinates.results[0].position;<br>            return { lng, lat };<br>          });<br>return address;<br>      }</pre><p>Now that our app has stored the geographical coordinates, we can call the calculate route service:</p><pre>// get the values of the input fields for configuring the calculateRoute service<br>      const isTruck = document.getElementById(&quot;is-truck&quot;).checked<br>        ? document.getElementById(&quot;is-truck&quot;).value<br>        : null;<br>      const arrivalTime = document.getElementById(&quot;arrival-time&quot;).checked<br>        ? document.getElementById(&quot;arrival-time&quot;).value<br>        : null;<br>      const carriesExplosive = document.getElementById(&quot;explosives-present&quot;)<br>        .checked<br>        ? document.getElementById(&quot;explosives-present&quot;).value<br>        : null;<br>      const carriesGas = document.getElementById(&quot;gas-present&quot;).checked<br>        ? document.getElementById(&quot;gas-present&quot;).value<br>        : null;<br> <br>    function getRoute(marker) {<br>        const routeOptions = {<br>          &quot;key&quot;: API_KEY,<br>          &quot;locations&quot;: marker,<br>          &quot;arriveAt&quot;: arrivalTime,<br>          &quot;travelMode&quot;: isTruck,<br>  &quot;vehicleLoadType&quot;: [ carriesExplosive, carriesGas],<br>          &quot;vehicleCommercial&quot;: true,<br>        };<br> <br>        tt.services.calculateRoute(routeOptions).then(function (response) {<br>          console.log(response.toGeoJson());<br>          console.log(response);<br>          var geojson = response.toGeoJson();<br>          map.addLayer({<br>            &quot;id&quot;: &quot;route&quot;,<br>            &quot;type&quot;: &quot;line&quot;,<br>            &quot;source&quot;: {<br>              &quot;type&quot;: &quot;geojson&quot;,<br>              &quot;data&quot;: geojson,<br>            },<br>            &quot;paint&quot;: {<br>              &quot;line-color&quot;: &quot;#4a90e2&quot;,<br>              &quot;line-width&quot;: 8,<br>            },<br>          });<br> <br>        var bounds = new tt.LngLatBounds();<br>        geojson.features[0].geometry.coordinates.forEach(function (point) {<br>        bounds.extend(tt.LngLat.convert(point)); // creates a bounding area<br>          });<br>          map.fitBounds(bounds, {<br>            duration: 200,<br>            padding: 50,<br>            maxZoom: 13,<br>          }); // zooms the map to the searched route<br>    });<br>  }</pre><p>In the code above, the tt.services.calculateRoute constructor calls the calculates route service. The constructor receives the routeOptions object containing properties like the type of loads onboard, time of arrival, vehicle type, and the locations property containing the origin and destination LngLat coordinates from the markers array.</p><p>Then, the service returns a promise. We’ll tap into this promise to get its response and draw the route’s path on the map.</p><p>We need to tell our application to run the code above when the user clicks the <strong>Track</strong> button.</p><pre>document.querySelector(&quot;.control-panel__btn&quot;)<br>        .addEventListener(&quot;click&quot;, function (e) {<br>          e.preventDefault();<br>          Promise.all([<br>            getAddress(document.getElementById(&quot;start-address&quot;).value),<br>            getAddress(document.getElementById(&quot;end-address&quot;).value),<br>          ])<br>             .then((points) =&gt; {     <br>              getRoute(points);<br>            })<br>            .then(() =&gt; {<br>              document.querySelectorAll(&quot;input&quot;).forEach((input) =&gt; {<br>                input.value = &quot;&quot;;<br>                input.checked = false;<br>              });<br>            });</pre><pre>        });</pre><p>See the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/0*TPYYn5FLoYIsIELd.jpg" /></figure><h3>ENABLING LOCATION HISTORY</h3><p>Construction managers need to know where their vehicles are and where they’ve been. This allows them to allocate assets efficiently and avoid idle equipment. TomTom’s Location History API enables us to store, retrieve, and track device location and movements.</p><p>To use the service, you need an admin key and a layer of security to complete API requests to the service.</p><p>You can generate an admin key using <a href="https://www.postman.com/">Postman</a> to send a POST request to <a href="https://api.tomtom.com/location/1/register?&amp;key=Your_API_Key">https://api.tomtom.com/location/1/register?&amp;key=Your_API_Key</a> with the following body:</p><pre>{<br>“secret”: &quot;your_secret&quot;,<br>}</pre><p>The body of the request takes a secret parameter. This secret is a password you’ll need for making any future configurations, so use a password you can remember and ensure you don’t lose it.</p><p>A successful response logs your admin key to the console:</p><pre>{<br>adminKey: your_admin_key<br>}</pre><h3>CREATING AN OBJECT</h3><p>Now, we can create an object representing the item we are tracking, such as a worker, phone, or vehicle.</p><p>To create an object, first send a post request to <a href="https://api.tomtom.com/locationHistory/1/objects/object?adminKey=Your_Admin_Key&amp;key=Your_API_KEY,">https://api.tomtom.com/locationHistory/1/objects/object?adminKey=Your_Admin_Key&amp;key=Your_API_KEY,</a> with the name of the object in the body:</p><pre>{<br> &quot;name&quot;: name,<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/0*bSCjGSBwMYEJIe6k.jpg" /></figure><p>Here’s a link to the request on Postman if you’d like to try it out: <a href="https://web.postman.co/workspace/My-Workspace~423b6c0c-e863-4974-8125-ecdb821e143b/request/12705763-548e8138-2682-4aa3-9725-ff7979aefdb6">Creating an object</a></p><p>The response will contain the object name and ID.</p><h3>WORKING WITH AN OBJECT’S LOCATION</h3><p>We can track an object’s location by storing and retrieving its positions from the service to know where it is and where it’s been.</p><p>To record an object’s location, you must give the service permission to store an object’s position. So, send a Post request to <a href="https://api.tomtom.com/locationHistory/1/settings?key=Your_API_Key&amp;adminKey=Your_Admin_Key">https://api.tomtom.com/locationHistory/1/settings?key=Your_API_Key&amp;adminKey=Your_Admin_Key</a> with a body of:</p><pre>{<br>  consentForStoringObjectsPositionsHistory: true,<br>}</pre><p>This call is a one-time request enabling storing an object’s location. Now, we can start tracking objects.</p><p>To track an object’s location, first, we need to start storing its changing positions as past positions, using the <a href="https://developer.tomtom.com/location-history-api/location-history-api-documentation-position-history-service/send-position">Send position</a> endpoint:</p><pre>// send object&#39;s location    <br>function sendPostion(lnglat) {<br>        let cordinates = lnglat;<br>        // create Json Object to store location<br>        let position = {<br>          type: &quot;Feature&quot;,<br>          geometry: {<br>            type: &quot;Point&quot;,<br>            coordinates: [cordinates.lng, cordinates.lat, 0],<br>          },<br>          object: &quot;Your_Object_ID&quot;<br>        };<br>        // Use fetch to send the location<br>        fetch(<br>          &quot;https://api.tomtom.com/locationHistory/1/history/positions?key=Your_Admin_Key &quot;,<br>          {<br>            method: &quot;POST&quot;,<br>            headers: {<br>              &quot;Content-Type&quot;: &quot;application/json&quot;,<br>            },<br>            body: JSON.stringify(position),<br>          }<br>        ).then((result) =&gt; {<br>          console.log(result);<br>        });<br>      }</pre><p>Now, we can get its past positions for tracking using the <a href="https://developer.tomtom.com/location-history-api/location-history-api-documentation-position-history-service/get-objects-position-history">get objects position</a> service:</p><pre>// get location history<br>      function getObjectLocations() {<br>const date = new Date().toISOString();<br>       fetch(<br>          &quot;https://api.tomtom.com/locationHistory/1/history/positions/Your_Object_Id?key=Your_API_Key&amp;adminKey=Your_AdminKey&amp;from=&quot;+date+&quot;&quot;<br>        )<br>          .then((response) =&gt; response.json())<br>          .then((result) =&gt; {<br>            const lngLatArray = result.positions.features.map(<br>              (feature) =&gt; feature.geometry.coordinates<br>            );<br>            console.log(lngLatArray);=<br>            lngLatArray.forEach((lngLat) =&gt; {<br>              addMarker(lngLat);<br>            });<br>          });<br>      }<br> <br> document.querySelector(&quot;.show-history&quot;).addEventListener(&quot;click&quot;, (e) =&gt; {<br>        e.preventDefault();<br>        getObjectLocations();<br>   });</pre><p>In this code, we add a marker to the map on page load. Every time the marker drags across the map, the code calls the sendPostion function to send the marker’s LngLat position to the location history API.</p><p>Then, when the user clicks the <strong>show-history</strong> button, the app calls the getObjectLocations function to get the object’s position history and render a marker on each of its previous positions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/0*bi5RrpeB7j8-ZVn_.jpg" /></figure><h3>ENABLING GEOFENCING</h3><p>TomTom’s Geofencing service lets you define and manage virtual borders (geofences) around specified locations. When we combine this geofencing with the Location History API, we can determine an object’s location relative to these virtual barriers. We can then know whether they’re located within, outside, or close to a geofenced area.</p><p>The app can notify managers when a vehicle is approaching a geofenced site. This notification enables the managers to ensure the site is ready to receive the vehicle’s contents, such as having workers ready to unload construction materials or use the concrete before solidification.</p><p>Just like Location History, Geofencing requires an admin key when accessing the service. However, you can only register one admin key per account, so we’ll use the same admin key we registered with the Location History API.</p><h3>CREATING A PROJECT</h3><p>Now that we have our admin key ready, we need to create a project. A project is an object that stores our geofences. We can store hundreds of geofences in a single project.<br> <br>First, we send a post request to the endpoint to create a project:</p><p>https://api.tomtom.com/geofencing/1/projects/project?adminKey&lt;ADMIN_KEY&gt;=&amp;key=&lt;API_KEY&gt;</p><p>We include the name of the project as a parameter in the body:</p><pre>{<br>  &quot;name&quot;: &quot;Project_Name&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/0*M0Zy4uUbDpqxMdsF.jpg" /></figure><p>Here’s a link to the request on Postman if you’d like to try it out: <a href="https://web.postman.co/workspace/My-Workspace~423b6c0c-e863-4974-8125-ecdb821e143b/request/12705763-87784c68-0ec7-473a-8c3f-9cbab1c33e32">Creating a Project</a></p><p>A successful response logs the project’s ID and name to the console.</p><h3>CREATING A GEOFENCE</h3><p>Now that we have created the project, we are ready to start creating geofences. We make a geofence around the construction site to track construction vehicle arrival.</p><p>To create a fence, we send a post request to the following:</p><p><a href="https://api.tomtom.com/geofencing/1/projects/$%7BprojectId%7D/fence?adminKey=Your_Admin_Key&amp;key=Your_API_Key">https://api.tomtom.com/geofencing/1/projects/${projectId}/fence?adminKey=Your_Admin_Key&amp;key=Your_API_Key</a></p><p>Remember to replace {projectId} in the request URL with the project ID you just created.</p><p>The request body should contain the following:</p><pre>{<br>    &quot;name&quot;: &quot;Area 1&quot;,<br>    &quot;type&quot;: &quot;Feature&quot;,<br>    &quot;geometry&quot;: {<br>        &quot;type&quot;: &quot;Point&quot;,<br>        &quot;radius&quot;: 11361.72744452612,<br>        &quot;shapeType&quot;: &quot;Circle&quot;,<br>        &quot;coordinates&quot;: [<br>            -121.892115,<br>            37.331016<br>        ]<br>    }<br>}</pre><p>The code above contains the details needed to create a fence around a location. The coordinates parameter takes the location’s latitude and longitude, and the shapeType parameter defines the fence’s shape (in this case, a circle). The response logs the request object above to the console, including the provided fence ID.</p><p>Now, we can display the geofence on our map:</p><pre>function displayFence() {<br>        fetch(&quot;https://api.tomtom.com/geofencing/1/fences/${fence id}?key=Your_API_Key&quot;)<br>          .then((response) =&gt; response.json())<br>          .then((result) =&gt; {<br>            console.log(result);<br>            map.addLayer({<br>              id: &quot;san jose&quot;,<br>              type: &quot;fill&quot;,<br>              source: {<br>                type: &quot;geojson&quot;,<br>                data: result,<br>              },<br>              paint: {<br>                &quot;fill-color&quot;: &quot;blue&quot;,<br>                &quot;fill-opacity&quot;: 0.4,<br>                &quot;fill-outline-color&quot;: &quot;blue&quot;,<br>              },<br>            });<br>          });<br>      }<br> <br>      map.on(&quot;load&quot;, () =&gt; {<br>        displayFence();<br>      });</pre><p>The code above calls the displayFence function when the map loads. This function displays the fence by fetching the fence details and drawing the shape on the map.</p><p>Remember to replace ${fence id} with your fence ID. The fence should now be visible on the map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*Lem5lymJRrXTrXkx.jpg" /></figure><h3>CREATING A TRANSITION ALERT RULE</h3><p>TomTom’s <a href="https://developer.tomtom.com/geofencing-api/documentation/product-information/introduction">Geofencing API</a> provides an alert service to notify your app when assets enter or leave geofences. You can use the same object with the Geofencing and Location History APIs interchangeably.<br> <br>First, you need to create a contact group. The contact group contains subscribed email addresses that will receive notifications from the service.</p><p>To set up a contact group, first, send a post request to <a href="https://api.tomtom/notifications/groups?key=Your_API_Key">https://api.tomtom/notifications/groups?key=Your_API_Key</a> with the request body:</p><pre>{<br>&quot;name&quot;: &quot;group_name&quot;,<br>&quot;webhookUrls&quot; : [],<br>&quot;emails&quot;: []<br>}</pre><p>The emails and webhooks parameters above will contain a list of URLs and email addresses to receive the messages.</p><p>A successful response logs the notification group ID to the console.</p><p>Next, send a post request to <a href="https://api.tomtom.com/geofencing/1/alerts/rules?key=Your_Admin_Key">https://api.tomtom.com/geofencing/1/alerts/rules?key=Your_Admin_Key</a> adminKey=Your_Admin_Key with the body:</p><pre>{<br>  &quot;name&quot;: &quot;Name of alert rule&quot;,<br>  &quot;project&quot;: &quot;Enter id of project to watch or *&quot;,<br>  &quot;fence&quot;: &quot;Id of fence to watch or *&quot;,<br>  &quot;object&quot;: &quot;id of object to watch or *&quot;,<br>  &quot;alertType&quot;: &quot;TRANSITION&quot;,<br>  &quot;alertRuleConstraints&quot;: {<br>    &quot;transitionType&quot;: &quot;ALL&quot;<br>  },<br>  &quot;notificationGroup&quot;: &quot;id of your notification group&quot;,<br>  &quot;enabled&quot;: true<br>}</pre><p>Now the app will notify the email address and URLs whenever an object enters the fence.</p><h3>NEXT STEPS</h3><p>Our construction company users now have a <a href="https://codesandbox.io/s/construction-fleet-app-lygy2">handy app</a> to plan fleet routes, track equipment locations, and receive an alert when a vehicle crosses a geofence and is on its way to the construction site. With all this information, the fleet manager can make the most efficient use of their equipment, ensure materials arrive when expected, and get workers ready to receive the materials — a boost to construction fleet efficiency with TomTom doing most of the heavy lifting.</p><p>From here, you can improve the app by including multiple construction sites, sorting equipment by vehicle type, adding authentication to restrict access to managers only, and much more.</p><p>Learn more about integrating TomTom’s Maps APIs into your applications to manage your fleets, locate vehicles, and track assets on a map in real-time. Visit the TomTom developer portal and <a href="https://developer.tomtom.com/user/register">sign up for a free developer account</a> today. Happy mapping!</p><p><em>This article was originally published at </em><a href="https://developer.tomtom.com/blog"><em>https://developer.tomtom.com/blog</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd99e3e00d77" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tomtom-developers/creating-a-real-time-construction-fleet-planning-app-with-tomtom-maps-apis-cd99e3e00d77">Creating a Real-Time Construction Fleet Planning App with TomTom Maps APIs</a> was originally published in <a href="https://medium.com/tomtom-developers">TomTom Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>