angular-google-maps icon indicating copy to clipboard operation
angular-google-maps copied to clipboard

Using Geocoder with GoogleMapsAPIWrapper

Open RedFour opened this issue 10 years ago • 42 comments

I saw in issue #139 you are providing the ability to access google.maps object via the getMap() function, which I assume is now the getNativeMap() function in GoogleMapsAPIWrapper. I've also read that other people have gotten it to work, but I can't find any documentation or examples on how to use the GoogleMapsAPIWrapper and Geocoder.

import { Component, OnInit } from '@angular/core';
import { LocationService } from '../../core/location.service';
import { GoogleMapsAPIWrapper } from 'angular2-google-maps/core';

declare var google: any;

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  constructor(private wrapper: GoogleMapsAPIWrapper) {
    this.wrapper.getNativeMap().then((m) => {
      console.log("test");
    });

  }

  ngOnInit() {
    // var address = "1045 mission street san francisco";

    // var geocoder = new google.maps.Geocoder();

    // var result = "";

    // geocoder.geocode({ 'address': address }, (results, status) => {
    //   var latitude = results[0].geometry.location.lat();
    //   var longitude = results[0].geometry.location.lng();
    //   console.log("lat: " + latitude + ", long: " + longitude);
    // });
  }
}

Right now I can't even get the console.log to print out "test". I'm not sure why. Also would the m variable be the equivalent of google.maps? So that I can then use m.Geocoder()?

I'm also not sure if I'm importing the GoogleMapsAPIWrapper correctly. Currently I'm importing it in the core.module, since the Angular 2 guidelines say to have services be in the core.module. "sebm-google-map" works for me without any issues, so I think the AgmCoreModule is imported correctly, I'm just not sure about how to use GoogleMapsAPIWrapper.

import {
    ModuleWithProviders, NgModule,
    Optional, SkipSelf
} from '@angular/core';

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


import { FirebaseService, FirebaseServiceConfig } from './firebase.service';
import { LocationService } from './location.service';


@NgModule({
    imports: [AgmCoreModule.forRoot({apiKey: "blahblahapikey"}),],
    declarations: [],
    exports: [AgmCoreModule],
    providers: [FirebaseService, LocationService, GoogleMapsAPIWrapper]
})
export class CoreModule {

    constructor( @Optional() @SkipSelf() parentModule: CoreModule) {
        if (parentModule) {
            throw new Error(
                'CoreModule is already loaded. Import it in the AppModule only');
        }
    }

    static forRoot(config: FirebaseServiceConfig): ModuleWithProviders {
        return {
            ngModule: CoreModule,
            providers: [
                { provide: FirebaseServiceConfig, useValue: config }
            ]
        };
    }
}

I've been able to get google.maps.Geocoder() to work via GMap from PrimeNG, but sometimes I get google is not defined errors. So I'm trying to use Sebastian's google map instead.

RedFour avatar Oct 01 '16 17:10 RedFour

If you just need Geocoder(), you don't need to use getNativeMap().

I'm importing MapsAPILoader, so I can use it this way :

this.mapsAPILoader.load().then(() => {
    console.log('google script loaded');
    var geocoder = new google.maps.Geocoder();
});

But if you want to get the native map, you TestComponent must be loaded inside the google map component :

<sebm-google-map [latitude]="lat" [longitude]="lng">
    <app-test></app-test>
</sebm-google-map>

and you have to be sure that your instance of GoogleMapsAPIWrapper inside TestComponent is the same instance used by SebmGoogleMap

gnujeremie avatar Oct 02 '16 13:10 gnujeremie

@gnujeremie thx for the tip to use MapsAPILoader. How do I go about importing it? Did you import it along with AgmCoreModule?

RedFour avatar Oct 03 '16 00:10 RedFour

No, AgmCoreModule is imported only in my module using google map. I directly import import { MapsAPILoader } from 'angular2-google-maps/core'; in my service.

gnujeremie avatar Oct 03 '16 08:10 gnujeremie

How about this -


import { Injectable, NgZone } from '@angular/core';
import { GoogleMapsAPIWrapper } from 'angular2-google-maps/core';
import { MapsAPILoader } from 'angular2-google-maps/core';
import { Observable, Observer } from 'rxjs';

declare var google: any;

@Injectable()
export class GMapsService extends GoogleMapsAPIWrapper{ 
    constructor(private __loader: MapsAPILoader, private __zone: NgZone) {
        super(__loader, __zone);
    }

    getLatLan(address: string) {
        console.log('Getting Address - ', address);
        let geocoder = new google.maps.Geocoder();
        return Observable.create(observer => {
            geocoder.geocode( { 'address': address}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    observer.next(results[0].geometry.location);
                    observer.complete();
                } else {
                    console.log('Error - ', results, ' & Status - ', status);
                    observer.next({});
                    observer.complete();
                }
            });
        })
    }
}

vintesh avatar Oct 10 '16 16:10 vintesh

In addition to the solution presented by @vintesh I had to update the lat and lng inside the NgZone to update the map.

clickSearchAddress() {
        this._mapsService.getLatLan(this.model.address)
            .subscribe(
            result => {
                // needs to run inside zone to update the map
                this._zone.run(() => {
                    this.model.lat = result.lat();
                    this.model.lng = result.lng();
                });
            },
            error => console.log(error),
            () => console.log('Geocoding completed!')
            );
    }

FabioBentoLuiz avatar Dec 09 '16 20:12 FabioBentoLuiz

I still run into problems when trying to use the geocoder. Here's my code.

import { MapsAPILoader } from 'angular2-google-maps/core';
constructor(public mapsApiLoader: MapsAPILoader) {
    this.mapsApiLoader.load().then(() => {
      console.log('google script loaded');
      this.geocoder = new google.maps.Geocoder();
      console.log(this.geocoder);
    });

I get two errors:

Cannot find name 'google'. and rollup failed: 'MapsAPILoader' is not exported by node_modules/angular2-google-maps/core/index.js (imported by src/services/location.ts). For help fixing this error see https://github.com/rollup/rollup/wiki/Troubleshooting#name-is-not-exported-by-module

slooker avatar Jan 04 '17 14:01 slooker

@slooker you need to add declare var google: any; before the declaration of your constructor.

gnujeremie avatar Jan 04 '17 14:01 gnujeremie

@gnujeremie That solves the google undefined problem, but it still tells me that MapsAPILoader isn't exported by angular2-google-maps.

slooker avatar Jan 04 '17 14:01 slooker

@slooker I too faced the same issue and MapsAPILoader error is coming because "node_modules/angular2-google-maps/core/index.js" do not export MapsAPILoader .I have solved this issue. Insert following code in "node_modules/angular2-google-maps/core/index.js" file as follows :

var core_module_2 = require('./core.umd'); exports.MapsAPILoader = core_module_2.MapsAPILoader;

This works for me. Hope this will work for you also.

kumar-ravi007 avatar Jan 25 '17 07:01 kumar-ravi007

Do you guys have a working version? I get my addresses from a database and I need their coordinates in order to build a marker cluster. GeoCoder is defined in the constructor but is not accessible via the nginit method.

DoubleExposure avatar Jun 06 '17 17:06 DoubleExposure

VinTesh, why does the service you listed say that google is undefined? What is the proper way tos et this up? Thanks

DoubleExposure avatar Jun 07 '17 13:06 DoubleExposure

I'm facing the same google undefined problem. Any suggestions?

I'm using "@agm/core": "^1.0.0-beta.0"

Thanks

nichovski avatar Jun 17 '17 18:06 nichovski

getCurrentPositionSuccessCallBack(position: Position) {
    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;

    const latLng: LatLngLiteral = {
      lat: latitude,
      lng: longitude
    };

    const geoCoder = new google.maps.Geocoder();

    geoCoder.geocode({ "location": latLng }, (results, status) => {

is my code and it works fine, but I am trying to write a unit test

fit('onGeoLocate should set the right location', () => {

    spyOn(navigator.geolocation, 'getCurrentPosition').and.callFake(function () {
      const position = { coords: { latitude: 32, longitude: -96 } };
      arguments[0](position);
    });
    component.onGeoLocate();

but it fails with

 Failed: google is not defined

Help please?

daBishMan avatar Jun 19 '17 20:06 daBishMan

Hello "google undefined" friends. Did you try the tip of our colleague @gnujeremie? This is working for me (Angular 2.2.3):

import { Injectable } from '@angular/core';
import { MapsAPILoader } from 'angular2-google-maps/core';
import { Observable } from 'rxjs/Observable';

declare var google: any;

@Injectable()
export class MapsService {
    constructor(private __loader: MapsAPILoader) {

    }

    getGeocoding(address: string) {
        return Observable.create(observer => {
            try {
                //at this point the variable google may be still undefined (google maps scripts still loading)
                //so load all the scripts, then...
                this.__loader.load().then(() => {
                    let geocoder = new google.maps.Geocoder();
                    geocoder.geocode({ address }, (results, status) => {

                        if (status === google.maps.GeocoderStatus.OK) {
                            const place = results[0].geometry.location;
                            observer.next(place);
                            observer.complete();
                        } else {
                            console.error('Error - ', results, ' & Status - ', status);
                            if (status === google.maps.GeocoderStatus.ZERO_RESULTS) {
                                observer.error('Address not found!');
                            }else {
                                observer.error(status);
                            }
                            
                            observer.complete();
                        }
                    });
                });
            } catch (error) {
                observer.error('error getGeocoding' + error);
                observer.complete();
            }

        });
    }
}

FabioBentoLuiz avatar Jun 22 '17 20:06 FabioBentoLuiz

Fabio, can you provide a sample of how this is called and used?

DoubleExposure avatar Jun 23 '17 14:06 DoubleExposure

@DoubleExposure assuming you have a constructor like this

constructor(private ms: MapsService) { }

you can call this in your code

this.ms.getGeocoding( '10 10th Street NE, Atlanta, GA 30309' ).subscribe(function (x) { console.log(x.toString()); });

neilpennell avatar Jul 23 '17 14:07 neilpennell

@FabioBentoLuiz @gnujeremie Hi 've tried your code and it's working great. Except the first call which allways fail. I've tried to make a first call in an ngOnInit but it does not seems to work.

Here my usage attempt

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router, ActivatedRoute, ParamMap} from '@angular/router';

import 'rxjs/add/operator/switchMap';
import { Observable } from 'rxjs/Observable';

import { Place } from './../place';
import { PlaceService } from './../place.service';
import { MapsService } from './map.service';
import { AlertService } from './../AlertComponent/alert.service';


@Component({
  selector: 'app-detailview',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.css'], 
})


export class DetailComponent implements OnInit {

	place: Place;  
	lat: number = 51.678418;
  	lng: number = 7.809007;

	ngOnInit() {
		let selectedId = this.route.paramMap.subscribe(
				(params: ParamMap)  =>	this.place = this.placeService.getPlaceById(+params.get('id'))
			);
		this.maps.getGeocoding('')
            .subscribe(
            result => console.log(result),
            error => console.log(error),
            () => console.log('Geocoding completed!')
            );
	}

	constructor(private placeService: PlaceService,
				private route       : ActivatedRoute,
				private location    : Location,
				private alert       : AlertService,
				private maps        : MapsService) {
	}

	clickSearchAddress() {
		let address = this.place.name + " " + this.place.address + " " + this.place.city + " " + this.place.postalCode;
        this.maps.getGeocoding(address)
            .subscribe(
            result => {
                    this.lat = result.lat();
                    this.lng = result.lng();
            },
            error => console.log(error),
            () => console.log('Geocoding completed!')
            );
    }

	back(){
		this.location.back();
	}

Canadadry avatar Oct 27 '17 13:10 Canadadry

Hi @Canadadry , How the first call fails? Are you using the MapsAPILoader?

FabioBentoLuiz avatar Oct 27 '17 13:10 FabioBentoLuiz

My map is supposed to center on the address. So I have mapped the clickSearchAddress() on a button and It only moves the map on the second click. On the first click I only have the log : Geocoding completed! Stranger thing, I have put the clickSearchAddress() call on the subscribe of route.paramMapin ngOnInit and there the function work on the first call.

I have tried waiting before starting to click to be sure google map script are loaded but it still require two clics.

The MapsService used is the one you provide.

Canadadry avatar Oct 27 '17 14:10 Canadadry

Try it using NgZone as described here

import { NgZone } from '@angular/core';

Add to your constructor

constructor(private _zone: NgZone){
}

Then set lat and lng like this:

this.maps.getGeocoding(address)
            .subscribe(
            result => {
                    this._zone.run(() => {
                    this.lat = result.lat();
                    this.lng = result.lng();
            });
                    
            },
            error => console.log(error),
            () => console.log('Geocoding completed!')
            );

Here is another thread that explain the reason of it.

Let me know if it works.

FabioBentoLuiz avatar Oct 28 '17 09:10 FabioBentoLuiz