Giter Club home page Giter Club logo

vue-google-autocomplete's Introduction

Vue Google Autocomplete

npm version sponsored_by

A Vue.js (2.x) autosuggest component for the Google Maps Places API.

Demo

Live demo: olefirenko.github.io/vue-google-autocomplete

Benefits

I have tried to use different Vue Google Autocomplete components, but did not find any that would solve my needs. So below I would like to mention what you can get from this exact component:

  • Load more than one autocompletion inputs (I could not achieve this with existing vue components)
  • Getting geolocation data (latitude, longitude) for found address object along with other address data (country, city, state, county, street, house number, zip code). So no need to do additional geocode request on backend side.
  • No external dependencies
  • You can get access to underlying PlaceResult object to get more details about found location. You are able to specify the specific fields you want to fetch from the PlaceResult object.
  • You can limit results to specific country or use users geolocation data

Installation

This component uses Google Maps Places API to get geo suggests for autocompletion, so you have to include the Google Maps Places API in the <head> of your HTML:

<!DOCTYPE html>
<html>
  <head><script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_HERE&libraries=places"></script>
  </head>
  <body></body>
</html>

To obtain API key please visit the Google Developer Console. The API's that you have to enable in your Google API Manager Dashboard are Google Maps Geocoding API, Google Places API Web Service and Google Maps Javascript API.

The easiest way to use Vue Google Autocomplete is to install it from npm or yarn.

npm install vue-google-autocomplete --save

Or

yarn add vue-google-autocomplete

Usage

The Vue Google Autocomplete works out of the box by just including it.

import VueGoogleAutocomplete from "vue-google-autocomplete";

In your template you can use this syntax:

<vue-google-autocomplete id="map" classname="form-control" placeholder="Start typing" v-on:placechanged="getAddressData">
</vue-google-autocomplete>

Properties

id

Type: String

required ID for the input container.

classname

Type: String

Class to the input container.

placeholder

Type: String Default: Start typing

The input field will get this placeholder text.

types

Type: String Default: address

Types supported in place autocomplete requests. More info

You may find this example helpful.

fields

Type: Array Default: ['address_components', 'adr_address', 'alt_id', 'formatted_address', 'geometry', 'icon', 'id', 'name', 'permanently_closed', 'photo', 'place_id', 'scope', 'type', 'url', 'utc_offset', 'vicinity']

Set which data fields to return in the PlaceResult from the Google Autocomplete API when the user selects a place. Google Autocomplete API by default returns all available data fields for the selected place, which may result in additional charges and thus the API users might pay for data they don't need. This package sets a sensible default for the fields value, fetching only the Basic Data fields which do not result in any additional charges. If you want to fetch other fields in addition to the default ones, make sure that the array you pass in to the fields prop contains the default fields listed above, and not only the additional fields you want to fetch.

Refer to this page for more details on how certain data fields are billed.

country

Type: String|Array Default: null

Option to restrict the autocomplete search to a particular country. Countries must be passed as a two-character, ISO 3166-1 Alpha-2 compatible country code (i.e. "br", "sg", "fr"). You can provide a single one, or an array of up to 5 country code strings. Note: this is a dynamic property. You must pass it as :country="" to your component, otherwise it won't work. For example:

<vue-google-autocomplete :country="['au', 'nz']"></vue-google-autocomplete>

will restrict the countries to Australia and New Zealand.

enable-geolocation

Type: Boolean Default: false

Bias the search towards user current location.

geolocationOptions

Type: Object Default: {}

Allow to configure Options for navigator.getCurrentPosition

Events

The component emits next events, which you can listen in your application:

placechanged

Gets triggered when the address data got obtained. This data is available on the returned objects:

  • street_number, route, locality, administrative_area_level_1, country, postal_code, latitude, longitude.
  • place - PlaceResult object is available as second parameter.
  • id a String representing the ID of the autocomplete that triggered the event.

no-results-found

Gets triggered when a user entered the name of a Place that was not suggested and pressed the Enter key, or the Place Details request failed.

  • object an object with a key name representing the user's input.

focus

Gets triggered when the autocomplete input field receives focus.

blur

Gets triggered when the autocomplete input field loses focus.

inputChange

Gets triggered every time autocomplete input got changed

change

Gets triggered when the autocomplete results got changed

keypress

Gets triggered when a key gets pressed

error

Gets triggered when an error is encountered

Exposed component functions

These functions are accessible by setting "ref" on the component (Refs documentation). See example below how to use these functions.

clear()

Call to clear the value of the user input.

focus()

Call focus to focus on the element

blur()

Call blur to blur (unfocus) the element

update(value)

Call to update the user input with a new value

updateCoordinates(latlng)

Call to force coordinates and update the input accordingly

geolocate()

Call to retrieve current position from navigator and update the input accordingly

Example

Please note that you need to provide what method will listen (v-on:placechanged) to an event when the address data is obtained.

<template>
  <div>
    <h2>Your Address</h2>

    <vue-google-autocomplete
      ref="address"
      id="map"
      classname="form-control"
      placeholder="Please type your address"
      v-on:placechanged="getAddressData"
      country="sg"
    >
    </vue-google-autocomplete>
  </div>
</template>

<script>
  import VueGoogleAutocomplete from "vue-google-autocomplete";

  export default {
    components: { VueGoogleAutocomplete },

    data: function () {
      return {
        address: "",
      };
    },

    mounted() {
      // To demonstrate functionality of exposed component functions
      // Here we make focus on the user input
      this.$refs.address.focus();
    },

    methods: {
      /**
       * When the location found
       * @param {Object} addressData Data of the found location
       * @param {Object} placeResultData PlaceResult object
       * @param {String} id Input container ID
       */
      getAddressData: function (addressData, placeResultData, id) {
        this.address = addressData;
      },
    },
  };
</script>

Correct usage of the types parameter

The example below shows the correct usage of the types parameter, when limiting the search to cities:

<vue-google-autocomplete
  id="map2"
  ref="toAddress"
  classname="form-control"
  placeholder="Start typing"
  v-on:placechanged="getToData"
  types="(cities)"
  country="us"
>
</vue-google-autocomplete>

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Dmytro Olefyrenko

💻

Daryle Dale De Silva

💻

DjilanoS

🚧

Juan Villegas

💻

Hugh Saffar

💻

Ahmed

💻

Ankur Kumar

💻

Artur Grigio

💻

Brian Rutledge

💻

Bryan Miller

💻

Chris Sepic

💻

Dennis van Breukelen

💻

Dmitry Mazurok

💻

Julian Renard

💻

Leonardo Arroyo

💻

Max Lyashuk

💻

Michał Gibowski

💻

Mickey Schwab

💻

Romain Léger

💻

Simon Kimber

💻

syffs

💻

Yann Bertrand

💻

ciaasteczkowy

💻

crabaux

💻

This project follows the all-contributors specification. Contributions of any kind welcome!

vue-google-autocomplete's People

Contributors

allcontributors[bot] avatar ankurk91 avatar arturgrigio avatar bemyguestdmitriy avatar bhrutledge avatar bryanjamesmiller avatar cgs avatar crabaux avatar daryledesilva avatar discountedcookie avatar djilanos avatar eoksni avatar hughsaffar avatar juanvillegas avatar julianfox avatar leonardoarroyo avatar liliumdev avatar mgibowski avatar mickeyschwab avatar mrgix avatar olefirenko avatar probil avatar rleger avatar skmbr avatar syffs avatar yannbertrand avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-google-autocomplete's Issues

Add custom result as last suggestion

It would be nice to add a custom result choice as last suggestion, in case where the API can't found the address.

I still didn't found a proper way to do it, any idea ? If I have a solution is it suitable for a Pull request ?

ReferenceError: google is not defined on Production

Hello there !

First : Thanks so much for this component, it's awesome :)

I am running into a small problem. Everything works great on development, but when I run npm run dev, and start using in production, I get the following error :

vue.esm.js:523 ReferenceError: google is not defined

Any ideas on what could be going wrong ?

InvalidValueError: not an instance of HTMLInputElement

Im getting the error above in a component where in using VueGoogleAutocomplete

The code is pretty simple:
vue-google-autocomplete(id="gaddress2222", placeholder="Endereço", v-on:placechanged="test", v-on:no-results-found="test")

I am importing the component too
components: { QModal, QField, QInput, QSelect, QPopover, QBtn, QAutocomplete, QIcon, QSearch, QDatetime, VueGoogleAutocomplete},

And I have the gmaps API script on my index.html

So I cant understand what's wrong, seems link a bug

I even have vue-google-autocomplete working perfectly in this same project, in another component, with the same code

edit: testing more, the problem seems intermittent: sometimes I just wont get the error, and the component will work normally

How to insert address to vue-google-autocomplete field by click button?

Hello. I try to make hybrid search address system: classic autocomplete and many buttons with pre-bind addresses. So, how to insert bind address to vue-google-autocomplete field by click button?

On my template:

<vue-google-autocomplete ref="address" ... ></vue-google-autocomplete>
<button v-on:click="swapAddress('New York, USA')">New York, USA</button>

And js:

...
methods: {
    swapAddress: function (location) {
        this.$refs.address = location;
    },
}
...

But it doesn't work. Please help me.

componentRestrictions other than country

Hi,
thanks for your great work !

Would it possible to add the ability to pass other componentRestrictions options such as route, locality, administrativeArea and postalCode ? I'm in Canada and need to restrict my search to specific provinces.
You exposed the country part but not the others.

Thanks.

feature request: add v-model

Pretty much all vue input components support v-model, both vue-native and third-party components. I think it is very convenient and well-known (among vue users) concept, and I think it would be great to be implemented in this awesome in other aspects component.

P. S. I know I can use @placechanged + update method via ref to emulate similar thing as v-model, but it is really not quite Vue-recommended way of doing things. Ref is always considered like more like a workaround than a proper solution.

If you don't mind this feature, I could make a PR with it some time later.

Version's tag

Could you please, add version's tag for releases?

Restrict input to city only?

Hi Dmitriy,
Thank you for making this component available.
I have a case where I don't need detailed address, but only city information. Could this component get one more parameter saying what type of location we want (street address, city, etc)? According to this answer it's possible to restrict the input:
https://stackoverflow.com/questions/8282026/how-to-limit-google-autocomplete-results-to-city-and-country-only/10170421#10170421
I'm looking myself into it, but I just started with Vue, so I would appreciate some direction.

Blur first value

Hello and thanks a lot for this Plugin :). It is very easy and comfortable to use 👍 .

But there is 1 Problem I have. The placechanged event will not be triggered if the user doesn't choose a value from the dropdown. I wanted to know if there is a possibility to trigger this event with a blur and provide the first address that google would recommend?

I would be very grateful for your help.

language parameter

It would be very useful to have the language parameter in this component.

error installing

$ npm install vue-google-autocomplete --save
npm WARN [email protected] requires a peer of ajv@^6.0.0 but none is installed. You must install peer dependencies yourself.

How to

Hello, thanks for this great component.

I am being able already to make it work, and it is like a charm!

I am now trying to pass a value when I edit the record and I would like to populate this field, I guess it is using the ' autocompleteText ' data. I tried to set v-model="updatedvaluenew" and get the variable using the computed variable but still no luck, any thoughts?

Thanks

If user input directly?

for example, if the user input
"725 5th Ave, New York, NY 10022, USA"
then hit enter, ignore all the auto-completion, how can I get this address?

Thanks.

Is there any way to disable autofill behaviour in Chrome?

When typing an address in the field I get the Google Map autocomplete displaying with the Google Chrome autofill pane rendering over the top. Is there a way to disable Chrome's Autofill so it doesn't obscure the autocomplete?

The input already has "autocomplete=off" but Chrome no longer seems to pay attention to this.
I've also tried overriding the "autocomplete" parameter with a semantic name, using autocomplete="false" and have tried using hidden fields with the same name. (All of these are suggested methods for disabling autocomplete, but none of them seem to work)

The only method I've found that works is adding automcomplete="off" to the wrapping form element, but that will disable autocomplete on all other inputs.

All types autocomplete not working?

I may be using the types property incorrectly, but here is what I see:

  • Don't supply the prop, get the default address type
  • Supply the prop, get the specified type back

However, in the google places API, it states (regarding autocomplete result types):

"If nothing is specified, all types are returned."

How do I tell the autocomplete element to not pass any type parameter to the API so I can get back all results?

Can't find all places

Hi. I have a problem, i can't find all places.
For exemple „Sadaclia”
Here is example with your plugin:
screen shot 2017-06-19 at 5 48 26 pm

And here is another autocomplete:
screen shot 2017-06-19 at 5 49 12 pm

Pls help me.

How to use in nuxtjs?

I am getting an error render function or template not defined in the component

I am not sure if this is the actual error. Because nuxt 1.4.0 throws this error most of the time without showing the actual error. I am not able to get this working in nuxtjs.

Limit search for only one city?

Hello. Thanks for your plugin!

Question is how to limit autocomplete search for one city?
For example, how to get addresses only for USA (country) and New York (city)?

I think, you may add option to plugin like city and send string from this option as start prefix in query for Google Maps API.

<vue-google-autocomplete
   ...
   types="address"
   city="New York"
   ...
>
</vue-google-autocomplete>

It's will be very helpful 👍

please add input name prop and return event when input value change

prop name

<input
          ref="autocomplete"
          type="text"
          :name="inputName"
          :class="classname"
          :id="id"
          :placeholder="placeholder"/>
  inputName: {
             type: [String, Array],
             default: 'autocomplete'
          },

event when input value change

onChange(event) {
              this.$emit('change', this.autocompleteText,event);
              },

it will help many very much for v-for input and @submit (event) for lame value

default value

Hello guys
Is there any way to define a default address or not?

Version of Vue

Hello, which Vue.js version do you support? Not working with Vue 2.2.1

How to prevent enter action after choosing address?

Hello.

I have a form on my site (Django + Vue.js frontend) where I'm using your awesome vue plugin. But if I click enter key (on keyboard) for choosing address (in Google drop-down menu) – form is submitting :(

I try to add to <vue-google-autocomplete ...> tag this attribute: @keydown.enter.prevent but it's not working. Help me, please.

IOS Problem

Hi! I just stepped on a problem with iPhones. You start typing, the autocomplete works fine suggesting resutls, but it's impossible to select one of the given options of the dropdown list.
When you click on them, the focus is set on the input again.

Thx in advance!

For posterity: conflict between bound `type` property in Vue component and Google Maps API JS

Hi there -- thanks for an excellent component! I incorporated the core VueGoogleAutocomplete.vue component into a generic form input field component and discovered a strange conflict (strange to me, anyway -- I'm new to Vue and the Google Maps API):

When setting a type attribute on the <input> element in the component template using a bound prop (:type='inputType'), the Google Maps scripts wouldn't attach properly to the element. By applying the attribute using $refs (e.g. this.$refs.[refname].setAttribute('type', inputType)), I was able to avoid the conflict.

Not sure what was going on here, but just wanted to mention the issue and my workaround in case that's helpful to others.

Binding value to v-model

Unable to bing value to v-model.After user selects the value the value is not reflecting in model.

Types parameter doesn't work

I'm not able to make the component bring only cities or localities.
The documentation says I can pass types parameter but It doesn't work.

Even If I pass 'address' which is the default it doesn't work; it forces me to take out the parameter.

How can I make it bring only cities/ localities?

Thanks a lot

Using alternative inputs with the component

Recently I needed to use vue-google-autocomplete with v-text-field(from vuetify). To do that I needed to fork vue-google-autocomplete and modify the template section.

Do you think it would be within the scope of this lib to accept multiple input fields or a fork would be better?

Feature request: allow Google Maps API script to be loaded asynchronously

This component works great, but it would be even better if it could work when the Google Maps API script is loaded asynchronously.

Right now, if you set the API script to load asynchronously, the component can mount and run the mounted function before the script has fully loaded, throwing an error. I'm not that skilled a JS programming so I don't know how best to handle this, but an interesting idea using dynamic components was posted on the Laracasts forum in case that's helpful.

Thanks for sharing your work on this component, in any case -- it's a big help!

Multiple countries

Hey.

Is there an option to limit to several countries instead of 1 ?
Something like countries="['de', 'gb', 'ru']" ?

if not, how could I achieve that?

Thanks in advance

Compilation error

Hi everyone. Recently I encounter vue compilation error like this.

{ [Error: ./\~/buble-loader!./\~/vue-loader/lib/selector.js?type=script&index=0!./\~/vue-google-autocomplete/src/VueGoogleAutocomplete.vue
    Module build failed: Error
    at Node.initialise (/node_modules/buble/dist/buble.umd.js:2004:65)
    at /node_modules/buble/dist/buble.umd.js:9381:56
    at Array.forEach (<anonymous>)
    at Node.initialise (/node_modules/buble/dist/buble.umd.js:9381:15)
    at Node.initialise (/node_modules/buble/dist/buble.umd.js:858:12)
    at Node.initialise (/node_modules/buble/dist/buble.umd.js:2098:31)
    at Node.initialise (/node_modules/buble/dist/buble.umd.js:858:12)
    at /node_modules/buble/dist/buble.umd.js:856:61
    at Array.forEach (<anonymous>)
@ ./\~/vue-google-autocomplete/src/VueGoogleAutocomplete.vue 3:2-105
@ ./resources/assets/js/app.js]
    message: './\~/buble-loader!./\~/vue-loader/lib/selector.js?type=script&index=0!./\~/vue-google-autocomplete/src/VueGoogleAutocomplete.vue\nModule build failed: Error\n    at Node.initialise (/node_modules/buble/dist/buble.umd.js:2004:65)\n    at /node_modules/buble/dist/buble.umd.js:9381:56\n    at Array.forEach (<anonymous>)\n    at Node.initialise (/node_modules/buble/dist/buble.umd.js:9381:15)\n    at Node.initialise (/node_modules/buble/dist/buble.umd.js:858:12)\n    at Node.initialise (/node_modules/buble/dist/buble.umd.js:2098:31)\n    at Node.initialise (/node_modules/buble/dist/buble.umd.js:858:12)\n    at /node_modules/buble/dist/buble.umd.js:856:61\n    at Array.forEach (<anonymous>)\n @ ./~/vue-google-autocomplete/src/VueGoogleAutocomplete.vue 3:2-105\n @ ./resources/assets/js/app.js',
        showStack: false,
    showProperties: true,
    plugin: 'webpack-stream',
    __safety: { toString: [Function: bound ] } }

Do you have any idea what is wrong with this.
Some of my colleagues didn't face with it. Unfortunately I did.

I use linux mint 17

Only street names not places

Thansk a lot for the component.

I want to also get the geo references when someone type a place, currently it is only retrieving street location o cities but it does not work correctly when looking for places

Any thoughts?

You have included the Google Maps API multiple times on this page. This may cause unexpected errors.

Hi,

I have the script in my head.

  <script src="https://maps.googleapis.com/maps/api/js?key=XXX-XXX&libraries=places"></script>

But there seems to be another script added automatically at the end of my body...

<script src="https://maps.googleapis.com/maps/api/js?key=XXX-XXXXXX&amp;libraries=places&amp;callback=vueGoogleMapsInit" async="" defer=""></script>

So I got this message coming around:

You have included the Google Maps API multiple times on this page. This may cause unexpected errors.
uh @ js?key=XXX&libraries=places&callback=vueGoogleMapsInit:101
(anonymous) @ js?key=XXX&libraries=places&callback=vueGoogleMapsInit:149
google.maps.Load @ js?key=XXX&libraries=places&callback=vueGoogleMapsInit:21
(anonymous) @ js?key=XXX&libraries=places&callback=vueGoogleMapsInit:149
(anonymous) @ js?key=XXX&libraries=places&callback=vueGoogleMapsInit:150

Any ideas?

If I remove the one in the header I have an error saying google is undefined...

Refresh the country filter

I have the country attribute pointing to my model: :country="form.step1.contact.country.toLowerCase()"

form.step1.contact.country.toLowerCase() change the value based on a dropdown.

Based in the Vue debugger, form.step1.contact.country.toLowerCase() value is correct, for instance 'es' - however the filter seems to be working only on load time, no if you modify it afterwards.

Any ideas?

Clear autocompleteText

Hi,

I like to clear the autocompleteText and found that this should be able through the clear() method, but I don't get how to use it. Can you give me a hint?

Can we search based store name ?

there is types in props for this component. but what types do we use to search location based store name ?? is this supported ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.