node-google-places
node-google-places copied to clipboard
Question? Browser-based issue with CORS
Trying to call places.autocomplete from a browser app (vue.js). Sorry if this turns out to be a question rather than an issue,.
Here's the code:
import Multiselect from 'vue-multiselect';
import debounce from 'lodash/debounce';
import cloneDeep from 'lodash/cloneDeep'
var GooglePlacesAPI = require('google-places');
var placeApi;
var vm;
module.exports = {
name: "GooglePlaces",
components: {
Multiselect
},
props: {
prop_id: String,
value: Object
},
data: function () {
return {
places: [],
selectedPlace: {},
isLoading: false,
resultCount: 0,
resultIndex: 0
};
},
created: function () {
vm = this;
placeApi = new GooglePlacesAPI('xxx'); //todo restrict
if (typeof vm.value === 'undefined') { return; }
vm.$set(vm, 'selectedPlace', cloneDeep(vm.value));
},
methods: {
googlePlaceSearch: debounce(searchString => {
if (searchString.length < 3) {
return;
}
vm.isLoading = true;
vm.resultCount = 0;
placeApi.autocomplete({ input: searchString, types: "(Regions)"}, vm.googlePlaceCallback);
}, 500),
googlePlaceCallback: function (err, response) {
if (err) {
console.log(err);
}
else {
places = [];
console.log("autocomplete: ", response.predictions);
vm.getPlaces(err, response);
}
},
getPlaces: function (err, response) {
for (var index in response.predictions) {
placesApi.details({ reference: response.predictions[index] }, vm.addPlace);
}
},
addPlace: function (err, response) {
if (err) {
console.log(err);
}
else {
places.push(response.result);
}
if (resultCount === resultIndex + 1) {
vm.isLoading = false;
vm.resultIndex = 0;
return;
}
vm.resultIndex++;
},
limitText: function (count) {
return `and ${count} other places`
},
placeChanged: function (newValue, id) {
//vm.$set(vm, 'selectedPlace', newValue); //handled by v-model
vm.$emit('input', newValue, id); //return as event per unidirectional data flow
},
}
};
Chrome is complaining:
Fetch API cannot load https://maps.googleapis.com/maps/api/place/autocomplete/json?input=vermont&types=(Regions)&language=en&sensor=false&key=xxx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I am experiencing the same issue and I have decided not to use this package but use Googles web api.
const PROXY_URL = 'https://cors-anywhere.herokuapp.com/';
const TARGET_URL = 'https://maps.googleapis.com/maps/api/place/autocomplete/json?&key=KEY'
const URL = PROXY_URL + TARGET_URL
this way using the proxy url you will be able to call the api