How to click 3D object on map (mapbox) with help from deck.gl (uber library)

Bartłomiej Leja
3 min readJan 24, 2020

Displaying map is one of the basic things you can do with the mapbox. Adding 3d layer seems to be hard, but it's well documented. But what about clicking on a particular 3D object on the displayed map? You can assume that if adding a map and adding 3d layer is easy. Clicking must be the simplest thing in the whole world but …… it's not 😉

In stackblitz example you can see simple angular 8 app which displays map and puts on this map rubber duck in glb format (https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/Duck/glTF-Binary/Duck.glb). After clicking duck you can see window.alert with some information and name of the layer. Additionally, you can click toggle building layer, and 3d buildings will show up. From message in alert and rotation of duck, you will know where I work 💪🏽

I will not cover adding the map and displaying 3D building layer. It’s well documented here . This is javascript example but it’s easy to convert into Angular.

Soo let’s talk about clicking …..

Basically, mapbox have an example in which they are adding 3d model to the map and they are using tree.js. It means that everything you can do in tree.js you can do on the map. So now you probably wonder what's so difficult in clicking on map if you have webGL based lib to work with. Generally, if you aren’t familiar with webGL libs like three.js or babylon.js it isn’t so easy. Additionally, map from mapbox have own 3d camera (that’s why you can pitch) and webGL layer have own camera. Those two cameras need to talk to each other and it’s hard. But thanks uber we can use deck.gl the powerful library that is dealing with 3d graphics (yes uber is doing 3d stuff as well, not only app for people that like to have ride almost for free 🤑 ). Now coding.

First import all libs, luma.gl and deck.gl are from uber. Add map layer array and a mechanism that will add all layers to the map.

Next, create a method that will create 3d models.

And here we are, the place where we can add our beautiful onClick event 👌

You can use hover event too. Unfortunately, I wasn’t able to distinguish left click from right click 😰.

getOrientation, getTranslation, getScale properties will help you to set your object in correct place. When I used my own object from AutoCad I had problems with the visibility of the object that’s why I set _lighting property for ‘pbr’, this is not needed with the duck example but it’s good to know.

Soo that’s it, now you can play with this and give me feedback. At the end of article, I put some links to luma.gl nad deck.gl

--

--

Bartłomiej Leja

I am a programming enthusiast. Mainly focus on C# and Javascripts programming languages. In my free time, I like to ride a bike and listen to music.