How to get the country from a coordinate (longitude, altitude) with angular2-google-maps?

1.2k views Asked by At

I want to know if possible get the country code or the country from a location (logitude and latitude), using the angular2-google-maps library.

 private setCurrentPosition() {
    if ("geolocation" in navigator) {
      navigator.geolocation.getCurrentPosition((position) => {
        this.latitude = position.coords.latitude;
        this.longitude = position.coords.longitude;
        this.zoom = 12;
      });
    }
  }

Plunker

1

There are 1 answers

0
Milo On

You have to reverse geocode to get that kind of information

map.service.ts

getRevGeoLocation(lat: number, lng: number): Observable<google.maps.GeocoderResult> {
    if (navigator.geolocation) {
        let geocoder = new google.maps.Geocoder();
        let latlng = new google.maps.LatLng(lat, lng);
        let request = {
            latLng: latlng
        };
        return Observable.create(observer => {
            geocoder.geocode(request, (results, status) => {
                if (status == google.maps.GeocoderStatus.OK) {
                    console.log(results[0]);
                    observer.next(results[0])
                    observer.complete();
                } else {
                    console.log('Error: ', results, ' & Status: ', status);
                    observer.error();
                }
            });
        });
    }
}

map.component.ts

callRevGeoLocate(lat: number, lng: number) {
    this._mapsService.getRevGeoLocation(lat, lng).subscribe(
        results => {
            this._zone.run(() => {
                this.fillInputs(results.formatted_address);
            });
        }
    );

fillInputs(formatted_address: string) {
    let addrElements = formatted_address.split(",");
    let provPostalCode = addrElements[2].split(" ");
    this.marker.draggable = true;
    this.marker.label = formatted_address;
    this.marker.buildingNum = addrElements[0].substr(0, addrElements[0].indexOf(' '));
    this.marker.streetName = addrElements[0].substr(addrElements[0].indexOf(' ') + 1);
    this.marker.city = addrElements[1].trim();
    this.marker.region = provPostalCode[1];
    if (provPostalCode.length == 4)
        this.marker.postalCode = provPostalCode[2] + provPostalCode[3];
    else if (provPostalCode.length == 3)
        this.marker.postalCode = provPostalCode[2];
    else
        this.marker.postalCode = "";
}

There may be better ways but this is how I got mine working.