Reputation: 3015
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)
Upvotes: 1
Views: 11478
Reputation: 3453
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();
}
});
});
}
Upvotes: 6