Our team of SEO Web Design gurus are standing by to assist you achieve your online marketing goals.

(541) 799-0040‬

SEO Web Design, LLC aims to improve business by delivering effective solutions based on innovative technologies and professional designs. Discover the variety of services we offer and convince yourself on the basis of the latest works that we've done. We love building fresh, unique and usable websites optimized specifically for your niche.

Responsive Web Design

SEO / SEM / Social Media

Conversion Rate Optimization

Email Marketing

Online Presence Analysis

Web Hosting
SEO Web Design / Web Design  / How To Build A Geocoding App In Vue.js Using Mapbox

How To Build A Geocoding App In Vue.js Using Mapbox

About The Author

Prince Chukwudire is a Frontend Engineer who is keen on the pixel-perfect implementation of user-centric UI designs and writing unit tests to improve code … More about Prince ↬[1]

In this guide, we’ll take a general look at the concepts of forward geocoding and reverse geocoding. We will build a mini-app that applies these concepts to display specific locations, using Mapbox[2] and Vue.js 2.6.11 to achieve this.

Pinpoint accuracy and modularity are among the perks that make geocodes the perfect means of finding a particular location.

In this guide, we’ll build a simple geocoding app[3] from scratch, using Vue.js and Mapbox. We’ll cover the process from building the front-end scaffolding up to building a geocoder to handle forward geocoding and reverse geocoding. To get the most out of this guide, you’ll need a basic understanding of JavaScript and Vue.js and how to make API calls.

What Is Geocoding?

Geocoding is the transformation of text-based locations to geographic coordinates (typically, longitude and latitude) that indicate a location in the world.

Geocoding is of two types: forward and reverse. Forward geocoding converts location texts to geographic coordinates, whereas reverse geocoding converts coordinates to location texts.

In other words, reverse geocoding turns 40.714224, -73.961452 into “277 Bedford Ave, Brooklyn”, and forward geocoding does the opposite, turning “277 Bedford Ave, Brooklyn” into 40.714224, -73.961452.

To give more insight, we will build a mini web app that uses an interactive web map with custom markers to display location coordinates, which we will subsequently decode to location texts.

Our app will have the following basic functions:

  • give the user access to an interactive map display with a marker;
  • allow the user to move the marker at will, while displaying coordinates;
  • return a text-based location or location coordinates upon request by the user.

Set Up Project Using Vue CLI

We’ll make use of the boilerplate found in this repository[6]. It contains a new project with the Vue CLI and yarn as a package manager. You’ll need to clone the repository. Ensure that you’re working from the geocoder/boilerplate branch.

Set Up File Structure of Application

Next, we will need to set up our project’s file structure. Rename the Helloworld.vue file in the component’s folder to Index.vue, and leave it blank for now. Go ahead and copy the following into the App.vue file:

  <div id="app">
    <!--Navbar Here -->
        <div class="header">
    <!--Index Page Here -->
    <index />
import index from "./components/index.vue";
export default {
  name: "App",
  components: {

Here, we’ve imported and then registered the recently renamed component locally. We’ve also added a navigation bar to lift our app’s aesthetics.

We need an .env file to load the environment variables. Go ahead and add one in the root of your project folder.

Install Required Packages and Libraries

To kickstart the development process, we will need to install the required libraries. Here’s a list of the ones we’ll be using for this project:

  1. Mapbox GL JS
    This JavaScript library uses WebGL to render interactive maps from vector tiles[7] and Mapbox[8].
  2. Mapbox-gl-geocoder
    This geocoder control for Mapbox GL will help with our forward geocoding.
  3. Dotenv
    We won’t have to install this because it comes preinstalled with the Vue CLI. It helps us to load environment variables from an .env file into process.env[9]. This way, we can keep our configurations separate from our code.
  4. Axios
    This library will help us make HTTP requests.

Install the packages in your CLI according to your preferred package manager. If you’re using Yarn, run the command below:

cd geocoder && yarn add mapbox-gl @mapbox/mapbox-gl-geocoder axios

If you’re using npm, run this:

cd geocoder && npm i mapbox-gl @mapbox/mapbox-gl-geocoder axios --save

We first had to enter the geocoder folder before running the installation command.

Scaffolding the Front End With Vue.js

Let’s go ahead and create a layout for our app. We will need an element to house our map, a region to display the coordinates while listening to the marker’s movement on the map, and something to display the location when we call the reverse geocoding API. We can house all of this within a card component.

Copy the following into your Index.vue file:

  <div class="main">
    <div class="flex">
      <!-- Map Display here -->
      <div class="map-holder">
        <div id="map"></div>
      <!-- Coordinates Display here -->
      <div class="dislpay-arena">
        <div class="coordinates-header">
          <h3>Current Coordinates</h3>
        <div class="coordinates-header">
          <h3>Current Location</h3>
          <div class="form-group">
            <button type="button" class="copy-btn">Copy</button>
          <button type="button" class="location-btn">Get Location</button>

To see what we currently have, start your development server. For Yarn:

yarn serve

Or for npm:

npm run serve

Our app should look like this now:

Scaffold preview
Geocoding app scaffold preview. (Large preview[10])

The blank spot to the left looks off. It should house our map display. Let’s add that.

Interactive Map Display With Mapbox

The first thing we need to do is gain access to the Mapbox GL and Geocoder libraries. We’ll start by importing the Mapbox GL and Geocoder libraries in the Index.vue file.

import axios from "axios";
import mapboxgl from "mapbox-gl";
import MapboxGeocoder from "@mapbox/mapbox-gl-geocoder";
import "@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css";

Mapbox requires a unique access token[11] to compute map vector tiles. Get yours[12], and add it as an environmental variable in your .env file.


We also need to define properties that will help with putting our map tiles together in our data instance. Add the following below the spot where we imported the libraries:

export default {
  data() {
    return {
      loading: false,
      location: "",
      access_token: process.env.VUE_APP_MAP_ACCESS_TOKEN,
      center: [0, 0],
      map: {},
  • The location property will be modeled to the input that we have in our scaffolding. We will use this to handle reverse geocoding (i.e. display a location from the coordinates).
  • The center property houses our coordinates (longitude and latitude). This is critical to putting our map tiles together, as we will see shortly.
  • The access_token property refers to our environmental variable, which we added earlier.
  • The map property serves as a constructor for our map component.

Let’s proceed to create a method that plots our interactive map with our forward geocoder embedded in it. This method is our base function, serving as an intermediary between our component and Mapbox GL; we will call this method createMap. Add this below the data object:

mounted() {

methods: {
  async createMap() {
    try {
      mapboxgl.accessToken = this.access_token; = new mapboxgl.Map({
        container: "map",
        style: "mapbox://styles/mapbox/streets-v11",
        zoom: 11,

    } catch (err) {
      console.log("map error", err);

To create our map, we’ve specified a container that houses the map, a style property for our map’s display format, and a center property to house our coordinates. The center property is an array type and holds the longitude and latitude.

Mapbox GL JS initializes our map based on these parameters on the page and returns a Map object to us. The Map object refers to the map on our page, while exposing methods and properties that enable us to interact with the map. We’ve stored this returned object in our data instance,

Forward Geocoding With Mapbox Geocoder

Now, we will add the geocoder and custom marker. The geocoder handles forward geocoding by transforming text-based locations to coordinates. This will appear in the form of a search input box appended to our map.

Add the following below the initialization that we have above:

let geocoder =  new MapboxGeocoder({
    accessToken: this.access_token,
    mapboxgl: mapboxgl,
    marker: false,

geocoder.on("result", (e) => {
  const marker = new mapboxgl.Marker({
    draggable: true,
    color: "#D80739",
    .addTo(; =;
  marker.on("dragend", (e) => { = Object.values(;

Here, we’ve first created a new instance of a geocoder using the `MapboxGeocoder` constructor. This initializes a geocoder based on the parameters provided and returns an object, exposed to methods and events. The `accessToken` property refers to our Mapbox access token, and `mapboxgl` refers to the [map library]( currently used. Core to our app is the custom marker; the geocoder comes with one by default. This, however, wouldn’t give us all of the customization we need; hence, we’ve disabled it. Moving along, we’ve passed our newly created geocoder as a parameter to the `addControl` method, exposed to us by our map object. `addControl` accepts a `control` as a parameter. To create our custom marker, we’ve made use of an event exposed to us by our geocoder object. The `on` event listener enables us to subscribe to events that happen within the geocoder. It accepts various [events]( as parameters. We’re listening to the `result` event, which is fired when an input is set. In a nutshell, on `result`, our marker constructor creates a marker, based on the parameters we have provided (a draggable attribute and color, in this case). It returns an object, with which we use the `setLngLat` method to get our coordinates. We append the custom marker to our existing map using the `addTo` method. Finally, we update the `center` property in our instance with the new coordinates. We also have to track the movement of our custom marker. We’ve achieved this by using the `dragend` event listener, and we updated our `center` property with the current coordinates. Let’s update the template to display our interactive map and forward geocoder. Update the coordinates display section in our template with the following:

<div class="coordinates-header">
  <h3>Current Coordinates</h3>
  <p>Latitude: {{ center[0] }}</p>
  <p>Longitude: {{ center[1] }}</p>

Remember how we always updated our center property following an event? We are displaying the coordinates here based on the current value.

To lift our app’s aesthetics, add the following CSS file in the head section of the index.html file. Put this file in the public folder.

<link href="" rel="stylesheet" />

Our app should look like this now:

Forward geocoding preview
Forward geocoding preview. (Large preview[13])

Reverse Geocode Location With Mapbox API

Now, we will handle reverse geocoding our coordinates to text-based locations. Let’s write a method that handles that and trigger it with the Get Location button in our template.

Reverse geocoding in Mapbox is handled by the reverse geocoding API. This accepts longitude, latitude, and access token as request parameters. This call returns a response payload — typically, with various details. Our concern is the first object in the features array, where the reverse geocoded location is.

We’ll need to create a function that sends the longitude, latitude and access_token of the location we want to get to the Mapbox API. We need to send them in order to get the details of that location.

Finally, we need to update the location property in our instance with the value of the place_name key in the object.

Below the createMap() function, let’s add a new function that handles what we want. This is how it should look:

async getLocation() {
  try {
    this.loading = true;
    const response = await axios.get(
    this.loading = false;
    this.location =[0].place_name;
  } catch (err) {
    this.loading = false;

This function makes a GET request to the Mapbox API. The response contains place_name — the name of the selected location. We get this from the response and then set it as the value of this.location.

With that done, we need to edit and set up the button that will call this function we have created. We’ll make use of a click event listener — which will call the getLocation method when a user clicks on it. Go ahead and edit the button component to this.

  :class="{ disabled: loading }"
  Get Location

As icing on the cake, let’s attach a function to copy the displayed location to the clipboard. Add this just below the getLocation function:

copyLocation() {
  if (this.location) {
    alert("Location Copied")

Update the Copy button component to trigger this:

<button type="button" class="copy-btn" @click="copyLocation">


In this guide, we’ve looked at geocoding using Mapbox. We built a geocoding app that transforms text-based locations to coordinates, displaying the location on an interactive map, and that converts coordinates to text-based locations, according to the user’s request. This guide is just the beginning. A lot more could be achieved with the geocoding APIs, such as changing the presentation of the map using the various map styles[14] provided by Mapbox.


Smashing Editorial(ks, vf, yk, il, al)


  1. ^ More about Prince ↬ (
  2. ^ Mapbox (
  3. ^ simple geocoding app (
  4. ^ Image Optimization (
  5. ^ Jump to table of contents ↬ (
  6. ^ boilerplate found in this repository (
  7. ^ vector tiles (
  8. ^ Mapbox (
  9. ^ process.env (
  10. ^ Large preview (
  11. ^ access token (
  12. ^ Get yours (
  13. ^ Large preview (
  14. ^ map styles (

Powered by WPeMatico

Smashing Magazine is a website and eBook publisher that offers editorial content and professional resources for web developers and web designers.