Creating Routes Between Two Point In Google Maps With Vue.js

Today, we will learn about how we can implement for creating Routes between two points in Google maps.

If you have not read the previous blog for google map autocompletes you can find it from here

Prerequisites:

  • Basic Knowledge of Vue.js
  • Node.js tobe installed
  • API Key For Google Maps
  • Vue CLI tobe installed

Lets start.

Goto your desired path, and create a new Vue.js project

Open command prompt and type the following command to create a new project

vue create google-maps-routes

Once your project is created navigate to the project and open it in your favorite code editor.

Now, we need to install the vue js google maps package, so type the following command in the terminal to install the package.

npm i vue2-google-maps

Now open the main.js file src folder and replace the file with the below code.

import Vue from 'vue'
import App from './App.vue'
import * as VueGoogleMaps from "vue2-google-maps";

Vue.config.productionTip = false

Vue.use(VueGoogleMaps, {
  load: {
    key: "api-key",
    libraries: "places",
  },
});

new Vue({
  render: h => h(App),
}).$mount('#app')

replace the “api-key” with your google maps key.

Create a new file as DirectionsRenderer.js and add the following code in it.

import { MapElementFactory } from "vue2-google-maps";

export default MapElementFactory({
  name: "directionsRenderer",

  ctr() {
    return window.google.maps.DirectionsRenderer;
  },

  events: [],

  mappedProps: {},

  props: {
    origin: { type: [Object, Array] },
    destination: { type: [Object, Array] },
    travelMode: { type: String },
  },

  afterCreate(directionsRenderer) {
    let directionsService = new window.google.maps.DirectionsService();

    this.$watch(
      () => [this.origin, this.destination, this.travelMode],
      () => {
        let { origin, destination, travelMode } = this;
        if (!origin || !destination || !travelMode) return;
        directionsService.route(
          {
            origin,
            destination,
            travelMode,
          },
          (response, status) => {
            if (status !== "OK") return;
            // eslint-disable-next-line no-debugger
            debugger
            directionsRenderer.setDirections(response);
          }
        );
      }
    );
  },
});

Now open the App.vue component file add the following code in it.

<template>
  <div id="app">
    <h2>Routes Google Maps</h2>
    <div>
      <table>
        <tr>
          <th>Start Location</th>
          <th><GmapAutocomplete @place_changed="setPlace" /></th>
          <th style="width: 50%;"><button class="btn" @click="addMarker(0)">Add</button></th>
        </tr>
        <tr>
          <th>End Location</th>
          <th><GmapAutocomplete @place_changed="setPlace" /></th>
          <th style="width: 50%;"><button class="btn" @click="addMarker(1)">Add</button></th>
        </tr>
      </table>
    </div>
    <br />
    <GmapMap :zoom="7" :center="center" style="width: 100%; height: 400px">
      <DirectionsRenderer
        travelMode="DRIVING"
        :origin="startLocation"
        :destination="endLocation"
      />
    </GmapMap>
  </div>
</template>

<script>
import DirectionsRenderer from "@/components/DirectionsRenderer";

export default {
  name: "App",
  components: {
    DirectionsRenderer,
  },
  data() {
    return {
      center: { lat: 45.508, lng: -73.587 },
      currentPlace: null,
      markers: [],
      places: [],
      startLocation: null,
      endLocation: null,
    };
  },
  methods: {
    setPlace(place) {
      this.currentPlace = place;
    },
    addMarker(index) {
      const marker = {
        lat: this.currentPlace.geometry.location.lat(),
        lng: this.currentPlace.geometry.location.lng(),
      };
      if (index === 0) this.startLocation = marker;
      if (index === 1) this.endLocation = marker;
      this.center = marker;
    },
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

.pac-target-input {
  padding: 10px;
  width: 100%;
}

.btn {
  margin-left: 20px;
  padding: 10px 20px;
  background-color: greenyellow;
}
</style>

That’s it.

Output:

2 Comments

  1. Gecko

    i think that the API doesnt got in from promise
    my API do the same thing
    even on native JS

    0
    0
    Reply
  2. Balachandar

    return window.google.maps.DirectionsRenderer;

    here goole not found error showing

    0
    0
    Reply

Submit a Comment

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

Subscribe

Select Categories