Giter Club home page Giter Club logo

vsgoogleautocomplete's Introduction

vsGoogleAutocomplete

Angularjs autocomplete module using Google Maps JavaScript API v3 and embedded autocomplete validator

Demo

Features

  • Has special embedded validator for autocomplete validation
  • Can easy parse address components through special directives
  • Uses google formatted address as result of autocomplete
  • Uses last version of Google Maps JavaScript API (v3)

Install

bower install vs-google-autocomplete

Getting started

  1. Add the Google Places library script to your index.html
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
  1. Add vs-google-autocomplete.js to your index.html

  2. Add vsGoogleAutocomplete module dependency:

angular.module('yourApp', ['vsGoogleAutocomplete']);
  1. Add vs-google-autocomplete directive to input field:
<form>
  <input vs-google-autocomplete
         ng-model="address"
         name="address"
         type="text">
</form>

Autocomplete options

You can add an options object as attribute parameter, which will restrict autocomplete results.

Options object can contain the following properties:

  • types {Array.<string>} (In general only a single type is allowed):
    • 'geocode'
    • 'address'
    • 'establishment'
    • '(regions)'
    • '(cities)'
  • bounds {google.maps.LatLngBounds}
  • componentRestrictions {object}

Example:

<form>
  <input vs-google-autocomplete="options"
         ng-model="address"
         name="address"
         type="text">
</form>
$scope.options = {
  types: ['(cities)'],
  componentRestrictions: { country: 'FR' }
}

In example above, autocomplete results will only consist of cities of France.

Parsing address components

You can bind your model with autocomplete address components.

Directives for parsing:

  • vs-place - gets place detail results object
  • vs-place-id - gets unique identifier denoting place
  • vs-street-number - gets street number of place
  • vs-street - gets street name of place
  • vs-city - gets city name of place
  • vs-state - gets state name of place
  • vs-country-short - gets country iso code of place
  • vs-country - gets country name of place
  • vs-latitude - gets latitude of place
  • vs-longitude - gets longitude of place
  • vs-post-code - gets postcode of place
  • vs-district - gets district of place (administrative_area_level_2)

Example:

<form>
  <input vs-google-autocomplete="options"
         ng-model="address.name"
         
         vs-place="address.place" 
         vs-place-id="address.components.placeId"
         vs-street-number="address.components.streetNumber" 
         vs-street="address.components.street"
         vs-city="address.components.city"
         vs-state="address.components.state"
         vs-country-short="address.components.countryCode"
         vs-country="address.components.country"
	     vs-district = "address.components.district"
         
         name="address"
         type="text">
</form>

Embedded validator

Module, as an addition, also provides special validator for autocomplete validation.

Default usage

  1. Add vs-autocomplete-validator.js to your index.html

  2. Add vs-autocomplete-validator directive to input field:

<form>
  <input vs-google-autocomplete
         vs-autocomplete-validator
         ng-model="address"
         name="address"
         type="text">
</form>

By default, validator checks if autocomplete result is a valid google address (selected from drop down list).

Additional validators

You can add additional validator by adding denormalized validator name as attribute parameter. If you need more than one additional validator, you can add validator names using comma(,) separator.

Validator names in html are normalized in javascript code, so validator with name vsStreetAddress should have name vs-street-address in html.

Available validator names

  • vsStreetAddress - normalized name of validator, which checks if autocomplete result is full address (street number, street, ...)

This module is under development and now it has only one additional validator (and one by default). Please, if you need other additional validators, you can write about this in issues, we will be grateful to you :).

Example

<form>
  <input vs-google-autocomplete
         vs-autocomplete-validator="vs-street-address"
         ng-model="address"
         name="address"
         type="text">
</form>

In the example above validator will checks if autocomplete result is a valid google address and if it is a full address (street number, street, ...).

Validation errors

Validator publishes validation errors if validation is failed.

If validation is failed, validator publish error with name vsAutocompleteValidator to NgModelController.$error hash object and name of each embedded validator to NgModelController.vsAutocompleteErorr hash object.

Custom validators

You can also add your own validator for your own needs. Embedded validator should validate PlaceResult object, which returns after autocomplete. For this, you should add factory to your main module, which must return function.

Custom validator template:

angular.module('yourApp')
  .factory('validatorName', function() {
    /**
    * Implementation of custom embedded validator.
    * @param {google.maps.places.PlaceResult} PlaceResult object.
    * @return {boolean} Valid status (true or false)
    */
    function validate(place) {
    	// ...
    }
    	
    return validate;
  });

Rules for custom validator:

  • you should add factory to any module of your app
  • factory must always return function (embedded validator implementation)
  • function for validation always gets PlaceResult object as parameter
  • you should implement function, which returns
  • factory name - it is normalized embedded validator name (eg. 'validatorName' in factory can be 'validator-name' in html)

After adding custom validator, you should add its name as attribute parameter to vs-autocomplete-validator directive. Validator with name someValidatorName in factory should have name some-validator-name in html.

Core developers can inject in validator factory vsGooglePlaceUtilityservice, which contains useful functionality for working with PlaceResult object (parameter of function for validation). You can look at this utility service in vs-autocomplete-validator.js :).

Author

K.Polishchuk (http://github.com/vskosp)

License

MIT © K.Polishchuk

Credits

Google Maps JavaScript API https://developers.google.com/maps/documentation/javascript/places-autocomplete

vsgoogleautocomplete's People

Contributors

jeremy24 avatar psykolm22 avatar rpocklin avatar vskosp 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vsgoogleautocomplete's Issues

Getting rid of Placeholder text

I'm having a strange problem with vsGoogleAutocomplete and Material Design. See this Plunker:

http://embed.plnkr.co/HQzx72fUNG5rMHnHNcHp/preview

The issue is more obvious using Chrome, Firefox seems to hide placeholder text until it has been clicked. Basically, my inputs are getting populated with "Enter a Location" and they're messing with with my labels.

The example above shows 3 versions:

  1. Normal MD input w/ no placeholder
  2. Normal MD input w/ placeholder
  3. MD input w/ placeholder and label removed. Animations disappear with this option.
  4. Input pulled from the original Plunker

How are you able to overwrite the generated text or not get it in the first place? Option 3 is how I currently have this running but I'd like to get the animation back.

Brooklyn is not fetched as a city.

When I select any address in Brooklyn (e.g. 1280 Ocean Ave, Brooklyn, NY 11230, USA) the city field is not populated automatically. Though it works with any other city.

I don't the lat and lng value.

js
$scope.address = {
name: '',
place: '',
components: {
placeId: '',
streetNumber: '',
street: '',
city: '',
state: '',
countryCode: '',
country: '',
postCode: '',
location: {
lat: '',
long: ''
}
}
};

html

            <span class="help-block"><b>Model: </b>{{address.name}}</span>
      <span class="help-block"><b>Place id: </b>{{address.components.placeId}}</span>
      <span class="help-block"><b>Street number: </b>{{address.components.streetNumber}}</span>
      <span class="help-block"><b>Street: </b>{{address.components.street}}</span>
      <span class="help-block"><b>City: </b>{{address.components.city}}</span>
      <span class="help-block"><b>State: </b>{{address.components.state}}</span>
      <span class="help-block"><b>Country code: </b>{{address.components.countryCode}}</span>
      <span class="help-block"><b>Country: </b>{{address.components.country}}</span>
      <span class="help-block"><b>Postcode: </b>{{address.components.postCode}}</span>
      <span class="help-block"><b>Latitude: </b>{{address.components.location.lat}}</span>
      <span class="help-block"><b>Longitude: </b>{{address.components.location.long}}</span>

screen shot 2015-10-13 at 12 11 05 pm

Not filtering by cities

Hi,

I noticed in your demo and also in my app that if I set types to '(cities)' I still get all possible locations and not only cities. Could you please fix?

Thanks

Possible Bug : ng-change doesnt work with this plugin

I still didnt found solution to my previous problem, so as a workaround, temporary fix to get going i decided to put latitude and longitude in text boxes and then via $watch or ng-change i will use data in controller, but neither $watch nor ng-change works with this script, i wasnt sure about my code so i duplicated demo plunker and tried with that script and found that it didnt work with demo as well so i believe that ng-change doesnt work with this plugin.

My demo : http://plnkr.co/edit/FvdAzKBTRmVeSNI7qpG8?p=preview

Getting Lat, and Long

Hi @vskosp, Thank for the great plugin.
However I have a small problem with accessing the lat, long of the autofill place.

HTML

<div class="col-md-3">
     <label for="" class="control-label">Address</label>
     <input vs-google-autocomplete
         ng-model="hotelAddress.Address"
         vs-place="hotelAddress.Place"
         vs-latitude="hotelAddress.components.location.lat"
         vs-longitude="hotelAddress.components.location.long"

         type="text" 
         class="form-control input-sm"
         name="address"
         id="address"
         placeholder="address">
   </div>

JS

$scope.addLocation = function (hoteladdress) {
    $scope.Obj = {
        Name              : hoteladdress.Name,
        Address           : hoteladdress.Address,
        Zones_id          : hoteladdress.Zone.id,
        City_id           : hoteladdress.City.id,
        LocationsType_id  : hoteladdress.LocationType.id,
        Latitude          : hoteladdress.Place.geometry,
      };
      console.log($scope.Obj);
}

So as you can see I lat and lng are undefined and give me a function (). Do you have idea why is not working? Thank you in advance

Image of Yaktocat

Selected address is not placing in the text field

I typed '1 queens road' in the vs google autocomple text field. It shows me a suggestion '1 queens road, melbourne, australia'. When I click on it, the address placed in my text field is 'Suite 943/1 Queens Rd, Melbourne VIC 3004, Australia'.

I don't know how to place the exact autocomplete suggestion into my text field. Please anyone help me on this. Thanks in advance.

Styling is off in Firefox

I seem to be running into an error in Firefox. When I keypress into the field; I background overlays the value and the autocomplete is shown way below the field.

I'm not sure if this was my styling issue or something is deprecated in the file. Has anyone else ran into this issue?

Postcode component

Hello!

The address components are super handy, would it be possible to add a vs-postcode directive?
Thanks for the awesome module!

Clearing the field but the value returns

Whenever I type and search an item and then clear the value in the field, after clicking away, the value I just cleared appear again in the field. May not be a bug but this is quite bad for user interactivity.

How can I stop the field from being automatically filled again after clearing it?

Not work with IONIC v.1.0

I try to implement this plugin in my app but not get success every time I get a blank result on my screen. I Invest lot of hours, but not get success every time I get only name which I type in the input box. Please help me.

Issue with Injector

Hi,

I tried to inject your module into my script

But i keep on getting this error:
Module 'vsGoogleAutocomplete' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

I've loaded it on my module:
var app = angular.module('myApp',['ngRoute','ngFileUpload', 'vsGoogleAutocomplete']);
included your file after angular file and declare

     $scope.address = {
    name: '',
    place: '',
    components: {
      placeId: '',
      streetNumber: '', 
      street: '',
      city: '',
      state: '',
      countryCode: '',
      country: '',
      postCode: '',
      district: '',
      location: {
        lat: '',
        long: ''
      }
    }
  };

on the related controller.

But its still throwing that error, is there anyway to rectify it?

Thanks,
screen shot 2016-01-30 at 12 31 04 pm

How to show City, Country after autocomplete

Thanks for great directive, I just wanted to know How can I only show the City, Country in input field once user typed and selected some suggestion.

Currently I have below setup and its returning something like this once autocompleted.

<input type="text"
       name="city"
       vs-google-autocomplete="{ types:['(cities)'] }"
       ng-model="user.location"
       class="form-control"
       placeholder="Your City"
>

its populate input with

<City>, <State>, <Country>
<City>, <State> <ZipCode>, <Country>
...
New York, NY, USA
Barcelona, Barcelona, Spain

I want just City, Country

New York, USA

Please help how can I do that. Is there any option to pass format in directive

Warning: The implementation for types in text search requests is changing

Do you care about this warning from google https://developers.google.com/maps/documentation/javascript/places-autocomplete:
Warning: The implementation for types in text search requests is changing. The types parameter is deprecated as of February 16, 2016, replaced by a new type parameter which only supports one type per search request. Additionally, the establishment, place_of_worship, food, health, general_contractor and finance types will no longer be supported as search parameters (however these types may still be returned in the results of a search). Requests using the deprecated features will be supported until February 16, 2017, after which all text searches must use the new implementation.

Impossible to empty the input text

Hi,

if you search for a city and then you get the result, when you try to empty the input text the last result will be set to the input (the model).

So:

  1. search for 'Rome'
  2. you get 'Rome, Italy'
  3. empty the input
  4. you get 'Rome, Italy' again when the input loses the focus

Trigger Autocomplete

How can i prefill the autocomplete result in the input box. I am having issues while achieving this as when i set the model value to text address, the validator is not marking it as valid. How can i resolve it?

How to i access latitude and longitude in controller

I tried with
$scope.watch on address variable but that didnt work.

$scope.$watch('address', function () { console.log($scope.address); }, true);

i am working on script which shows neatby atms, script auto detects users location to show nearby atms as well as user can check atms in other areas/places using autocomplete plugin as well.

for that purpose i want to access address variable. But i couldn't.
if u use <span class="help-block"><b>Place id: </b>{{address.components.placeId}}</span> i can see values there but dont know why it doesnt show.

2 location textboxes overriding with new one

Hi, In a page I have 2 location search boxes for Move Out Location And Move In Location. When search for second location it overriding the first location information. How can overcome this issue? Please provide any suggestions

Accounting for sublocality

getCity() relies on "locality" being available in the place object.
However, some places only have "sublocality" and no "locality".
Places like Brooklyn will show no city when this function is called.

by the way this module is pretty incredible, so thank you.

Can't make input empty after selecting place + validation issue

Hey! We're using your module in our project, but we faced with such issue:

  1. Our autocomplete field is not required, so when user select some place he can change his mind, erase it and leave empty, but we can't do so with your module, because on blur value is getting back to previous one. Temporary I just checking if modelCtrl.$viewValue is empty we don't setting viewValue. Can you consider to implement such option?
  2. We're using vs-autocomplete-validator and field is invalid if empty.

Please provide an expanded demo.

While the existing demos are OK, as far as they go, they really don't capture a typical usage of an address form.

Please create an expanded demo ( similar to your existing "Demo with validator") except have every component of the address in it's own Label/Input code.

So the form should have lable/input fields which the user can enter data into, and that autofils:

  • Street number and street "105 north 1st ave"
  • City
  • State
  • Zip and Zip+4

Also, could your release package in NPM ?

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.