在片段中实现android谷歌地图

时间:2015-03-01 07:43:10

标签: java android google-maps android-fragments google-maps-android-api-2

我为我的应用实现了this代码,它将以片段形式显示。我已经将使用FragmentActivity的所有方法更改为片段。但是当我运行它并去映射片段时它给出了这个错误: 日志文件:

03-31 12:10:47.235: E/AndroidRuntime(612): FATAL EXCEPTION: main
03-31 12:10:47.235: E/AndroidRuntime(612): java.lang.ClassCastException: plusnet.tashrifat.MainActivity cannot be cast to android.support.v4.app.FragmentActivity
03-31 12:10:47.235: E/AndroidRuntime(612):  at plusnet.tashrifat.MapFragment.onAttach(MapFragment.java:47)
03-31 12:10:47.235: E/AndroidRuntime(612):  at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:787)
03-31 12:10:47.235: E/AndroidRuntime(612):  at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
03-31 12:10:47.235: E/AndroidRuntime(612):  at android.app.BackStackRecord.run(BackStackRecord.java:635)
03-31 12:10:47.235: E/AndroidRuntime(612):  at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1397)
03-31 12:10:47.235: E/AndroidRuntime(612):  at android.app.FragmentManagerImpl$1.run(FragmentManager.java:426)
03-31 12:10:47.235: E/AndroidRuntime(612):  at android.os.Handler.handleCallback(Handler.java:615)
03-31 12:10:47.235: E/AndroidRuntime(612):  at android.os.Handler.dispatchMessage(Handler.java:92)
03-31 12:10:47.235: E/AndroidRuntime(612):  at android.os.Looper.loop(Looper.java:137)
03-31 12:10:47.235: E/AndroidRuntime(612):  at android.app.ActivityThread.main(ActivityThread.java:4745)
03-31 12:10:47.235: E/AndroidRuntime(612):  at java.lang.reflect.Method.invokeNative(Native Method)
03-31 12:10:47.235: E/AndroidRuntime(612):  at java.lang.reflect.Method.invoke(Method.java:511)
03-31 12:10:47.235: E/AndroidRuntime(612):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-31 12:10:47.235: E/AndroidRuntime(612):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-31 12:10:47.235: E/AndroidRuntime(612):  at dalvik.system.NativeStart.main(Native Method)

和我的片段代码:

public class MapFragment extends Fragment {

public MapFragment() {

}

@Override
public void onAttach(Activity activity) {
    myContext = (FragmentActivity) activity;
    super.onAttach(activity);
}

GoogleMap map;
ArrayList<LatLng> markerPoints;
LatLng userPoint;
private FragmentActivity myContext;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub

    View rootView = inflater.inflate(R.layout.mymap, container);
    LatLng tashrifat = new LatLng(38.065922, 46.323698);

    // Initializing
    markerPoints = new ArrayList<LatLng>();

    // Getting reference to SupportMapFragment of the activity_main
    SupportMapFragment fm = (SupportMapFragment) myContext
            .getSupportFragmentManager().findFragmentById(R.id.map);
    userPoint = new LatLng(38.090079, 46.233212);
    // Getting Map for the SupportMapFragment
    map = fm.getMap();

    LocationResult locationResult = new LocationResult() {
        public void gotLocation(Location location) {
            userPoint = new LatLng(location.getLatitude(),
                    location.getLongitude());
        }
    };
    CameraUpdate center = CameraUpdateFactory.newLatLng(tashrifat);
    CameraUpdate zoom = CameraUpdateFactory.zoomTo(17);

    map.moveCamera(center);
    map.animateCamera(zoom);
    MyLocation myLocation = new MyLocation();
    myLocation.getLocation(getActivity(), locationResult);
    // String url = getDirectionsUrl(userPoint, tashrifat);
    // DownloadTask downloadTask = new DownloadTask();

    // Start downloading json data from Google Directions
    // API
    // downloadTask.execute(url);

    if (map != null) {

        // Enable MyLocation Button in the Map
        map.setMyLocationEnabled(true);

        // Setting onclick event listener for the map

        // Already two locations
        if (markerPoints.size() > 1) {
            markerPoints.clear();
            map.clear();
        }

        // Adding new item to the ArrayList
        markerPoints.add(userPoint);
        markerPoints.add(tashrifat);

        // Creating MarkerOptions
        MarkerOptions options = new MarkerOptions();

        // Setting the position of the marker
        options.position(userPoint);
        options.position(tashrifat);

        /**
         * For the start location, the color of marker is GREEN and for the
         * end location, the color of marker is RED.
         */
        if (markerPoints.size() == 1) {
            options.icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
        } else if (markerPoints.size() == 2) {
            options.icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_RED));
        }

        // Add new marker to the Google Map Android API V2
        map.addMarker(options);

        // Checks, whether start and end locations are captured

        LatLng origin = tashrifat;
        LatLng dest = userPoint;

        // Getting URL to the Google Directions API
        String url = getDirectionsUrl(origin, dest);

        DownloadTask downloadTask = new DownloadTask();

        // Start downloading json data from Google Directions
        // API
        downloadTask.execute(url);

    }

    return rootView;
}

另一个我不会处理它的功能,并且喜欢那个引用代码:

private String getDirectionsUrl(LatLng origin, LatLng dest) {

    // Origin of route
    String str_origin = "origin=" + origin.latitude + ","
            + origin.longitude;

    // Destination of route
    String str_dest = "destination=" + dest.latitude + "," + dest.longitude;

    // Sensor enabled
    String sensor = "sensor=false";

    // Building the parameters to the web service
    String parameters = str_origin + "&" + str_dest + "&" + sensor;

    // Output format
    String output = "json";

    // Building the url to the web service
    String url = "https://maps.googleapis.com/maps/api/directions/"
            + output + "?" + parameters;

    return url;
}

/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException {
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(strUrl);

        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(
                iStream));

        StringBuffer sb = new StringBuffer();

        String line = "";
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        data = sb.toString();

        br.close();

    } catch (Exception e) {
        Log.d("Exception while downloading url", e.toString());
    } finally {
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}

// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String> {

    // Downloading data in non-ui thread
    @Override
    protected String doInBackground(String... url) {

        // For storing data from web service
        String data = "";

        try {
            // Fetching the data from web service
            data = downloadUrl(url[0]);
        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        return data;
    }

    // Executes in UI thread, after the execution of
    // doInBackground()
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        ParserTask parserTask = new ParserTask();

        // Invokes the thread for parsing the JSON data
        parserTask.execute(result);
    }
}

/** A class to parse the Google Places in JSON format */
private class ParserTask extends
        AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {

    // Parsing the data in non-ui thread
    @Override
    protected List<List<HashMap<String, String>>> doInBackground(
            String... jsonData) {

        JSONObject jObject;
        List<List<HashMap<String, String>>> routes = null;

        try {
            jObject = new JSONObject(jsonData[0]);
            DirectionsJSONParser parser = new DirectionsJSONParser();

            // Starts parsing data
            routes = parser.parse(jObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return routes;
    }

    // Executes in UI thread, after the parsing process
    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        ArrayList<LatLng> points = null;
        PolylineOptions lineOptions = null;
        MarkerOptions markerOptions = new MarkerOptions();

        // Traversing through all the routes
        for (int i = 0; i < result.size(); i++) {
            points = new ArrayList<LatLng>();
            lineOptions = new PolylineOptions();

            lineOptions.width(5);
            lineOptions.color(Color.BLUE);
            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // Fetching all the points in i-th route
            for (int j = 0; j < path.size(); j++) {
                HashMap<String, String> point = path.get(j);

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(2);
            lineOptions.color(Color.RED);
        }

        // Drawing polyline in the Google Map for the i-th route
        map.addPolyline(lineOptions);
    }
}

}

我的布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<fragment
    android:id="@+id/map"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    class="com.google.android.gms.maps.SupportMapFragment" />

主要活动:

public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;

// nav drawer title
private CharSequence mDrawerTitle;

// used to store app title
private CharSequence mTitle;

// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;

private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mTitle = mDrawerTitle = getTitle();

    // load slide menu items
    navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

    // nav drawer icons from resources
    navMenuIcons = getResources()
            .obtainTypedArray(R.array.nav_drawer_icons);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

    navDrawerItems = new ArrayList<NavDrawerItem>();

    // adding nav drawer items to array
    // Home
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons
            .getResourceId(0, -1)));
    // Find People
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons
            .getResourceId(1, -1)));
    // Photos
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
            .getResourceId(2, -1)));
    // Communities, Will add a counter her
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
            .getResourceId(3, -1), false, "22"));
    // // Pages
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons
            .getResourceId(4, -1)));
    // // What's hot, We will add a counter here
    // navDrawerItems.add(new NavDrawerItem(navMenuTitles[5],
    // navMenuIcons.getResourceId(5, -1), true, "50+"));

    // Recycle the typed array
    navMenuIcons.recycle();

    mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

    // setting the nav drawer list adapter
    adapter = new NavDrawerListAdapter(getApplicationContext(),
            navDrawerItems);
    mDrawerList.setAdapter(adapter);

    // enabling action bar app icon and behaving it as toggle button
    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            R.drawable.ic_drawer, // nav menu toggle icon
            R.string.app_name, // nav drawer open - description for
                                // accessibility
            R.string.app_name // nav drawer close - description for
                                // accessibility
    ) {
        public void onDrawerClosed(View view) {
            getActionBar().setTitle(mTitle);
            // calling onPrepareOptionsMenu() to show action bar icons
            invalidateOptionsMenu();
        }

        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);
            // calling onPrepareOptionsMenu() to hide action bar icons
            invalidateOptionsMenu();
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    if (savedInstanceState == null) {
        // on first time display view for first nav item
        displayView(0);
    }
}

/**
 * Slide menu item click listener
 * */
private class SlideMenuClickListener implements
        ListView.OnItemClickListener {
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        // display view for selected nav drawer item
        displayView(position);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.actionbar, menu);
    // SearchManager searchManager = (SearchManager)
    // getSystemService(Context.SEARCH_SERVICE);
    // SearchView searchView = (SearchView) menu.findItem(R.id.search)
    // .getActionView();
    // searchView.setSearchableInfo(searchManager
    // .getSearchableInfo(getComponentName()));
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // toggle nav drawer on selecting action bar app icon/title
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    // Handle action bar actions click
    switch (item.getItemId()) {
    case R.id.action_settings:
        return true;
    case R.id.search:
        return true;
    case R.id.card:
        gotCardFragment();
    default:
        return super.onOptionsItemSelected(item);
    }
}

/* *
 * Called when invalidateOptionsMenu() is triggered
 */

private void gotCardFragment() {
    Fragment cardFragment = new Card();
    FragmentManager FM = getFragmentManager();
    FM.beginTransaction().replace(R.id.frame_container, cardFragment)
            .commit();
}

/**
 * Diplaying fragment view for selected nav drawer list item
 * */
private void displayView(int position) {
    // update the main content by replacing fragments
    Fragment fragment = null;
    switch (position) {
    case 0:
        fragment = new ParentCategoury();
        break;
    case 1:
        fragment = new AccountFragment();
        break;
    case 2:
        fragment = new MapFragment();
        break;
    case 3:
        fragment = new Card();
        break;
    case 4:
        this.finish();
        break;
    case 5:
        this.finish();

    default:
        break;
    }

    if (fragment != null) {
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.frame_container, fragment).commit();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        setTitle(navMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    } else {
        // error in creating fragment
        Log.e("MainActivity", "Error in creating fragment");
    }
}

@Override
public void setTitle(CharSequence title) {
    mTitle = title;
    getActionBar().setTitle(mTitle);
}

/**
 * When using the ActionBarDrawerToggle, you must call it during
 * onPostCreate() and onConfigurationChanged()...
 */

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
    mDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Pass any configuration change to the drawer toggls
    mDrawerToggle.onConfigurationChanged(newConfig);
}

}

1 个答案:

答案 0 :(得分:1)

我建议您从主要活动中引用地图片段。 您可以通过在OnCreate方法上执行以下操作来实现此目的

        //load static layout from: res/layout/activity_main.xml
    setContentView(R.layout.activity_main);

    //get Map Fragment and retrieve GoogleMap object
    MapFragment mapFragment = (MapFragment) getFragmentManager()
            .findFragmentById(R.id.map);
    map = mapFragment.getMap();

然后您可以开始使用它,例如您可以启用位置,设置缩放级别等。