从google maps api中的地址获取latlng

时间:2017-05-29 13:57:54

标签: angular typescript google-maps-api-3

我如何从地址获取纬度和经度?

我目前的方法是将地址传递给google maps api:

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);
        }
    });
}

但我觉得这不是正确的方法。我可以使用地理编码器吗?类似的东西:

{{1}}

提前致谢。 (它基本上是this question但反过来了)

1 个答案:

答案 0 :(得分:2)

我回答了你链接的问题,这是适用于我的方法:

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();
            }
        });
    });
}