我正在从tabhost片段活动中调用一个地图片段
mTabHost.addTab(mTabHost.newTabSpec("tab4").setIndicator("Commend",tabIcon4Light), Map_Locations_Fragment.class, null);
现在我的GoogleMap回来了
mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
我正在扩展片段而不是片段活动因为tabhost不会让我扩展活动。
我也在使用android.support.v4.app.Fragment;我在堆栈下尝试了一些其他答案((SupportMapFragment)getFragmentManager()。findFragmentById(R.id.map))。getMap(); null,但我似乎设置正确,或者他们说扩展FragmentActivity,在我的情况下似乎不是一个选项。
XML
<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/rg_views"
class="com.google.android.gms.maps.SupportMapFragment"/>
类
public class Map_Locations_Fragment extends Fragment implements LocationListener, LocationSource, OnMarkerClickListener, OnInfoWindowClickListener {
View inflatedView;
Context context = null;
ViewGroup group;
private ProgressDialog pd;
private String popoid;
private GoogleMap mMap;
private OnLocationChangedListener mListener;
private LocationManager locationManager;
private String phoneNumber;
private JSONObject json;
private JSONObject json2;
private JSONArray nameArray;
private JSONArray valArray;
private JSONArray valArray2 = null;
private JSONArray nameArray2;
private LatLng userLocation = null;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
if (inflatedView != null) {
ViewGroup parent = (ViewGroup) inflatedView.getParent();
if (parent != null)
parent.removeView(inflatedView);
}
try {
inflatedView = inflater.inflate(R.layout.fragment_map_locations,
container, false);
context = getActivity().getApplicationContext();
popoid = getActivity().getString(R.string.popoid);
setUpMapIfNeeded();
} catch (InflateException e) {
}
return inflatedView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void locationCheck() {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
boolean gpsIsEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!gpsIsEnabled) {
buildAlertMessageNoGps();
} else {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 5000L, 10F, this);
}
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double latitute, longitude = 0;
if (location != null) {
latitute = location.getLatitude();
longitude = location.getLongitude();
userLocation = new LatLng(latitute, longitude);
}
} else {
// Show some generic error dialog because something must have gone
// wrong with location manager.
}
}
// Ask to turn on GPS in its off
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(
"Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog,
final int id) {
startActivity(new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog,
final int id) {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean networkIsEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (networkIsEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 5000L,
10F, (LocationListener) getActivity());
}
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
@Override
public void onPause() {
if (locationManager != null) {
locationManager.removeUpdates(this);
}
super.onPause();
}
@Override
public void onResume() {
super.onResume();
context = getActivity().getApplicationContext();
if (Repeatables.isNetworkAvailable(context) == true) {
locationCheck();
setUpMapIfNeeded();
} else {
}
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play
* Services)
*/
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();
if (isGoogleMapsInstalled()) {
if (locationManager != null) {
mMap.setMyLocationEnabled(true);
}
// Check if we were successful in obtaining the map.
if (mMap != null) {
// This is how you register the Location Source
mMap.setLocationSource(this);
setUpMap();
}
} else {
Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Please install Google Maps");
builder.setCancelable(false);
builder.setPositiveButton(
"Install",
(android.content.DialogInterface.OnClickListener) getGoogleMapsListener());
AlertDialog dialog = builder.create();
dialog.show();
}
}
}
public void onDestroyView() {
super.onDestroyView();
SupportMapFragment f = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
if (f != null){
getFragmentManager().beginTransaction().remove(f).commitAllowingStateLoss();
}
}
public boolean isGoogleMapsInstalled() {
try {
@SuppressWarnings("unused")
ApplicationInfo info = getActivity().getPackageManager().getApplicationInfo(
"com.google.android.apps.maps", 0);
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
public OnClickListener getGoogleMapsListener() {
return new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("market://details?id=com.google.android.apps.maps"));
startActivity(intent);
// Finish the activity so they can't circumvent the check
//finish();
}
};
}
/**
* This is where we can add markers or lines, add listeners or move the
* camera.
* <p>
* This should only be called once and when we are sure that {@link #mMap}
* is not null.
*/
private void setUpMap() {
mMap.setMyLocationEnabled(true);
// Set up sat/street/reg view
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
RadioGroup rgViews = (RadioGroup) inflatedView.findViewById(R.id.rg_views);
rgViews.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.rb_normal) {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
} else if (checkedId == R.id.rb_satellite) {
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
} else if (checkedId == R.id.rb_terrain) {
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
}
}
});
// Setting a custom info window adapter for the google map
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 = getLayoutInflater(getArguments()).inflate(R.layout.map_popup, null);
// Getting the position from the marker
// LatLng latLng = arg0.getPosition();
// Getting reference to the TextView to set latitude
TextView tvTitle = (TextView) v.findViewById(R.id.popTitle);
// Getting reference to the TextView to set longitude
TextView tvSnippet = (TextView) v.findViewById(R.id.popSnippet);
StringTokenizer tokens = new StringTokenizer(arg0.getSnippet(),
":");
String address = tokens.nextToken();
phoneNumber = tokens.nextToken();
if (phoneNumber.equals("0")) {
((Button) v.findViewById(R.id.btnCall))
.setVisibility(View.GONE);
} else {
((Button) v.findViewById(R.id.btnCall))
.setVisibility(View.VISIBLE);
}
tvTitle.setText((arg0.getTitle()));
tvSnippet.setText(address);
// Returning the view containing InfoWindow contents
return v;
}
});
new MoveOutOfUIthread().execute();
mMap.setOnInfoWindowClickListener(this);
mMap.setOnMarkerClickListener(null);
}
@Override
public void activate(OnLocationChangedListener listener) {
mListener = listener;
}
@Override
public void deactivate() {
mListener = null;
}
@Override
public void onLocationChanged(Location location) {
if (mListener != null) {
mListener.onLocationChanged(location);
userLocation = new LatLng(location.getLatitude(),
location.getLongitude());
// Zoom to users location
// mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(
// location.getLatitude(), location.getLongitude())));
}
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
// Toast.makeText(this, "provider disabled", Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
// Toast.makeText(this, "provider enabled", Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
// Toast.makeText(this, "status changed", Toast.LENGTH_SHORT).show();
}
// What happens when the pop box is clicked.
@Override
public void onInfoWindowClick(Marker marker) {
// TODO Auto-generated method stub
Log.e("InfoWindow", "Click");
Intent i = new Intent(Intent.ACTION_DIAL);
String p = "tel:" + phoneNumber;
i.setData(Uri.parse(p));
startActivity(i);
}
// What happens when the pin is clicked other than the pop up box.
@Override
public boolean onMarkerClick(Marker marker) {
// TODO Auto-generated method stub
Log.e("Marker", "Click");
return false;
}
private class MoveOutOfUIthread extends AsyncTask<Void, Void, Void> {
ProgressDialog dialogLoadingPins = new ProgressDialog(getActivity());
@Override
public void onPreExecute() {
this.dialogLoadingPins.setMessage("Loading Map Pins...");
this.dialogLoadingPins.show();
}
protected Void doInBackground(Void... unused) {
// your background task here
String resultURL = Repeatables
.queryRESTurl("my url goes here");
try {
json = new JSONObject(resultURL);
nameArray = json.names();
valArray = json.toJSONArray(nameArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
try {
String TITLE = null;
String SNIPPET = null;
for (int i = 0; i < valArray.length(); i++) {
json2 = new JSONObject(valArray.getString(i));
nameArray2 = json2.names();
valArray2 = json2.toJSONArray(nameArray2);
TITLE = valArray2.getString(0);
SNIPPET = valArray2.getString(1);
final LatLng newCords = new LatLng(valArray2.getDouble(3),
valArray2.getDouble(2));
mMap.addMarker(new MarkerOptions()
.position(newCords)
.title(TITLE)
.snippet(SNIPPET)
.icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
builder.include(newCords);
}
// builder.include(userLocation);
// Set Zoom to Markers
LatLngBounds bounds = builder.build();
int padding = 30; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds,
padding);
mMap.moveCamera(cu);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (dialogLoadingPins.isShowing()) {
dialogLoadingPins.dismiss();
}
}
}
}
答案 0 :(得分:0)
您应该将MapView小部件添加到布局中,如下所示:
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
然后从MapView对象获取googleMap引用:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.map_fragment_layout,
container, false);
mMapView = (MapView) rootView.findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
imageCompass = (ImageView) rootView.findViewById(R.id.mapImageCompass);
googleMap = mMapView.getMap();
return rootView;
}