I am trying to add autocomplete to my project with angular2-google-maps. I add AgmCoreModule.forRoot (with libraries: 'places') in my AppModule and then added the autocomplete code in my component. Still I get "Cannot read property 'Autocomplete' of undefined" error. I tried checking the value of global var google, and google.map does not contain 'places' field. I am relatively new to angular2, so would need some help to understand what I am missing. My code is
in AppModule
import { AgmCoreModule } from 'angular2-google-maps/core';
#NgModule({
bootstrap: [ App ],
declarations: [
App,
ErrorComponent,
],
imports: [ // import Angular's modules
AgmCoreModule.forRoot({
apiKey: '[API_KEY_REDACTED]',
libraries: ["places"]
}),
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpModule,
TranslateModule.forRoot(),
RouterModule.forRoot(ROUTES, { useHash: true })
],
providers: [ // expose our Services and Providers into Angular's dependency injection
ENV_PROVIDERS,
APP_PROVIDERS,
]
})
export class AppModule {
In AppComponent:
import {MapsAPILoader} from 'angular2-google-maps/core';
import { NgZone } from '#angular/core';
declare var google: any;
export class EventInfoTab {
#ViewChild('gmap') gmap:any;
constructor(
private _loader: MapsAPILoader,
private zone : NgZone,
)
ngAfterViewInit(): void {
this._loader.load().then(() => {
let address = document.getElementById("location");
console.log("google", google);
let autocomplete = new google.maps.places.Autocomplete(address, {});
console.log ("autocomplete",autocomplete);
google.maps.event.addListener(autocomplete, 'place_changed', () => {
this.zone.run(() => {
console.log ("autocomplete place_changed",autocomplete);
var place = autocomplete.getPlace();
this.lat = place.geometry.location.lat();
this.lng = place.geometry.location.lng();
//alert(JSON.stringify(place));
this.markers[0] ={
lat: this.lat,
lng: this.lng,
label: 'x',
draggable: false
};
});
});
});....
So, I was able to make it work. I was trying to include the map with autocomplete in a feature component, after routing from the main component. I removed the code
'AgmCoreModule.forRoot({
apiKey: '[API_KEY_REDACTED]',
libraries: ["places"]
}),'
from app module.ts and added it in the feature's module.ts imports and it worked.
Since Pooja got hers working, and I had already completed a working example of Angular2 + angular2-google-maps + Autocomplete for her, I thought I'd add the code here to help future developers looking for something similar.
import {
Component,
NgModule,
OnInit,
NgZone
} from '#angular/core';
import {
BrowserModule
} from '#angular/platform-browser';
import {
AgmCoreModule,
MapsAPILoader
} from 'angular2-google-maps/core';
declare var google: any;
#Component({
selector: 'my-app',
styles: [`
.sebm-google-map-container {
height: 300px;
}
`],
template: `
<sebm-google-map
[latitude]="lat"
[longitude]="lng"
[zoom]="zoom"
[disableDefaultUI]="false"
[zoomControl]="true">
<sebm-google-map-marker
*ngFor="let m of markers; let i = index"
(markerClick)="clickedMarker(m.label, i)"
[latitude]="m.lat"
[longitude]="m.lng"
[label]="m.label"
[markerDraggable]="m.draggable"
(dragEnd)="markerDragEnd(m, $event)">
<sebm-google-map-info-window>
<strong>InfoWindow content</strong>
</sebm-google-map-info-window>
</sebm-google-map-marker>
</sebm-google-map>
<input type="text" id="autocompleteInput">
`})
export class App implements OnInit {
constructor(
private _loader: MapsAPILoader,
private _zone: NgZone) {
}
ngOnInit(): void {
this.autocomplete();
}
autocomplete() {
this._loader.load().then(() => {
var autocomplete = new google.maps.places.Autocomplete(document.getElementById("autocompleteInput"), {});
google.maps.event.addListener(autocomplete, 'place_changed', () => {
this._zone.run(() => {
var place = autocomplete.getPlace();
this.markers.push({
lat: place.geometry.location.lat(),
lng: place.geometry.location.lng(),
label: place.name,
});
this.lat = place.geometry.location.lat();
this.lng = place.geometry.location.lng();
console.log(place);
});
});
});
}
// google maps zoom level
zoom: number = 8;
// initial center position for the map
lat: number = 51.673858;
lng: number = 7.815982;
clickedMarker(label: string, index: number) {
console.log(`clicked the marker: ${label || index}`)
}
mapClicked($event: MouseEvent) {
this.markers.push({
lat: $event.coords.lat,
lng: $event.coords.lng
});
}
markerDragEnd(m: marker, $event: MouseEvent) {
console.log('dragEnd', m, $event);
}
markers: marker[] = [];
}
// just an interface for type safety.
interface marker {
lat: number;
lng: number;
label?: string;
draggable: boolean;
}
#NgModule({
imports: [
BrowserModule,
AgmCoreModule.forRoot({
libraries: ['places']
})
],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
Working Plnkr
4/17/2017 UPDATE
In version 1.0.0-beta.0 - green-zebra, the AGM team released a breaking change with the naming of their components which will require an update to your template file as follows:
<agm-map
[latitude]="lat"
[longitude]="lng"
[zoom]="zoom"
[disableDefaultUI]="false"
[zoomControl]="true">
<agm-marker
*ngFor="let m of markers; let i = index"
(markerClick)="clickedMarker(m.label, i)"
[latitude]="m.lat"
[longitude]="m.lng"
[label]="m.label"
[markerDraggable]="m.draggable"
(dragEnd)="markerDragEnd(m, $event)">
<agm-info-window>
<strong>InfoWindow content</strong>
</agm-info-window>
</agm-marker>
</agm-map>
<input type="text" id="autocompleteInput">
An updated version of the above plnkr/code can be found in the following GitHub repo.
I also have the same issue, but different cause. I use the map inside modal (pop-up)
let address = document.getElementById("location");
let autocomplete = new google.maps.places.Autocomplete(address, {});
In my case the above code run inside ngOnInit, the problem is the text input element is still not created.
You need to put the autocomplete code inside a function which runs each time the elements are created. I tried ngAfterViewInit, but didn't work
Related
My map is not loading and no error is being displayed in the console.
please help.
this is the error screenshot as shown in the browser
there is no build error while compiling the code neither any error is thrown but the ma form mabox is not loading and is written as - Missing mapbox Gl JS CSS
the following is the code snippet for the same
// code for map.component.ts
import { Component, OnInit } from '#angular/core';
import * as mapboxgl from 'mapbox-gl';
import { MapService } from '../map.service';
import { GeoJson, FeatureCollection } from '../map';
#Component({
selector: 'app-map-box',
templateUrl: './map-box.component.html',
styleUrls: ['./map-box.component.css']
})
export class MapBoxComponent implements OnInit{
/// default settings
map: mapboxgl.Map;
style = 'mapbox://styles/kanavmalik10/cjfbjx6fp70fl2snuphc7zjw2';
lat = 37.75;
lng = -122.41;
message = 'Hello World!';
// data
source: any;
markers: any;
constructor(private mapService: MapService) {
}
ngOnInit() {
this.markers = this.mapService.getMarkers()
this.initializeMap()
}
private initializeMap() {
/// locate the user
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
this.lat = position.coords.latitude;
this.lng = position.coords.longitude;
this.map.flyTo({
center: [this.lng, this.lat]
})
});
}
this.buildMap()
}
buildMap() {
this.map = new mapboxgl.Map({
container: 'map',
style: this.style,
zoom: 13,
center: [this.lng, this.lat]
});
/// Add map controls
this.map.addControl(new mapboxgl.NavigationControl());
//// Add Marker on Click
this.map.on('click', (event) => {
const coordinates = [event.lngLat.lng, event.lngLat.lat]
const newMarker = new GeoJson(coordinates, { message: this.message })
this.mapService.createMarker(newMarker)
})
/// Add realtime firebase data on map load
this.map.on('load', (event) => {
/// register source
this.map.addSource('firebase', {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: []
}
});
/// get source
this.source = this.map.getSource('firebase')
/// subscribe to realtime database and set data source
this.markers.subscribe(markers => {
let data = new FeatureCollection(markers)
this.source.setData(data)
})
/// create map layers with realtime data
this.map.addLayer({
id: 'firebase',
source: 'firebase',
type: 'symbol',
layout: {
'text-field': '{message}',
'text-size': 24,
'text-transform': 'uppercase',
'icon-image': 'rocket-15',
'text-offset': [0, 1.5]
},
paint: {
'text-color': '#f16624',
'text-halo-color': '#fff',
'text-halo-width': 2
}
})
})
}
/// Helpers
removeMarker(marker) {
this.mapService.removeMarker(marker.$key)
}
flyTo(data: GeoJson) {
this.map.flyTo({
center: data.geometry.coordinates
})
}
}
<input type="text" [(ngModel)]="message" placeholder="your message...">
<h1>Markers</h1>
<div *ngFor="let marker of markers | async">
<button (click)="flyTo(marker)">{{ marker.properties.message }}</button>
<button (click)="removeMarker(marker)">Delete</button>
</div>
<div class="map" id="map"></div>
You seed to include the GL JS CSS stylesheet. See the quickstart at https://docs.mapbox.com/mapbox-gl-js/overview/#quickstart
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.45.0/mapbox-gl.css' rel='stylesheet' />
Hi all I am using the googles maps nodejs client web api and would like to display a map on my HTMLviews through AngularJS 2.
I have this server export that returns an object to my AngularJS2 client service
const googleMapsClient = require('#google/maps').createClient({
key: 'AIzaSyCYcyd0vCGRY6Pq5E0u_ECTFi4I9VmUE4o'
});
module.exports = (req, res) => {
googleMapsClient.geocode({
address: 'Cosmo City, Roodepoort USA street'
}, function(err,response) {
if(err) {
console.log("There was an error geocoding the address", err)
} else {
console.log("Here is the maps response", response.json.results)
var obj = {
name: "Thabo",
age: 23,
maps: response.json.results
};
res.json({obj});
}
});
}
The Angular2 services looks like this
#Injectable()
export class MyService {
constructor(private http: Http) { }
getMessage(): Promise<mma> {
return this.http.get('/map-moving-agents')
.toPromise()
.then((res)=> {
console.dir(res.json().maps);
return res.json().obj;
})
.catch(this.handleError);
}
Everything seems to be fine, I get the expected response from the server, now i would like to use this response to draw a map on my component template.
And then here is my AngularJS2 component
#Component({
moduleId:module.id,
selector: 'map-moving-agents',
templateUrl: 'moving-agents.html',
styleUrls: ['moving-agents.css'],
providers: [ MyService ]
})
export class MapMovingAgents implements OnInit{
msg : mma;
constructor(private myService: MyService ){}
getMessage(): void {
this.myService.getMessage().then((res) => {
this.msg = res;
console.log(this.msg.name);
})
}
ngOnInit(): void {
this.getMessage();
}
}
I have used the angular2-google-maps package, i now have this In my component class
export class MapMovingAgents implements OnInit{
map: any;
lat: number;
lng: number;
zoom: number = 18;
constructor(private myService: MyService ){}
getMessage(): void {
this.myService.getMessage().then((res) => {
this.map = res;
this.lat = this.map.maps[0].geometry.location.lat;
this.lng = this.map.maps[0].geometry.location.lng;
console.log(this.lat,this.lng);
})
}
And have this in my tempate
<sebm-google-map [latitude]="lat" [longitude]="lng" [zoom]="zoom">
<sebm-google-map-marker [latitude]="lat" [longitude]="lng"></sebm-google- map-marker>
</sebm-google-map>
I have also updated my app module by importing the module and passed it the api key
import { AgmCoreModule } from 'angular2-google-maps/core';
imports: [... AgmCoreModule.forRoot({
apiKey: 'AIzMSNPY'
})...]
You can read through the angular2-google-maps here
I followed the this example (click here) to make a field of address with autocompletion of google map Places,
But it's giving the following error:
Can not find name 'google'.
L53: this.mapsAPILoader.load (). Then (() => {
L54: let autocomplete = new google.maps.places.Autocomplete
(this.searchElementRef.nativeElement, {
I tried to install google-maps types npm install --save #types/google-maps but it is without results.
After installing #types/google-maps the build is ok but when I luanch i have this error :
Cannot find name 'google' after installing #types/google-maps
My Code :
import { FormControl } from '#angular/forms';
import { Component, ViewChild, OnInit, ElementRef } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { MapsAPILoader } from 'angular2-google-maps/core';
#Component({
selector: 'page-page2',
templateUrl: 'page2.html'
})
export class Page2 implements OnInit {
latitude: number = 51.678418;
longitude: number = 7.809007;
zoom: number = 4;
searchControl: FormControl;
#ViewChild("search")
searchElementRef: ElementRef;
constructor(public navCtrl: NavController, public navParams: NavParams, private mapsAPILoader: MapsAPILoader) {
// some not related to this question code
}
ngOnInit() {
//create search FormControl
this.searchControl = new FormControl();
//set current position
this.setCurrentPosition();
//load Places Autocomplete
this.mapsAPILoader.load().then(() => {
let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
types: ["address"]
});
autocomplete.addListener("place_changed", () => {
//get the place result
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
//set latitude and longitude
this.latitude = place.geometry.location.lat();
this.longitude = place.geometry.location.lng();
});
});
}
private setCurrentPosition() {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
this.zoom = 12;
});
}
}
}
Run typings install dt~google.maps --global
as found here
I want to use GoogleMapAPI auto-complete in angularjs2 and onsenUI2, but I can't do that.
This is my code:
import { Component, NgModule, OnInit, ViewChild, ElementRef } from '#angular/core';
import { FormControl, FormsModule, ReactiveFormsModule } from "#angular/forms";
import { BrowserModule } from "#angular/platform-browser";
import { AgmCoreModule, MapsAPILoader } from 'angular2-google-maps/core';
// import {GoogleplaceDirective} from '../googleplace.directive';
import {NgModel} from '#angular/forms';
#Component({
selector: 'app-root',
styles: [`
.sebm-google-map-container {
height: 300px;
}
`],
template: `
<google-search-bar></google-search-bar>
<div class="container">
<div class="form-group">
<input placeholder="search for location" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="form-control" #search [formControl]="searchControl">
</div>
<sebm-google-map [latitude]="latitude" [longitude]="longitude" [scrollwheel]="false" [zoom]="zoom">
<sebm-google-map-marker [latitude]="latitude" [longitude]="longitude"></sebm-google-map-marker>
</sebm-google-map>
</div>
`})
export class GoogleMap implements OnInit {
public latitude: number;
public longitude: number;
public searchControl: FormControl;
public zoom: number;
public fuzzyControl: FormControl;
public address:string;
#ViewChild("search")
public searchElementRef: ElementRef;
constructor(
private mapsAPILoader: MapsAPILoader
) {}
ngOnInit() {
//set google maps defaults
this.zoom = 4;
this.latitude = 39.8282;
this.longitude = -98.5795;
//create search FormControl
this.searchControl = new FormControl();
this.fuzzyControl = new FormControl();
//set current position
this.setCurrentPosition();
this.setMapsAPILoader();
//load Places Autocomplete
this.mapsAPILoader.load().then(() => {
let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
types: ["address"]
});
autocomplete.addListener("place_changed", () => {
//get the place result
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
//set latitude and longitude
this.latitude = place.geometry.location.lat();
this.longitude = place.geometry.location.lng();
});
});
}
private setCurrentPosition() {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
this.zoom = 12;
});
}
}
This is Error
Unhandled Promise rejection: Cannot read property 'Autocomplete' of undefined ; Zone: angular ; Task: Promise.then ; Value: TypeError: Cannot read property 'Autocomplete' of undefined(…) TypeError: Cannot read property 'Autocomplete' of undefined
I have been been stuck on this same exact error with code that is very similar to yours.
I am only using the auto complete part of the code (no map display but my input call is the exact same as yours) so I can't completely verify this but the error seems to be caused by this in the input statement:
"#search [formControl]="searchControl"
Looking at this article I noticed how they used an id call within the input: angular2-google-maps autocomplete not working
So I removed that part of my input statement. It should look like this:
<input id="address" placeholder="search for location" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="form-control">
And used javascript in my auto complete look look for that the id:
this.mapsAPILoader.load().then(() => {
let autocomplete = new google.maps.places.Autocomplete(
<HTMLInputElement>document.getElementById("address"), {
types: ['address']
});
autocomplete.addListener('place_changed', () => {
this.ngZone.run(() => {
// get the place result
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
// add map calls here
});
});
});
After changing that, the error disappears and auto-complete works as hoped. Hope this works for you.
One other thing to check is that you imported your API Key into the correct component. See the article above for reference.
My location with longitude and latitude is working but I need to make a pointer over there, is it possible? I am using NativeScript, Angular2 and NativeScript plugin for Google Maps SDK (nativescript-google-sdk)
file.ts
import { registerElement } from 'nativescript-angular/element-registry';
registerElement("MapView", () => require("nativescript-google-maps-sdk").MapView);
file.xml
<MapView [latitude]="configService.unitPreview.latitude" [longitude]="configService.unitPreview.longitude"
zoom="17" bearing="0"
tilt="0" (mapReady)="OnMapReady"
(markerSelect)="onMarkerSelect"
(cameraChanged)="onCameraChanged">
</MapView>
map_without_pointer
map_with_pointer
You could use addMarker method to add Markers in the map. You could review my example below, where have been shown, how to do that.
app,component.html
<GridLayout>
<MapView (mapReady)="onMapReady($event)" ></MapView>
</GridLayout>
app.com-ponent.ts
import {Component, ElementRef, ViewChild} from '#angular/core';
var mapsModule = require("nativescript-google-maps-sdk");
#Component({
selector: "my-app",
templateUrl: "app.component.html",
})
export class AppComponent {
#ViewChild("MapView") mapView: ElementRef;
constructor(){
}
//Map events
onMapReady = (event) => {
console.log("Map Ready");
var map =event.object;
var marker = new mapsModule.Marker();
marker.position = mapsModule.Position.positionFromLatLng(48.87, 2.35);
marker.title = "Sydney";
marker.snippet = "Australia";
marker.userData = { index : 1};
map.addMarker(marker);
};
}
It is possible show the real traffic like image bellow?
traffic_real_time.png