【问题标题】:Get latlng from address in google maps api从google maps api中的地址获取latlng
【发布时间】:2017-05-29 13:57:53
【问题描述】:

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

我当前的方法是将地址传递给 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"];
    });
}

但我觉得这不是正确的方法。我可以为此使用地理编码器吗?比如:

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 你能发布你的导入/谷歌变量吗?它要么在 google var 上抛出一个空指针,要么当我将 googlemapsapi 脚本添加到 index.html 时,它会说 geocode 不是构造函数。
    • @woodsprite 查看我在 github (github.com/Milan03/angular2-google-maps-sandbox) 上的地图项目,您可以随意浏览代码。
    • 我仍然无法确定为什么我的代码不起作用,但您的项目确实有帮助。谢谢!
    • @woodsprite :) 要回答您关于导入/google var 的问题,如果您使用 Angular CLI,您可能需要显式导入 google 类型:npm install --save-dev @types/googlemaps,然后 -> import {} from '@types/googlemaps';
    猜你喜欢
    • 1970-01-01
    • 2011-07-31
    • 2011-04-25
    • 2012-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 2016-08-21
    相关资源
    最近更新 更多