1

How would I go about getting the latitude and longitude from an address?

My current method is passing the address to the google maps api:

getLocationJson(term: string) {
    var term = "Mechelsesteenweg+64";
   return this._http.get('https://maps.googleapis.com/maps/api/geocode/json?address=Someroad+64&key=AIzkeystuffjXDm6eU5mPP9Nczg')
   .subscribe((json: any) => {
        var obj = JSON.parse(json);
        var jsonParsed = obj["results"];
    });
}

But I feel like this is not the correct way. Can I use geocoder for this? Something like:

getGeoLocation(address: string) {
    let geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          var latlng = google.maps.location.LatLng();
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}

Thanks in advance. (It's basically this question but reversed)

DGK
  • 2,947
  • 5
  • 32
  • 47

1 Answers1

6

I answered that question you linked, here is the method that worked for me:

getGeoLocation(address: string): Observable<any> {
    console.log('Getting address: ', address);
    let geocoder = new google.maps.Geocode();
    return Observable.create(observer => {
        geocoder.geocode({
            'address': address
        }, (results, status) => {
            if (status == google.maps.GeocoderStatus.OK) {
                observer.next(results[0].geometry.location);
                observer.complete();
            } else {
                console.log('Error: ', results, ' & Status: ', status);
                observer.error();
            }
        });
    });
}
Milo
  • 3,365
  • 9
  • 30
  • 44
  • Could you post your imports/google var? It either throws a nullpointer on the google var or when I add the googlemapsapi script to the index.html it'll say that geocode is not a constructor. – DGK May 31 '17 at 07:23
  • 1
    @woodsprite check out my maps project on github (https://github.com/Milan03/angular2-google-maps-sandbox) and you can poke around the code all you like. – Milo May 31 '17 at 11:40
  • I still can't pinpoint why my code didn't work but your project really helped. Thanks! – DGK May 31 '17 at 13:53
  • @woodsprite :) To answer your question on imports/google var, if you are using Angular CLI you may need to explicitly import google typings: `npm install --save-dev @types/googlemaps` and then -> `import {} from '@types/googlemaps';` – Milo May 31 '17 at 17:30