0

I currently work on vue.js project. The app goal is to check distance between 2 localisations, then show route on the map and calculate cost of transport which is based on the distance.

I use google directions api, axios for get request.

Problem is that, because of CORS, get request gives me an error (I run this app locally). I already tried chrome CORS plugin, but problem still exists.

error screenshot

Do You have any solutions or just idea how to solve this problem?

Thank You in advance.

P.S. Code below

import axios from 'axios';

const directionsApi = 'https://maps.googleapis.com/maps/api/directions/json?';
const apiKey = '&key=trust_me_the_key_is_valid';

export default {
  name: 'FirstForm',
  data() {
    return {
      fromValue: '',
      toValue: '',
      distance: '',
    };
  },
  methods: {
    handleFromToInput: function () {
      const fromTo = `origin=${this.fromValue}&destination=${this.toValue}`;
      axios.get(`${directionsApi}${fromTo}${apiKey}`)
        .then((response) => {
          // this.distance = response.routes[0].legs[0].distance.text;
          console.log(response.routes[0].legs[0].distance.text);
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
};
sticky bit
  • 36,626
  • 12
  • 31
  • 42
lysy.vlc
  • 79
  • 1
  • 10
  • 2
    Looks like you have to use the Google Maps JavaScript SDK instead of doing plain HTTP requests: https://github.com/googlemaps/google-maps-services-js/issues/59#issuecomment-399626833 Does that help you? – n1try Jan 29 '19 at 00:09
  • Google Maps JavaScript SDK? What do You mean? How could I get distance between two points just using normal javascript api? I have switched to distance matrix api and "postman" gives me pretty json with whole data I need. Problem still exist in vue app. – lysy.vlc Jan 29 '19 at 00:55
  • 1
    Why not use [VueGoogleMaps](https://www.npmjs.com/package/vue2-google-maps) package? – MrUpsidown Jan 29 '19 at 10:59

2 Answers2

3

Similar here

If you use Javascript API way to do,

  1. Create an account on Google Maps Platform
  2. Open Vue Project
  3. Make a js file (src/utils/gmap.js)
// src/utils/gmaps.js
const API_KEY = 'XXXXXYOURAPIKEYXXXX';
const CALLBACK_NAME = 'gmapsCallback';

let initialized = !!window.google;
let resolveInitPromise;
let rejectInitPromise;
const initPromise = new Promise((resolve, reject) => {
  resolveInitPromise = resolve;
  rejectInitPromise = reject;
});

export default function init() {
  if (initialized) return initPromise;

  initialized = true;
  window[CALLBACK_NAME] = () => resolveInitPromise(window.google);

  const script = document.createElement('script');
  script.async = true;
  script.defer = true;
  script.src = `https://maps.googleapis.com/maps/api/js?key=${API_KEY}&callback=${CALLBACK_NAME}`;
  script.onerror = rejectInitPromise;
  document.querySelector('head').appendChild(script);

  return initPromise;
}
  1. In view js (src/views/MyMap.vue)
<template>
  <div class="my-map">
      My Map
      <div id="map"></div>
  </div>
</template>

<script>
import gmapsInit from '@/utils/gmaps';
export default {
  name: 'myMap',
  components: {
  },
  data () {
    return {
    }
  },
  computed: {
  },
  async mounted() {
    try {
      const google = await gmapsInit();
    var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -34.397, lng: 150.644},
        zoom: 8
    });

    } catch (error) {
      console.error(error);
    }
  },
  methods:{
  }

}
</script>

<style>
#map{
    width:400px;
    height:400px;
}
</style>

Ref on

Using the Google Maps API with Vue.js

Maps JavaScript API, Hello World

Ka Lun Lau
  • 31
  • 3
0

I've found solution. Maybe it's not best but it works.

I've used cors-anywhere proxy.

https://cors-anywhere.herokuapp.com/${directionsApi}${fromTo}${apiKey}
lysy.vlc
  • 79
  • 1
  • 10