我正在尝试将Google Maps集成到我正在开发的应用程序中,但迄今为止我做得并不顺利。不过,最终我成功地显示了一个SupportMapFragment地图,并设置了位置和缩放级别。
以下是我代码中的功能部分:
@Override
public void onActivityCreated( Bundle savedInstanceState ) {
super.onActivityCreated( savedInstanceState );
Location location = BundleChecker.getExtraOrThrow( KEY_LOCATION, new Bundle[] { savedInstanceState, getArguments() } );
setLocation( location );
if ( checkGooglePlayServicesStatus() == ConnectionResult.SUCCESS ) {
setMapFragment( new SupportMapFragment() );
getActivity().getSupportFragmentManager().beginTransaction().add( R.id.location_detail_mapFrame, getMapFragment() ).commit();
}
populateAddress();
attachButtonListeners();
Runnable initMap = new Runnable() {
@Override
public void run() {
if ( checkGooglePlayServicesStatus() == ConnectionResult.SUCCESS ) {
try {
GoogleMap map = getMapFragment().getMap();
LatLng latLng = getLocation().getAddress().getLatLng( getActivity() );
CameraUpdate update = CameraUpdateFactory.newLatLngZoom( latLng, DEFAULT_MAP_ZOOM );
map.animateCamera( update );
}
catch (IOException e) {
Log.e( TAG, e.getMessage(), e );
Toast.makeText( getActivity(), "Unable to find location", Toast.LENGTH_SHORT ).show();
}
}
}
};
Handler handler = new Handler();
handler.postDelayed( initMap, 200 );
}
此外,我编写了一个简单的方便方法来从我的地址模型中获取一个LatLng,您也可以对其进行批评:
/*
* Convenience method to easily check if there is a valid lat & lng in this address
*/
public boolean hasLatLng() {
return getLatitude() != null && getLongitude() != null;
}
/*
* Convenience method for use with Google Maps API
*/
public LatLng getLatLng( Context context ) throws IOException {
LatLng latLng = null;
if ( hasLatLng() ) {
latLng = new LatLng( getLatitude(), getLongitude() );
}
else {
String locationString = getStreet() + ", " + AddressUtil.makeCityStateZipString( this );
Geocoder geoCoder = new Geocoder( context );
try {
List<android.location.Address> matches = geoCoder.getFromLocationName( locationString, 2 );
if ( matches != null && matches.size() > 0 ) {
double lat = matches.get( 0 ).getLatitude();
double lng = matches.get( 0 ).getLongitude();
latLng = new LatLng( lat, lng );
}
}
catch (IOException e) {
throw new IOException( e );
}
}
return latLng;
}
我知道这段代码不太理想,需要进行重构。这是我第一次使用Google Maps,所以如果您有任何建议,请随时提出。当我试图将MapFragment作为我的布局XML的标签使用时,遇到了很多问题,所以我现在正在以编程方式创建它。
问题的核心:
我从分段服务器获取了一些虚假的地址数据,这导致Address#getLatLng方法返回null,在调用CameraUpdateFactory.newLatLngZoom时引发异常。在遇到此异常后,我无法再从Google获取地图数据。现在地图片段是空白的,logcat中显示消息:
05-21 18:11:42.903: I/Google Maps Android API(15747): Failed to contact Google servers. Another attempt will be made when connectivity is established.
05-21 18:11:43.093: E/Google Maps Android API(15747): Failed to load map. Error contacting Google servers. This is probably an authentication issue (but could be due to network errors).
我已经创建了一个新的API密钥,并在清单中替换了当前的API密钥,但没有任何更改。我对上述代码做的唯一更改是处理了null LatLng,但我已经撤消了这些更改,无济于事,试图将代码恢复到可用状态。
另外,更奇怪的是,我构建了包含在Google Play服务Extra中的示例地图项目,它完美地工作(顺便说一下,有一个单独的API密钥)。
我可能做错了什么?是否忽略了明显的问题?