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

Turf.js integration

Purpose

This tutorial shows you how to integrate TomTom Maps SDK for Web with Turf.js and use some of its features. Turf.js. is an open source library for geospatial analysis. With this tutorial you can:

  • Learn how to display a well-defined and limited area (in our example: Amsterdam) on the map.
  • Learn how to calculate polygon’s area in square kilometers with Turf.js.
  • Find out how to check if some points are located within or outside of the area (polygon) with Turf.js.

1. Prerequisites

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

  • An SDK that can be downloaded from here: Downloads. Unzip it and save it in a folder. This tutorial assumes your folder is named ‘sdk’. If you choose another name, remember to change the provided paths to match.

    Check out the current file structure

    .
    └── sdk-tutorial
        └── sdk
            ├── LICENSE.txt
            ├── README.md
            ├── glyphs
            ├── images
            ├── map.css
            ├── mapbox-gl-js
            ├── sprites
            ├── styles
            ├── tomtom.min.js
            └── tomtom.min.js.map
        
  • API key

    Create your API key now

    To create a new API key you need to first register on the portal. Once you are logged in there are only two steps remaining:

    Create a new application in your Dashboard:

    Choose all the APIs:

    All set up. You can now click on your newly created app and copy your API key:

  • Coordinates

    How to find your company location coordinates?

    The simplest way for obtaining these coordinates is to go to api_explorer. First, click on Fuzzy Search and then on a Try it out button. Let's assume your company address is: '100 Century Center Ct 210, San Jose, CA 95112, USA'. You have to place it in a query field and clear other pre-populated fields, then scroll down and press the Execute button. Please take into account that you should not use special HTML characters (like '$','?',&','#') in address. In the response you can find section and there you can see that the very first item from the list of items matched your query. Look at the property below address fields. There you can see the data you need:

    <position>
        <lat>37.36729</lat>
        <lon>-121.91595</lon>
    </position>
  • Turf.js

    Add Turf.js to your project

    You can follow the Turf.js Getting started instructions. There are a few different ways to add the library to your project. In this tutorial, Turf.js is loaded via a script tag.

    1. Add the following script tag to the
    <script src='https://npmcdn.com/@turf/turf/turf.min.js'></script> 
    

2. Displaying the map

To display a map, use the following HTML5 code:

<!DOCTYPE html>
<html>
<head> 
  <meta charset="UTF-8"> 
  <title>TomTom Web SDK plus TURF</title> 
  <link rel='stylesheet' type='text/css' href='sdk/map.css'/> 
  <link rel='stylesheet' type='text/css' href='style.css'/>
  <script src='sdk/tomtom.min.js'></script>
  <script src='https://npmcdn.com/@turf/turf/turf.min.js'></script> 
</head>
<body>
  <div id='map'></div>
  <script src='app.js'></script>
</body>
</html>

Create file app.js with following code:

var map = tomtom.L.map('map', {
	key: '<your-api-key>',
	source: 'raster'
});

All javascript code should be added to this file.

Create style.css file with following code:

body {
 height: 100vh;
 width: 100vw;
 margin: 0;
 padding: 0;
}
#map {
 height: 100vh;
 width: 100vw;
}

3. Displaying a polygon on the map

Let's assume you offer your service only in the city area, in this example in Amsterdam. The application displays city area and its borders.

To display city boundaries, you need to retrieve a polygon from Additional Data Service. Before that you need to get geometry.id of that city by querying Fuzzy Search endpoint.

To implement this, perform the following steps:

You can find more information about the fuzzySearch method and indexes values at: Fuzzy Search.
var SEARCH_QUERY = 'Amsterdam';
function findGeometry() {
	tomtom.fuzzySearch({idxSet:"Geo"})
	  .query(SEARCH_QUERY)
	  .go()
	  .then(getAdditionalData);
}

Here is the code which executes findGeometry function:

findGeometry();
  1. Create a function called findGeometry and declare a SEARCH_QUERY variable.
  2. Use the tomtom.fuzzySearch method to get the geometry.id.

    To limit indexes utilized for the search to Geographies, set the idxSet parameter to Geo.

  3. Create the getAdditionalData function. Inside call the additionalData method and obtain requested geometries. Pass them for further processing to another function called processAditionalDataResponse.
    function getAdditionalData(fuzzySearchResults) { 
    	var geometryId = fuzzySearchResults[0].dataSources.geometry.id;
    	tomtom.additionalData({
    		geometries: [geometryId],
    		geometriesZoom: 12
    	    })
    	    .go()
    	    .then(processAdditionalDataResponse);
    }
    
  4. To display a polygon on the map, create a new GeoJSON layer using previously obtained geometryData and add it to the map. Use Leaflet’s fitBounds and getBounds methods to zoom the map on the polygon. See the following code:
    function displayPolygonOnTheMap(additionalDataResult) {
    	var geometryData = additionalDataResult.geometryData.features[0].geometry;
    	var geoJsonLayer = tomtom.L.geoJson(geometryData,{
    		style: {
    			color: '#2FAAFF',
    			opacity: 0.8
    		}
    	}).addTo(map);
    	map.fitBounds(geoJsonLayer.getBounds());
    	return geometryData;
    }
    
  5. Create the processAditionalDataResponse function and execute displayPolygonOnTheMap function inside.
    function processAdditionalDataResponse(additionalDataResponse) {
    	if (additionalDataResponse.additionalData && additionalDataResponse.additionalData.length) {
    		var geometryData = displayPolygonOnTheMap(additionalDataResponse.additionalData[0]);
    	}
    }
    

4. Calculate and display the polygon area with Turf.js

To calculate the area of your polygon, use the Turf.js area method.

  1. Create the function called calculateTurfArea.
    • Pass geometryData as an argument, as previously defined in the getGeometry function.
    • According to Turf.js, this method returns the area of the polygon in square meters.
    • Convert it to square kilometers to make it more readable. See the following code:
      function calculateTurfArea(geometryData) {
       var areaInMeters = turf.area(geometryData);
       var areaInKilometers = turf.round(turf.convertArea(areaInMeters, 'meters', 'kilometers'),2);
      }
      
  2. To display the polygon area information, create a polygon-info-box HTML element inside the  div with 'id' map.
    <div id='polygon-info-box'>
    	<label>Area of the polygon:</label>
    	<div>
    	  <span id='area-info'> - </span><span>km2</span> 
    	</div>
    </div>
    
  3. In the calculateTurfArea function created before, set the content of areaInfo element to areaInKilometers value by using an innerText property.
    function calculateTurfArea(geometryData) {
     var areaInMeters = turf.area(geometryData);
     var areaInKilometers = turf.round(turf.convertArea(areaInMeters, 'meters', 'kilometers'),2);
     var areaInfo = document.getElementById('area-info');
     areaInfo.innerText = areaInKilometers;
     var areaInfoWrapper = document.getElementsByClassName('tomtom-control-panel')[0];
     areaInfoWrapper.style.visibility = "visible";
    }
    
  4. Create a map control panel and add a polygon-info-box to it:
    tomtom.controlPanel({
    	position: 'topright',
    	collapsed: false,
    	close: null,
    	closeOnMapClick: false
    }).addTo(map).addContent(document.getElementById('polygon-info-box'));
    
  5. Add styling to your controlPanel in style.css file:
    .tomtom-control-panel {
    	border-radius: 0;
    	box-shadow: rgba(0, 0, 0, 0.45) 2px 2px 2px 0px;
    	visibility: hidden;
    }
    .tomtom-control-panel label {
    	font-size: 1.3em;
    	font-weight: bold;
    	line-height: 2;
    }
    .tomtom-control-panel span {
    	font-size: 1.2em;
    }
    .tomtom-control-panel{
    	text-align: right;
    }
    
  6. Add the calculateTurfArea function execution inside of the processAdditionalDataResponse function:
    function processAdditionalDataResponse(additionalDataResponse) {
    	if (additionalDataResponse.additionalData && additionalDataResponse.additionalData.length) {
    		var geometryData = displayPolygonOnTheMap(additionalDataResponse.additionalData[0]);
    		calculateTurfArea(geometryData);
    	}
    }
    

5. Finding points located within a polygon using Turf.js

  1. Define the markerCoordinates array with points, some of them from the inside and some from the outside of the polygon:
    var markerCoordinates = [
    	[4.899431, 52.379189],
    	[4.8255823, 52.3734312],
    	[4.7483138, 52.4022803],
    	[4.797049, 52.435065],
    	[4.885911, 52.320235]
    ];
    
  2. Now, create a drawPointsInsideAndOutsideOfPolygon function and use a pointsWithinPolygon method from the turf library:
    function drawPointsInsideAndOutsideOfPolygon(geometryData) {
    	var turfPolygon = turf.polygon(geometryData.coordinates);
    	var points = turf.points(markerCoordinates);
    	var pointsWithinPolygon = turf.pointsWithinPolygon(points, turfPolygon);
    }
    
  3. Create an img directory and in it place the images you want to use as the outside and inside of the polygon markers.
  4. Define customInsidePolygonMarkerIcon and customOutsideMarkerIcon variables and provide in them paths to the marker images which you have just added to the img folder. See the following code:
    var customInsidePolygonMarkerIcon = tomtom.L.icon({
    	iconUrl: 'img/inside_marker.png',
    	iconSize: [40, 46],
    	iconAnchor: [20, 46]
    });
    var customOutsideMarkerIcon = tomtom.L.icon({
    	iconUrl: 'img/outside_marker.png',
    	iconSize: [40, 46],
    	iconAnchor: [20, 46]
    });
    
  5. Create a marker for each point contained in the markerCoordinates variable.
    1. You need to switch the coordinates order for the marker to [lat, lon] as Turf.js uses the [lon, lat] order.
    2. Then set the proper icons for your markers. Set icon marker to customInsidePolygonMarkerIcon for the points which are within the polygon and customOutsideMarkerIcon for the other.
    3. Add markers to the map. See the following code:
      function drawPointsInsideAndOutsideOfPolygon(geometryData) {
      	[...]
      	markerCoordinates.forEach(function (markerCoordinate) {
      	  var marker = tomtom.L.marker(L.GeoJSON.coordsToLatLng(markerCoordinate));
      	  marker.setIcon(customOutsideMarkerIcon);
      	  pointsWithinPolygon.features.forEach(function (pointWithinPolygon) {
      		if (markerCoordinate[0] === pointWithinPolygon.geometry.coordinates[0] && 
      		    markerCoordinate[1] === pointWithinPolygon.geometry.coordinates[1]) {
      		    marker.setIcon(customInsidePolygonMarkerIcon);
      		}
      	  });
      	  marker.addTo(map);
      	})
      }
      
  6. Execute the drawPointsInsideAndOutsideOfPolygon function inside of the processAdditionalDataResponse function:
    function processAdditionalDataResponse(additionalDataResponse) {
    	if (additionalDataResponse.additionalData && additionalDataResponse.additionalData.length) {
    		var geometryData = displayPolygonOnTheMap(additionalDataResponse.additionalData[0]);
    		calculateTurfArea(geometryData);
    		drawPointsInsideAndOutsideOfPolygon(geometryData);
    	}
    }
    

See the result!

Summary

From this tutorial you learned:

  • How to show a polygon on a map.
  • How to calculate and show its area using Turf.js.
  • How to show points located within and outside of a polygon using Turf.js.

You can find source code here: GitHub.

You are here