从谷歌地图API中获取latlng地址

问题描述:

我该如何去获取地址的经度和纬度?从谷歌地图API中获取latlng地址

我目前的方法传递地址到谷歌地图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但相反)

我回答你挂这个问题,这里是为我工作的方法:

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

你能发表您的进口/谷歌变种?它会在google var上抛出一个空指针,或者当我将googlemapsapi脚本添加到index.html时,它会说geocode不是构造函数。 – Laurens

+0

@woodsprite在github上查看我的地图项目(https://github.com/Milan03/angular2-google-maps-sandbox),你可以在代码中搜索所有你喜欢的东西。 – Milo

+0

我仍然无法确定为什么我的代码无法正常工作,但是您的项目确实有所帮助。谢谢! – Laurens