Polygons on a Leaflet map

This basic example shows you how to add a marker to the map and display travel time polygons from this location.

First you need to import the necessary javascript and css files into the header of your HTML document:

    <!--  Include jquery - required for XHR requests -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <!--  Include leaflet javascript and css -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet-src.js" crossorigin=""></script>
    <!--  Include r360.js -->
    <script src="https://releases.route360.net/r360-js/latest.js"></script>

Define some css to make the map take up the entire page:

html, body {
    width: 100%;
    height: 100%;

#map {
    width: 100%;
    height: 100%;

Now for the map.

In our main script, we are going to set the map center, initialize the map, and add the basemap.

// define a pair of coordinates, where the map should be centered
// and should serve a the source for polygonization
var latlon = [52.51, 13.37];

// add the map and set the initial center to berlin
var map = L.map('map').setView(latlon, 14);
// add attribution for the transit data used by the r360 polygon service
map.attributionControl.addAttribution("ÖPNV Daten © <a href='https://www.vbb.de/de/index.html' target='_blank'>VBB</a>");

// initialise the base map
r360.basemap({ style: 'basic', apikey: "__your-targomo-api-key__" }).addTo(map);

Using the same latlon pair we used to center the map, we are going to create a marker on the map.

var marker = L.marker((latlon)).addTo(map);

We also need to create an empty layer where we will be adding the polygons

var polygonLayer = r360.leafletPolygonLayer().addTo(map);

The polygon service has options that need to be defined (for more travel options check out the other tutorials)

var travelOptions = r360.travelOptions();
// please contact us and request your own key
// set the service url for your area
// we only have one source which is the marker we just added
// we want to have polygons for 10 to 30 minutes
travelOptions.setTravelTimes([600, 1200, 1800]);
// go by foot

Now that the options are set, we can call the service to request the polygons

r360.PolygonService.getTravelTimePolygons(travelOptions, function(polygons){

    // add the returned polygons to the polygon layer
    // and zoom the map to fit the polygons perfectly
    polygonLayer.clearAndAddLayers(polygons, true);

Easy, right? You should see something like this:

Basic LeafletJS map

Display Targomo polygons on leaflet map

GET YOUR FREE API KEY to use this example
open in new tab
show code