How did we create a thematic map of ski resorts

As everybody of the Geoapify team loves skiing as well as snowboarding, we decided to create a demo map for Mapifator with ski resorts in the Alps. We intended to create a map that can help to choose a perfect place for the next ski vacation. Another goal was to find out how difficult is it to utilize OpenStreetMap data to create a thematic map with the Mapifator map builder.

In this article, we would like to share with you our experience, our conclusions, and recommendations, that can support you for making a custom map or extracting data from OSM.

Geodata and other data we decided to add to the map

After some discussions, we decided that a ski resorts map should have the following data to useful:

Ski lifts and ski slopesThe interactive map should contain not only geometries and locations of lifts and slopes but also information about a ski resort size and infrastructure: length of slopes and amount of lifts.
ElevationIn the situation of Global Warming, a lot of ski resorts can’t guarantee snow. And it’s really sad! However, it becomes more and more important to have information about the altitude of ski resorts.
AmenitiesAmenities are always nice to have! They may be not so important when you choose a ski resort. But become very helpful when you choose accommodation near the ski resort. Moreover, amenities can be used to make some suggestions about the ski resort. For example, the density of bars can tell you that the ski resort can be characterized as a party spot.
We decided to visualize on the map markings, restaurants, cafes, bars and toilets. We also added international airports near Alpin region.
MediaTo make the map more alive and attractive we decided to add pictures and videos to ski resorts information. After some research, we made a choice in the direction of the Youtube Data API.

Mapifator map builder API to create custom thematic maps

We used a Mapifator map builder as a visualization tool. As we attended to add a big amount of places and complex geometries (lifts and slopes) we used Mapifator API to add data to the map.

As the goal was to create a thematic map that helps to make a decision toward the next ski vacation, we decided not to show each and every small resort but give an overview of the biggest ones. This is the result:

Top 100 Ski Resorts in the Alpin region

Getting geodata from OSM

In our previous article, we already described ways to extract data from OpenStreetMap. So the geodata we obtained from OSM with the help of Overpass API and Overpass Turbo.

It is worthwhile to mention that we reached a free version limits there very quickly and this inspired us to create our own instance. On another hand, we’ve found that Overpass API has performance problems on big values and complex queries. So we decided to run simple queries and process results with JavaScript after.

The first task was to identify ski resorts. After some analyses, we found that some of the ski resort areas have “landuse”=”winter_sports” tag, but a lot don’t. According to that we’ve chosen the following algorithm:

Step 1. Collect all ski lifts in the Alpin area
// getting ski lifts in the Alps
overpass.queryData(`[out:json];
    area(3602698607)->.alps;
    way
      ["aerialway"]
      ["aerialway"!="goods"]
      ["aerialway"!="zip_line"]
    (area.alps);
out geom;`));
Step 2. Create ski lift clusters with ski lifts connected to each other

This was done with JS only. First, all lifts were represented as a separate cluster, then we combined clusters connected to each other.

Step 3. For each cluster (list of lifts) find slopes

Slopes we had to add recursively. First slopes connected to lifts, then other slopes connected to found slopes.

Here is an example of the Overpass API query (called from JS):

// getting slopes near ski lifts
overpass.queryData(`[out:json];
    way(id:${ids})->.lifts;
     way
       ["piste:type"="downhill"](around.lifts:100)->.pistes;
.pistes out geom;`));

// getting slopes connected to existing slopes
overpass.queryData(`[out:json];
    way(id:${ids.join(',')})->.piste;
    way
      ["piste:type"="downhill"]
      ["area"!~".*"]
      ["landuse"!~".*"]
    (around.piste:10);
out geom;`));
Step 4. Identify and combine clusters, that connected to each other with ski-slopes

Here we acted similarly to step 2.

Step 5. Add amenities to each separate ski resort

Amenities to searched nearby ski slopes. We queried all amenities to find out what options we have and filtered them by types later on:

// getting amenities
overpass.queryData(`[out:json];
    way(id:${ids.join(',')})->.piste;
    nwr["amenity"](around.pistes:100)->.amenities;
.amenities out geom;`));

Getting elevation

To get maximum and minimum elevation values we queried top and bottom location for each lift. We used the Google Elevation API for that purpose. To all ski resorts that ascend 2000, 2500 and 3000 we added appropriate tags, so it possible to filter ski resorts on the resulting map.

Getting Youtube data

Youtube videos are great to embed. You do not need to take care of a license & copyrights. The Youtube player has all the required information. The Youtube Data API allows searching videos from a code.

However, the API has a quota which is calculated in some strange way. It happened to us that we could make only 70-80 requests per day per key.

Conclusions

How difficult is it to create a custom thematic map? It’s not! But takes time and requires some experience.

Data

Data is available! OpenStreetMap is only one option, but there are other ones. Of course, some analysis and post-processing are needed to unify data formats and extract only the data you need.

APIs

Almost all APIs have a free tier and usually, it’s enough to make requests required for the map creation.

Mapifator Map Builder

Even if we create it, we really enjoy using it! We believe that Mapifator has great perspectives! It allows creating custom maps at small costs. With a new Mapifator pricing policy 1 fully functional map is included in the Free plan.

Moreover, Mapifator API empowers users to add complex geometries and structured data.

Geoapify provides a platform, products, and services to help you benefit location intelligence

  • Check our Maps API that allows developing a map from scratch.
  • Try our Mapifator map builder that can be used to create a custom map with a graphical interface.
  • Or contact us and we will advise you the best fitting to your use case technologies and provide a turn-key solution for you!

Visualizing time series data on the map

In this article, I’ll show how to create a map-based visualization of multi-dimensional data – time, location and value. As an example, I’m going to use the public daily statistics for nCoV-2019 “coronavirus” outbreak.

By the end of January 2020, the “coronavirus” outbreak started to become one of the top world concerns. Despite the high amount of information that authorities and news agencies provide every day, it is surprisingly hard to see the big picture behind all those numbers.

As most situational data, virus outbreak numbers have a clear location component. Therefore map-based visualization can be extremely helpful.

We’re going to take the raw data and create a simple web-based dashboard that looks like this:

Coronavirus outbreak visualization
Coronavirus outbreak visualization

Preparing data

As the first step, I took the daily statistics data kindly made available here by the Center for Systems Science and Engineering at John Hopkins University.

Raw data were normalized, aggregated by date and geocoded with Geoapify Geocoding API. For convenience, the resulting data for each day were represented in the GeoJSON format, that looks like this:

{
        "type": "FeatureCollection",
        "features": [{
          "type": "Feature",
          "geometry": {
            "type": "Point",
            "coordinates": [121.4554, 31.20327]
          },
          "properties": {
            "Place": "Shanghai",
            "Confirmed": 9
          }
        },
        ...
}

Configuring map

As the next step, I created a simple webpage with Mapbox GL data visualization library, “dark” basemap and two layers – “case-circles” and “case-labels”. Both layers configured to use the GeoJSON data source and dynamically take the number of confirmed cases from each GeoJSON Feature “properties.Confirmed” field.

// please get your own free ApiKey at https://myprojects.geoapify.com
var geoapifyApiKey = '7e99a2fb2e9b41ae9e40742f24c33d75';

var map = new mapboxgl.Map({
  container: 'map',
  style: `https://maps.geoapify.com/v1/styles/dark-matter/style.json?apiKey=${geoapifyApiKey}`,
  center: [15, 21],
  refreshExpiredTiles: false,
  zoom: 1.1
});

map.on('load', function() {
  map.addSource('cases', {
    'type': 'geojson',
    data: null
  });

  map.addLayer({
    'id': 'case-circles',
    'type': 'circle',
    'source': 'cases',
    'paint': {
      'circle-color': '#FF0000',
      'circle-opacity': 0.5,
      'circle-radius': [
        'interpolate',
        ["exponential", 0.9],
        ['get', 'Confirmed'],
        1,
        5,
        5000,
        15
      ]
    }
  });

  map.addLayer({
    'id': 'case-labels',
    'type': 'symbol',
    'source': 'cases',
    'layout': {
      'text-field': [
        'to-string', ['get', 'Confirmed']
      ],
      'text-font': [
        'Open Sans Bold',
        'Arial Unicode MS Bold'
      ],
      'text-size': 12
    },
    'paint': {
      'text-color': 'rgba(0,0,0,0.5)'
    }
  });
});

Due to the significant difference in the number of confirmed cases per location, the “case-circles” layer was configured to use an exponential scale, to emphasize new locations as they appear on the map.

Adding interactivity

Additionally, I’ve added the date slide that triggers map update accordingly to the selected date and allows to see outbreak dynamics.

<div class="map-overlay top">
    <div class="map-overlay-inner">
        <h2 id="date"></h2>
        <input id="slider" type="range" min="0" max="1" step="1" value="0" />
        <h2 id="count">Confirmed cases</h2>
    </div>
</div>

<script>
var casesHistory = getCasesHistory()
var dates = Object.keys(casesHistory)

document.getElementById('slider').max = dates.length - 1

function updateMap(dateId) {
  var date = dates[dateId]
  var casesForDate = casesHistory[date]
  document.getElementById('date').textContent = `Date: ${date}`;
  document.getElementById('count').textContent = `Confirmed cases: ${casesForDate.total}`;
  map.getSource('cases').setData(casesForDate.geojson);
}

document
  .getElementById('slider')
  .addEventListener('input', function(e) {
    var dateId = parseInt(e.target.value, 10);
    updateMap(dateId);
});

updateMap(0);
</script>

Going further

I hope that you now have the general idea of how to create similar visualizations. To make it easier, I’ve prepared a free JSFiddle example to help you get started.

Still too complicated? Don’t worry, and get in touch with us. We’ll be happy to help you with your project.

5 Steps to create a map with pins

Visualize multiple locations on a map with beautiful and interactive pins. It’s very simple with Mapifator Map Story! In this article, we tell you how to create maps with attractive markers and multiple locations with ease and no coding only in 5 Steps.

Preconditions

You need to register in Mapifator and create a new map. You may have a question if it’s free or not. So the answer is “Yes! It’s free for small map stories! Even for commercial use!” We have a freemium model, so start creating a map for free and extend when you need it.

Step 1. Prepare places data

Mapifator Map Story allows creating maps and visualizing places on it. Place in Mapifator is not only a location but also interesting and useful information, attached media and even actions. To make a map quick and easy we recommend to prepare some data before you start.

Here is an example of data we prepared for the “Top 10 most popular National Parks in the USA” map story:

NameLocationDescriptionYoutube videosExternal links
Great Smoky MountainsGreat Smoky Mountains National Park, United States of AmericaRecreation Visits in 2018: 11,421,200
As a part of the Appalachian Mountains, Great Smoky Mountains contain more than 850 miles (1,370 km) of hiking trails…
https://youtu.be/
poyWuEA6HT0
https://www.nps.gov/
grsm/index.htm
Grand CanyonGrand Canyon, United States of AmericaRecreation Visits in 2018: 6,380,495
Grand Canyon is a steep-sided canyon carved by the Colorado River…
https://youtu.be/
dGGWu_noS3w
https://www.nps.gov/
grca/index.htm
Images for the map with pins

If you place to add some pictures to the map, it’s better to prepare them as well. A place in the Mapifator can have a few images attached. We recommend adapting picture sizes to the web and having pictures with the same aspect ratio. We use 450px width pictures for our map stories.

Moreover, Mapifator allows adding some general information and pictures (logos) about the map, prepare it as well. You can prepare this data as well. For example like that:

NameDescriptionLinks
Top 10 most popular National Parks in the USAThere are 61 protected areas in the United States knows as National Parks. More than 85 Million people visited Parks in 2018. You can find 10 the most popular ones in this Map Storyhttps://en.wikipedia.org/wiki/
List_of_national_parks_of_the_United_States

Step 2. Create markers and tags

With Mapifator you can create very beautiful markers for your places. You can use default one or create a set of markers for the places you want to visualize.

Markers and tags for the map
Map Story markers

To add new Markers and Tags go to the “Settings” menu. You can always change the design of your markers and tags later, so all pins on a map will be automatically redrawn.

Mapifator tags help you to provide information about a place in a compact and informative form. For example, you can add tags like “Fishing”, “Walking”, “Swimming” and show their icons when providing the place description. In addition, tags are used as filters on a map. So your customers could have quick access to places with the tag feature.

Tags and tag filters

With Mapifator you can add text and icons to tags and specify a color.

Furthermore, some tags could be added to the map description and appear as the main place filters for your map.

Step 3. Add places and map information to the map

When the main job is done, it takes only a few moments to get a map with pins and integrate it into your website or application.

Add places data in the “Places” menu. You can specify also an order of the places there.

In the Place Editor, you can add prepared data and media, specify tags for each place.

Similarly, add map information and define tag filters.

In addition, you can add information about the map owner and an external link as the main action for the map. This could be, for example, a link to your website or another resource.

If you use some media that requires attribution, in Mapifator you can add all required labels and links to make your map compatible with the license conditions.

Step 4. Define a design for your map

Mapifator allows you to choose between several layouts for your map story.

Define a design for the Map Story by selecting one for the Map Information, List Item and Place view.

Map layouts

In addition, you can choose colors for your map story, that fill the best to your website or application design.

Note! Mapifator maps are already prepared for the mobile view, so the chosen layouts could look different on small devices. With the help of preview buttons, you can check how the map adjusts to different screen sizes.

Step 5. Share or embed your Map Story

Congratulations! Your map is ready for your customers!

Just click the “Share / Embed” button to get the share link or embed code.

Mapifator provides Map Stories as maps and articles. Choose the view you like the most!

Quickstart quide

What is OpenStreetMap and how it is better than Google Maps

About OpenStreetMap

OpenStreetMap, or “OSM”, is a Wikipedia for the maps. It is a free, open, and global community project. OpenStreetMap mission is to map everything that worth to be mapped. And, similar to Wikipedia, OSM data can be added, edited and used by everyone.

I say “data” and not “maps” because that’s what OSM essentially is. Open Street Map is a big open database full of free geospatial data, available for everyone!

Indeed, OSM is widely used to create digital maps. But it can do way more than that. OSM applications include routing and navigation, converting GPS coordinates to addresses, searching places by name, analyzing map data and many many more.

Driving route from Berlin to Potsdam, Germany, calculated on OSM data
Driving route from Berlin to Potsdam, Germany, calculated on OSM data

In 2019, OpenStreetMap with its more than 5 000 000 members and more than than 1 200 000 contributors is clearly the biggest and most successful crowd-sourced mapping project in human history. And as Facebook, Uber, Microsoft and thousands of others are utilizing OSM data in their products, almost anyone can be counted as OSM user, direct or indirect.

Power of crowdsourcing

OpenStreetMap project was started in 2004. Back then map data were controlled by commercial organizations and governments, hard to use and expensive to buy. Mapping itself was done primarily by the teams of GIS specialists. Most of the time, they were not in a position to know how well data they map reflecting the reality, to validate and timely update them.

OpenStreetMap managed to disrupt the industry and change all of that in just a few years. It helped to demystify cartography and geography as a science and has given everyone the possibility and tools needed to contribute. No long formalities, no expensive licenses or equipment – anyone with a computer and Internet access could join and start making the world better.

And that approach worked amazingly well!

First 10 years of OpenStreetMap mapping progress

In fact, OpenStreetMap became so successful that Google had to play a “catch-up” game. The company introduced Google Map Maker, with familiar OSM-like interface, to allow people around the world to contribute.

Of course, it was not the same. The main difference is – if you contribute to OSM, data belong to you and OSM community, and stay free and open for everybody, under creative commons license. And when you contribute to Google Maps – well, all changes you make belong to Google, and it is up to Google to decide who and how can use that data.

Number of monthly edits for OpenStreetMap exceeds 8 000 000
Number of monthly edits for OpenStreetMap exceeds 8 000 000

In addition, every change made to OpenStreetMap is immediately visible to others, when in the case of Google it is delayed by long moderation and review process.

Crowdsourced mapping with immediate access to the changes appeared to be especially important for mapping crisis and natural disaster areas. In 2010, when Haiti suffered from a disastrous earthquake, OSM volunteers managed to map the whole island in just a couple of days from satellite imagery.

OpenStreetMap volunteers mapping Haiti after 2010 earthquake

This would not be possible with any existing commercial provider. Businesses are bound to mapping data that are profitable to sell. Also, most of the time they only capable of publishing results on a particular schedule and cannot do it every second, as OSM does. And, even Google with huge investments, cannot match the scale and the power local knowledge of the OSM community.

History of OpenStreetMap

Like most many things, OpenStreetMap started small. In August 2004, Steve Coast, back than a physics student at UCL, came up with an initiative to create free, editable maps of UK.

Just a few months later, by the end of 2004, web site openstreetmap.org was up and running, based on 100% open source software. It contained community email list, wiki documentation and first versions of map editing software.

By the end of 2005, OpenStreetMap had more than 1000 registered users. And in August 2006 OpenStreetMap Foundation was formally registered as a non-profit, UK based company. At that time OSM community included more than 3000 members.

Following infographic depicts major and noteworthy OpenStreetMap milestones.

Moments of OpenStreetMap history infographic, by Martin Elmer, from Visually
Moments of OpenStreetMap history infographic, from Visually

Part of OSM success related to its explosive community growth and perfect timing. OSM growth matched with the global adoption of smartphones, which at the same time can benefit from the quality offline map data and ideal for the “on-the-go” mapping. Most of the smartphone map and navigation applications are fully or partially based on the OpenStreetMap.

Explosive growth of OSM community year-to-year
Explosive growth of OSM community year-to-year

Another important component of success is related to the active position of the OpenStreetMap Foundation. Successful negotiations with companies like Bing, DigiGlobe, and Ersi allowed using their high-quality satellite and aerial imagery for the OpenStreetMap mapping efforts. Thanks to this, the ever-growing OSM community had enough raw material to work on.

Arcgis satellite imagery as base layer in OSM map editor
Arcgis satellite imagery as base layer in OSM map editor

OpenStreetMap vs Google Maps

OpenStreetMap data widely used to create “digital maps” or “slippy maps“, similar to Google Maps. Both OpenStreetMap and Google Maps support searching places by name and route calculations.

OpenStreetMap vs Google Maps

No surprise that Google Maps, as a state-of-the-art commercial product backed by one of the biggest tech companies in the world, has more polish on it.

It has smarter place search, better user interface, fast 3D accelerated map rendering. Google Maps also gives its users the possibility to submit new and corrected information, which may be added to the map after moderation.

Google Maps also has amazing satellite and aerial imagery, and very cool “street view” mode – something that current OpenStreetMap cannot offer.

How can OpenStreetMap compete or be better than that? By offering features that Google Maps, as a cloud service, cannot offer.

OpenStreetMap is more than just a map of the world, place search and navigation. It gives free and unlimited access to the entire dataset, with a complete history of changes, without limiting who and how can use it. OpenStreetMap is a perfect foundation for emerging innovative and creative solutions and targeted products.

With OSM, map data for the whole planet can be downloaded and used completely offline. Google Maps can only cache small region and generally can not work without an Internet connection.

OSM dataset can be used to large-scale geocoding, routing and analysis, which would be impossible using Google Maps.

OpenStreetMap for business

OpenStreetMap is awesome, yet using it for your business may be quite challenging. As a non-profit organization, OSM does not provide uptime SLAs, support and consulting.

We at Geoapify believe that this limits OSM adoption, and happy to support you by providing stable, affordable, business-friendly OpenStreetMap mapping service. In addition to maps, we also provide a complete set of tools, including places search, geocoding, routing and reachability analysis.

And the best thing – you can register and start to use this all for free, also for commercial purposes. Give our services a try with our interactive Playground – no registration required.

You can reach us at any time at [email protected]. We will be happy to help!

Why do need more interactive maps if we have Google Maps?

Google Maps is one of the best interactive maps. We use it every day to build routes, get more information about places and plan our trips. But does it cover 100% of our needs and requirements? Or even more generic question: can one product cover all users needs and requirements?

Just recently I planned a journey by car with my family. It was 678 km or 7 hours of driving one way. I needed to choose a route and plan intermediate stops. Of course, I used Google Maps to do that, but it took me quite a lot of time and effort to solve my problem. Even if Google Maps gives very good results for general cases, it still needs improvements to cover more specific needs.

As professionally I work with spatial analytics and digital maps, I hear the “Why do need to create more interactive maps if we have Google Maps?” very often. In this article, I provide some ideas, which could give the answer.

Why do we need interactive maps at all?

It’s a silly question, isn’t it? Maps allow exploring locations and places, which we do not know very well or which are new for us. In other words, maps give us answers to location related questions, help to plan trips and optimize them. Ideally, a map should answer all your location questions from a box. So you do not need to use other tools or services.

Of course, it’s difficult or maybe even impossible to make one tool answer all the questions. That’s why it happens that we have a dozen browser tabs opened trying to solve a small trip planning task. For example, split a 6-hour driving route as well as find pleasant and interesting places for stops.

Should we have a separate map website for each and every use case?

Don’t think so. It doesn’t make sense to compete with Google Maps. But a map could be a part of a website. So it’s not a separate web service but a part of your main website. Moreover, if your customers can find all the answers on the website it will make it more informative, attractive and useful.

What should the map contain?

It should answer questions! Where is it located? How can I get there? What interesting can I find nearby? Moreover, the map should help to find a location which fits the chosen criteria and allow filter locations by criteria. A map nowadays is more than a map, but the location intelligence solution.

For example, if your website offers beach holidays planning, the map could show hotels within walking distance from a beach, sights nearby, restaurants & cafes. Further allow to build routes to those amenities, give information about tolls or local public transport tariff.

Beach vacation map
Beach vacation planning map

Geoapify Mapping APIs and components to create interactive maps

Only you know how an ideal map for your website should look like. We at Geoapify can support you by providing the required APIs and tools. You can register and start to use the APIs for free or try them in our Playground right now – no registration required.

Reach us at [email protected] if you need help or missing some features! We are interested in improving and extending our services!

Map animation with Mapbox GL

What can be more eye-catching than smooth, interactive, three-dimensional map animation? Impress your visitors by displaying your map data in stunning 3D!

Previously we have compared OpenLayers and Leaflet map libraries. Both are great choices if you want to add interactive map to your website. They are free, battle-tested, extensible and supported by active communities.

But what if you need a very fast, animated, eye-catching 3D map? Both Leaflet API and OpenMapLayersAPI do not support 3D and free-form map rotation. In this case Mapbox GL map library can be a great option.

Mapbox GL JS is one of the most advanced JavaScript map rendering libraries when it comes to smooth interactive animation. Mapbox GL API is slightly harder to use and not compatible with existing Leaflet plugins and examples. But it is using hardware-accelerated WebGL technology to dynamically draw data with the speed and smoothness of a video game.

In this article I’ll show you how to animate and implement 3D map rotation around a selected point. The end result should look like this:

Map rotation animation in 3D with Mapbox GL

If you short on time and just looking for the complete HTML code, you can find it at the bottom of the page.

Setting up our 3D map

As first step, we need to add imports for Mapbox GL library and its CSS style sheet into the HEAD of our page

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mapbox-gl/0.53.1/mapbox-gl.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/mapbox-gl/0.53.1/mapbox-gl.js"></script>

Once imported, we can define a <div> element which will host map visualization and add Javascript code which will initialize Mapbox GL to render our map in 3D with specified initial location, zoom, pitch and bearing. Please do not forget to put your real API key instead of “YOUR_API_KEY” placeholder in the map tiles URL.

<div id='map'></div>
<script>
var map = new mapboxgl.Map({
    container: 'map',
    style: {
        "version": 8,
        "sources": {
            "basemap": {
                "type": "raster",
                // map tile source 
                "tiles": [
                    "https://maps.geoapify.com/v1/tile/carto/{z}/{x}/{y}.png?api_key=YOUR_API_KEY"
                ],
                "tileSize": 256
            }
        },
        "layers": [{
            "id": "basemap",
            "type": "raster",
            "source": "basemap",
            "minzoom": 0,
            "maxzoom": 22
        }]
    },
    center: [-73.991462, 40.724637], // starting position
    zoom: 12, // starting zoom
    pitch: 60, // starting pitch in degrees
    bearing: 0, // starting bearing in degree
});

This should give us basic interactive 3D map. You should be able to move the map to a different locations, zoom in and out, and change view angle.

Interactive 3D map view of Manhattan, NY
Interactive 3D map view of Manhattan, NY

Adding map rotation animation

As next step, let’s add dynamic map animation, which will change view angle to create effect of flying around the map center. Please add the following code into our <script> block and refresh the page:

function rotateCamera(timestamp) {
    // rotate at approximately ~10 degrees per second
    map.rotateTo((timestamp / 100) % 360, {duration: 0});
    // request the next frame of the animation
    requestAnimationFrame(rotateCamera);
}

map.on('load', function () {
    // start the animation
    rotateCamera(0);
});

Final steps

As the last step, let’s add basic map navigation controls and basemap attribution.

// map navigation controls
map.addControl(new mapboxgl.NavigationControl());

// attribution
map.addControl(new mapboxgl.AttributionControl({
	compact: false,
	customAttribution: 'Powered by <a href="https://geoapify.com/">Geoapify</a> | © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}));
Complete map with controls and attribution
Complete map with controls and attribution

Complete HTML code

Final version of the HTML page could look like this. Please feel free to copy the code, insert API key and open it in your browser to see how it works.

<html>
<head>
    <meta charset='utf-8' />
    <title>Mapbox GL example: rotate map animation in 3D</title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mapbox-gl/0.53.1/mapbox-gl.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mapbox-gl/0.53.1/mapbox-gl.js"></script>
    <style>
        body { margin:0; padding:0; }
        #map { position:absolute; top:0; bottom:0; width:100%; }
    </style>
</head>
<body>

<div id='map'></div>
<script>
var map = new mapboxgl.Map({
    container: 'map',
    style: {
        "version": 8,
        "sources": {
            "basemap": {
                "type": "raster",
                // map tile source 
                "tiles": [
                    "https://maps.geoapify.com/v1/tile/carto/{z}/{x}/{y}.png?api_key=YOUR_API_KEY"
                ],
                "tileSize": 256
            }
        },
        "layers": [{
            "id": "basemap",
            "type": "raster",
            "source": "basemap",
            "minzoom": 0,
            "maxzoom": 22
        }]
    },
    center: [-73.991462, 40.724637], // starting position
    zoom: 12, // starting zoom
    pitch: 60, // starting pitch in degrees
    bearing: 0, // starting bearing in degree
});

function rotateCamera(timestamp) {
    // rotate at approximately ~10 degrees per second
    map.rotateTo((timestamp / 100) % 360, {duration: 0});
    // request the next frame of the animation
    requestAnimationFrame(rotateCamera);
}

map.on('load', function () {
    // start the animation
    rotateCamera(0);
});

// map navigation controls
map.addControl(new mapboxgl.NavigationControl());

// attribution
map.addControl(new mapboxgl.AttributionControl({
	compact: false,
	customAttribution: 'Powered by <a href="https://geoapify.com/">Geoapify</a> | © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}));
	
</script>

</body>
</html>

Summary

Mapbox GL generally requires more JavaScript code to be written than Leaflet and can be more complicated to maintain.

So, you may ask when to use Leaflet and when to use Mapbox GL?

The answer is simple – if you don’t need 3D and extremely fast animation then Leaflet would be the best choice. It has biggest community, best documentation, extensive set of plugins and works well in any situation. And if you really need advanced 3D maps with animations and top rendering speed on modern devices – then Mapbox GL is your friend.