我正在使用谷歌地图api v2 for android。 这是我的片段类代码 的 mapview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mySwitch="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rlmain"
android:background="@drawable/mainbg" >
<include
android:id="@+id/rlheader"
android:layout_alignParentTop="true"
layout="@layout/header" >
</include>
<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/rlheader"
class="com.google.android.gms.maps.SupportMapFragment"
/>
</RelativeLayout>
MapViewFragment
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapViewFragment extends BaseFragment{
private RelativeLayout ll;
ImageButton ivbtShopList,ivbtSearch;
TextView tvHeader;
private LocationManager locationManager;
private String provider;
Location location;
ThreadPreLoader mTask;
Handler mHandler;
ArrayList<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>();
ArrayList<DataOfPlaceList> Placelist=new ArrayList<DataOfPlaceList>();
HashMap<String,DataOfPlaceList> Placelistdata=new HashMap<String,DataOfPlaceList>();
DataOfPlaceList data;
JSONArray jsonArray;
JSONObject jsonObject;
String APILink,Jsonstring;
String TAG="NearByShop";
Button btBack;
private GoogleMap mMap;
Boolean Successfull=false,isDestory=false;
TextView tv5kmRecord,tv10kmRecord,tvAllRecord;
int maptype;
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
PlaceListProgressHolder.initHolder(getActivity(), "Loading...");
Jsonstring=(String) getArguments().get("jsonresponse");
maptype=mPrefs.getInt("maptype", 0);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(readyToGo()){
if (ll == null) {
ll = (RelativeLayout)inflater.inflate(R.layout.mapview, container, false);
tvHeader=(TextView)ll.findViewById(R.id.tvHeaderTitle);
tvHeader.setTypeface(tf);
btBack=(Button)ll.findViewById(R.id.btBack);
btBack.setVisibility(View.VISIBLE);
btBack.setOnClickListener(OnBackClickListener);
setUpMapIfNeeded();
if(((TABActivity)mActivity).checkConnection()){
mTask = new ThreadPreLoader(PlaceListProgressHolder);
mTask.execute();
mHandler = new Handler(Looper.getMainLooper());
}
Log.e("remove","noremove");
} else {
((ViewGroup) ll.getParent()).removeView(ll);
Log.e("remove","yesremove");
}
}else{
return null;
}
return ll;
}
private OnClickListener OnBackClickListener=new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
isDestory=true;
((TABActivity)mActivity).onBackPressed();
}
};
@Override
public void onResume() {
super.onResume();
if (ll == null) {
tvHeader.setText(getResources().getString(R.string.search));
btBack.setText(getActivity().getResources().getString(R.string.back));
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
switch(maptype){
case 0:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case 1:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case 2:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
}
mMap.setInfoWindowAdapter(new InfoWindowAdapter() {
// Use default InfoWindow frame
@Override
public View getInfoWindow(Marker arg0) {
return null;
}
// Defines the contents of the InfoWindow
@Override
public View getInfoContents(Marker arg0) {
// Getting view from the layout file info_window_layout
View v = getActivity().getLayoutInflater().inflate(R.layout.mapinfowindow, null);
return v;
}
});
if(location!=null){
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(latLng);
mMap.animateCamera(cameraUpdate);
}
mMap.animateCamera(CameraUpdateFactory.zoomBy(8));
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener(){
@Override
public void onInfoWindowClick(Marker marker) {
// TODO Auto-generated method stub
PlaceDetailsFragment fragment=new PlaceDetailsFragment();
Bundle bundle=new Bundle();
bundle.putString("placeid",""+Placelistdata.get(marker.getId()).getPlaceid());
fragment.setArguments(bundle);
((TABActivity)mActivity).pushFragments(AppConfig.TAB_B,fragment,true,true);
}
});
}
}
private ProgressHolder PlaceListProgressHolder = new ProgressHolder() {
@Override
public boolean getMessagelist() {
// TODO Auto-generated method stub
try{
Placelist.clear();
jsonObject=new JSONObject(Jsonstring);
Successfull=jsonObject.getBoolean("successfull");
if(Successfull){
jsonArray=jsonObject.getJSONArray("Place");
for(int i=0;i<jsonArray.length();i++){
jsonObject=jsonArray.getJSONObject(i);
data=new DataOfPlaceList();
data.setPlaceid(jsonObject.getString("place_id"));
data.setPlacename(jsonObject.getString("placename"));
data.setFacility(jsonObject.optString("facility"));
data.setLatitude(jsonObject.getDouble("latitude"));
data.setLongitude(jsonObject.getDouble("longitude"));
data.setDistance(jsonObject.optDouble("distance"));
Placelist.add(data);
}
}
}catch(Exception e){
Log.e(TAG,e.toString());
return false;
}
return true;
}
@Override
public void updateContent() {
// TODO Auto-generated method stub
mHandler.post(new Runnable() {
@Override
public void run() {
try{
if(Successfull){
Log.i("Size",""+Placelist.size());
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for(int i=0;i<Placelist.size();i++){
setUpMap(Placelist.get(i));
builder.include(new LatLng(Placelist.get(i).getLatitude(),Placelist.get(i).getLongitude()));
}
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(builder.build(), 10);
mMap.moveCamera(cameraUpdate);
}
}catch(Exception e){
Log.e(TAG,e.toString());
}
}});
}
};
private void setUpMap(DataOfPlaceList placelistdata) {
Marker marker=mMap.addMarker(new MarkerOptions().position(new LatLng(placelistdata.getLatitude(),placelistdata.getLongitude())).title(""+placelistdata.getPlacename()).icon(BitmapDescriptorFactory.fromResource(R.drawable.mapicon)).snippet(placelistdata.getFacility()));
Placelistdata.put(marker.getId(),placelistdata);
/*LatLng latLng = new LatLng(shoplistdata.getLatitude(), shoplistdata.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(latLng);
CameraUpdateFactory.newLatLngBounds(latLng, 0);
LatLngBounds bounds=new LatLngBounds(latLng, latLng);
mMap.animateCamera(cameraUpdate);*/
}
class DataOfPlaceList{
private String placeid;
private String faciltiyid;
private String placename;
private Double distance;
private Double latitude;
private Double longitude;
public String getPlaceid(){
return placeid;
}
public void setPlaceid(String placeid){
this.placeid=placeid;
}
public String getFacility() {
return faciltiyid;
}
public void setFacility(String faciltiyid) {
this.faciltiyid = faciltiyid;
}
public String getPlacename() {
return placename;
}
public void setPlacename(String placename) {
this.placename = placename;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public Double getDistance() {
return distance;
}
public void setDistance(Double distance) {
this.distance = distance;
}
}
@Override
public void onDestroy() {
super. onDestroyView();
Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));
if(fragment!=null && isDestory){
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
trimCache(getActivity());
}
}
@Override
public boolean onBackPressed() {
// TODO Auto-generated method stub
isDestory=true;
return false;
}
}
BaseFragment
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
public class BaseFragment extends Fragment {
public TABActivity mActivity;
SharedPreferences mPrefs;
Typeface tf;
Boolean TABARefresh=false,TABBRefresh=false,TABCRefresh=false,TABDRefresh=false;
protected static final String TAG_ERROR_DIALOG_FRAGMENT="errorDialog";
/// For Email Validation////
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = (TABActivity) this.getActivity();
mPrefs = PreferenceManager.getDefaultSharedPreferences(mActivity);
tf=Typeface.createFromAsset(getActivity().getAssets(), "PORKYS.TTF");
}
public boolean onBackPressed(){
return false;
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
}
protected boolean readyToGo() {
int status=
GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if (status == ConnectionResult.SUCCESS) {
return(true);
}
else if (GooglePlayServicesUtil.isUserRecoverableError(status)) {
ErrorDialogFragment.newInstance(status)
.show(getActivity().getSupportFragmentManager(),
TAG_ERROR_DIALOG_FRAGMENT);
}
else {
AlertDialog dialog = new AlertDialog.Builder(getActivity()).create();
dialog.setMessage(getString(R.string.no_maps)+" Please install latest google map and update google play service too.");
dialog.setButton(AlertDialog.BUTTON_POSITIVE, "Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
((TABActivity)mActivity).onBackPressed();
}
});
dialog.show();
}
return(false);
}
public static class ErrorDialogFragment extends DialogFragment {
static final String ARG_STATUS="status";
static ErrorDialogFragment newInstance(int status) {
Bundle args=new Bundle();
args.putInt(ARG_STATUS, status);
ErrorDialogFragment result=new ErrorDialogFragment();
result.setArguments(args);
return(result);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle args=getArguments();
return GooglePlayServicesUtil.getErrorDialog(args.getInt(ARG_STATUS),
getActivity(), 0);
}
@Override
public void onDismiss(DialogInterface dlg) {
if (getActivity() != null) {
getActivity().finish();
}
}
}
}
我遇到的问题与此处发布的 http://code.google.com/p/gmaps-api-issues/issues/detail?id=4766 相同,并且由于内存泄漏,加载地图时会出现内存错误。
有时会显示首次加载时间图,但有时会崩溃。 我已经在三星TAB 2,索尼Erricson以及SAMSUNG GALAXY X-Cover型号GT-S5690 Android vers中进行了测试。 2.3.6在三星XCover中它大部分时间会崩溃,而且在索尼的情况下会崩溃一段时间。
我还在模拟器中通过模拟器进行了测试,如果第一次加载时我会第二次回来,而不是它会崩溃。
由于 https://developers.google.com/maps/documentation/android/releases 此问题的链接已解决但无法解决问题,我还尝试使用生成新的地图密钥。
任何帮助都会得到满足。
感谢。