0

I am using vue front end for my app , I have vue-google-maps to show maps , and vue-google-places for searching place, I want to get place details with placeId, none of above package support this. I tried sending request to google maps api, I can make requests from Postman or by pasting link in the browser I am getting data in response but when i make request from frontend it gives me CORS error. searching internet i found this StackOverflow question Google Maps API: No 'Access-Control-Allow-Origin' header is present on the requested resource it suggest that Google maps api is for server side only, reading google maps api documentation for js i found they had sdk but that needs to be included as script-tag to work for frontend. My question is how to do this in Vue, including such script stages in vue would be messy right? is there any npm package that might help, any reference or example is appreciated.

1 Answers1

0

1. use this library https://github.com/xkjyeah/vue-google-maps

npm install vue2-google-maps

or

yarn add vue2-google-maps

// somewhere u initialize main Vue app instance or install vue plugin, maybe in main.js
import Vue from 'vue';
import * as VueGoogleMaps from 'vue2-google-maps';

Vue.use(VueGoogleMaps, {
  load: {
    key: 'YOUR_API_KEY',
    libraries: '', // google map library u want to use
  },
  installComponents: true
});
import Vue from 'vue';
import {gmapApi} from 'vue2-google-maps';

export default class SomeComponent extends Vue {
  computed: {
    google: gmapApi,
  },
  data() {
    return {
      placeId: '',
      geocoder: null
    }
  }
  mounted() {
    this.$gmapApiPromiseLazy().then(() => {
      if(this.google) {
        this.geocoder = new this.google.maps.Geocoder();
      }
    });
  },
  methods: {
    geocode() {
      this.geocoder.geocode({placeId: this.placeId}, (results, status) => {
        console.log(results,status);
      })
    }
  }
}

after some studies on google map documentation, to search by placeId, u are more likely to use geocoder

https://developers.google.com/maps/documentation/javascript/reference/geocoder

https://developers.google.com/maps/documentation/javascript/examples/geocoding-place-id


2. rest api https://developers.google.com/maps/documentation/geocoding/intro#place-id

should be something like this:

https://maps.googleapis.com/maps/api/geocode/json?place_id=ChIJd8BlQ2BZwokRAFUEcm_qrcA&key=YOUR_API_KEY

LHJ
  • 672
  • 5
  • 13