Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using google places autocomplete with angular2-google-maps #782

Closed
samredway opened this issue Dec 9, 2016 · 15 comments
Closed

Using google places autocomplete with angular2-google-maps #782

samredway opened this issue Dec 9, 2016 · 15 comments

Comments

@samredway
Copy link

Issue description

Unable to get hold of the 'google' object.

Steps to reproduce and a minimal demo of the problem

I am currently working on an angular2 application which uses Google Maps.

I have embedded and instance of Google Maps into the app using the excellent sebm angular2-google-maps module.

The problem I now have is that I would like to use the google place autocomplete search bar.

I have imported the module into my map module like this:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AgmCoreModule } from 'angular2-google-maps/core';
import { MapComponent } from './map.component';

@NgModule({
  imports: [
    CommonModule,
    AgmCoreModule.forRoot({
      apiKey: '************************',
      libraries: ['places']
    })
  ],
  declarations: [MapComponent]
})
export class MapModule { }

Which works fine re the map itself. However all the documentation I can find ( for example this thread ) says that the 'google' object should exist globally now and that I should be able to get hold of it by simply declaring it in my component i.e.

declare var google: any;

When I try this though and then try to use the google object e.g.

console.log(google);

... it gives me the error that google is undefined.

_Use https://plnkr.co or similar -- try this template as a starting point: http://plnkr.co/edit/YX7W20?p=preview

What steps should we try in your demo to see the problem?

Current behavior

google is undefined

Expected/desired behavior

the google object should be globally accessable

angular2 & angular2-google-maps version

0.16.0

Other information

@NathanielMalca
Copy link

+1

@ericel
Copy link

ericel commented Dec 11, 2016

I am facing the same problem with my app.

@nthonymiller
Copy link

nthonymiller commented Dec 12, 2016

You need to inject the MapsAPILoader into your class, then call the load method.

Until the loader is complete the google object will not be accessible.

Example:

constructor(private _mapsAPILoader: MapsAPILoader) { }

ngAfterViewInit() {
this._mapsAPILoader.load().then(() => {
// Place your code in here...
});
}

@sebholstein
Copy link
Owner

Yeah this the right way to go right now. We will improve it with #740.

@yuzhva
Copy link

yuzhva commented Feb 3, 2017

Is there any opportunity to set a language for MapsAPILoader?

    // Load Places Autocomplete
    this.mapsAPILoader.load().then(() => {
      let autocomplete = new google.maps.places.Autocomplete(this.searchInputRef.nativeElement, {
        types: ['address']
      });
      autocomplete.addListener('place_changed', () => {

        this.ngZone.run(() => {
          // get the place result
          let selectedPlace = autocomplete.getPlace();

         // place.formatted_address => is in english, because I didn't setup it.
         // Need to have opportunity for localization of formatted_address
        });
      });
    });

UPDATE: One of the possible solutions - add language and region keys to the params object like:

import { AgmCoreModule } from 'angular2-google-maps/core';

const googleMapsParams = {
  apiKey: environment.GOOGLE_MAPS_API_KEY,
  libraries: ['places'],
  language: 'uk',
  region: 'UA'
};

...
imports: [
    BrowserModule,
    ...
    AgmCoreModule.forRoot(googleMapsParams)
  ],

@nicolas-piquerez
Copy link

Would be great if someone could provide a full example of autocomplete binding with model.address. Or maybe add an input to your Getting started example ? I can see a lot of changes in last 12 months, so most examples are now out of date.

@yuzhva
Copy link

yuzhva commented Mar 13, 2017

@clenoma That article was really helpful for me: http://brianflove.com/2016/10/18/angular-2-google-maps-places-autocomplete/

@totallytotallyamazing
Copy link

Very interested in this because I would go a step further than @clenoma and say, all examples are unfortunately out of date. I would like to get involved in this.

@totallytotallyamazing
Copy link

totallytotallyamazing commented Apr 27, 2017

My Google Maps API is now working.
These two plnkr's helped me out quite a bit.
Hopefully they help someone else out too.

http://plnkr.co/edit/V0ZyOvVvxAehPo7sDBic?p=preview

https://plnkr.co/edit/LdKdSj?p=preview

@devbirBrst
Copy link

Unable to get the 'google' object, still undefined, compilation fails because it is not declared.

@garthmountain
Copy link

import {} from '@types/googlemaps';

@telenord
Copy link

telenord commented Jul 27, 2017

In my proj we use g-map in directives and solve it this way:
declare var google: any;
Of course this works too:
declare let google: any;

@epitomz
Copy link

epitomz commented Aug 1, 2017

@yuzhva I used your solution to make the search places feature work but I'd like to use the received viewport to fit the bounds of my map depending on the result of the request.

I can't do anything with the type google.maps.LatLngBounds and the fitBounds() method of the GoogleMapsAPIWrapper service. Any idea? Thanks

@atom-morgan
Copy link

The solution provided by @telenord works for me both locally and when building my application for production. Importing @types/googlemaps eventually gave me errors when running ng build --aot -prod.

@inorganik
Copy link

inorganik commented Mar 26, 2018

For the sake of completeness:

import { Component, OnInit } from '@angular/core';
import { MapsAPILoader } from '@agm/core';

declare let google: any;

@Component({
	selector: 'place-search',
	templateUrl: './place-search.component.html'
})

export class PlaceSearchComponent implements OnInit {

	placeService: any;
        placeServiceIsReady = false;

	constructor(private _loader: MapsAPILoader) { }

	ngOnInit() {
		this._loader.load().then(() => {
			this.placeService = new google.maps.places.AutocompleteService();
                         this.placeServiceIsReady = true;
		});
	}

        autoComplete() {
             if (this.placeServiceIsReady) {
                 // ...do stuff with place service
             }
        }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests