Using Vue.js in Laravel with Mapbox

I spent a lot of time on configuring Mapbox in vuejs and show the map in my laravel application. I hope this tutorial can save you some time.

Prerequisites

I supposed that you already have the things below:

Already set up your laravel application, which means you have your laravel running either on your server or your local host.

A mapbox account. Either a free trial account or a business account can do the job. We only need the token of your account.

 

Step 1: Take a look at your Laravel folder.

I am using the latest Laravel framework 5.4, but I think this tutorial is good for all Laravel 5.X version. The project folder should look like this. I used php artisan make:auth to generate the app layout file. I am going to render my map in welcome.blade.php. So I deleted all default contents there and extends my app layout file.

 

Step 2: Import Mapbox Css and Js file

To render a map with Mapbox, you need to import mapbox’s css and js file. Put

<script src=’https://api.tiles.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.js’></script>

<link href=’https://api.tiles.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.css’ rel=’stylesheet’ />

on the header of your app layout file.

 

Step 3: Create Map.vue file

Create a Map.vue file under your /resources/js/components/ and put the code as I showed here:

 

Step 4: Register your Map.vue in app.js file

Register your Map.vue in your app.js file. I named it <demo-map> and don’t forget to run npm run dev in your terminal to build your Laravel Mix.

 

Step 5: Render your map in the view.

Put tag <demo-map></demo-map> in the view where you want to render your map. I put my map in Welcome.blade.php:

 

Step 6: Enjoy your map.

Now if you go to your view, you should see your map rendering. If not, try to recheck every step in this tutorial or leave me a comment and I’ll reply asap.

 

Leave a Reply

Your email address will not be published. Required fields are marked *