驾驶距离和旅行时间谷歌地图V2错误

时间:2014-04-14 03:50:10

标签: java android google-maps

我在java中有这个代码,这个代码错误,以及来自Google Map Android API V2中两个位置之间的行驶距离和行程时间的代码:

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);    

    try {
        initilizeMap();

        tvDistanceDuration = (TextView) findViewById(R.id.tv_distance_time);
        // Initializing
        markerPoints = new ArrayList<LatLng>();

        // Getting reference to SupportMapFragment of the activity_main
        SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);

        // Getting Map for the SupportMapFragment
        googleMap = fm.getMap();

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

        googleMap.setOnMapClickListener(new OnMapClickListener() {

            public void onMapClick(LatLng point) {
                // TODO Auto-generated method stub
                // Already two locations
                if(markerPoints.size()>1){
                    markerPoints.clear();
                    googleMap.clear();
                }

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

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

                // Setting the position of the marker
                options.position(point);

                /**
                 * 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));
                 }

                 googleMap.addMarker(options);

              // Checks, whether start and end locations are captured
                 if(markerPoints.size() >= 2){
                     LatLng origin = markerPoints.get(0);
                     LatLng dest = markerPoints.get(1);

                     // 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);
                 }
            }
        });

        //Coding Map

        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        googleMap.setMyLocationEnabled(true);
        googleMap.getUiSettings().setZoomControlsEnabled(false);
        googleMap.getUiSettings().setMyLocationButtonEnabled(true);
        googleMap.getUiSettings().setCompassEnabled(true);
        googleMap.getUiSettings().setRotateGesturesEnabled(true);
        googleMap.getUiSettings().setZoomGesturesEnabled(true);
        googleMap.getMyLocation();

        double latitude = -6.941830;
        double longitude = 107.628480;



            MarkerOptions marker = new MarkerOptions().position(
                    new LatLng(latitude, longitude))
                    .title("I'm Here");

            Log.e("Random", "> " + latitude + ", "
                    + longitude);

                marker.icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
            googleMap.addMarker(marker);

            //setting zoom level
                CameraPosition cameraPosition = new CameraPosition.Builder()
                        .target(new LatLng(latitude,
                                longitude)).zoom(16).build();

                googleMap.animateCamera(CameraUpdateFactory
                        .newCameraPosition(cameraPosition));



    } catch (Exception e) {
        e.printStackTrace();
    }

    //Coding Slide atau Drawable

    mTitle = mDrawerTitle = getTitle();

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

    // ngambil nav drawer icons drawer 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>();


    // Home
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
    // Kereta
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
    // Bis
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
    // Pesawat
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
    // Kapal Laut
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
    // Tempat/Place
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
    // About
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));


    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,
            R.string.app_name,
            R.string.app_name
    ) {
        public void onDrawerClosed(View view) {
            getActionBar().setTitle(mTitle);
            // Buat Show
            invalidateOptionsMenu();
        }

        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);
            // Buat Hide
            invalidateOptionsMenu();
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    if (savedInstanceState == null) {
        displayView(0);
    }



}


 private class SlideMenuClickListener implements
 ListView.OnItemClickListener {
     @Override
     public void onItemClick(AdapterView<?> parent, View view, int position,
     long id) {
         // Buat Display
         displayView(position);
     }
 }

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        switch (item.getItemId()) {
        case R.id.action_help:
            return true;
        case R.id.action_refresh:
            return true;
        case R.id.action_settings:
            return true;
        case R.id.action_search:
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    private void displayView(int position) {
        Fragment fragment = null;
        switch (position) {
        case 0:
            fragment = new HomeFragment();
            break;
        case 1:
            fragment = new KeretaApiFragment();
            break;
        case 2:
            fragment = new BisFragment();
            break;
        case 3:
            fragment = new PesawatFragment();
            break;
        case 4:
            fragment = new KapalLautFragment();
            break;
        case 5:
            fragment = new PlaceFragment();
            break;
        case 6:
            fragment = new AboutFragment();
            break;

        default:
            break;
        }

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

            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            Log.e("MainActivity", "Gagal Memuat");
        }
    }

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

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }


@Override
protected void onResume() {
    super.onResume();
    initilizeMap();
}

private void initilizeMap() {
    if (googleMap == null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();

        // cek map status, bisa dubuat / tidak
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Maaf Maps anda gagal dimuat \n"+
                    "Mungkin karena koneksi anda lelet :)", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}

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;
}

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);
    }
}

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
    @SuppressWarnings("unused")
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        ArrayList<LatLng> points = null;
        PolylineOptions lineOptions = null;
        MarkerOptions markerOptions = new MarkerOptions();
        String distance = "";
        String duration = "";

        if(result.size()<1){
            Toast.makeText(getBaseContext(), "No Points", Toast.LENGTH_SHORT).show();
            return;
        }

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

            // 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);

                if(j==0){    // Get distance from the list
                    distance = (String)point.get("distance");
                    continue;
                }else if(j==1){ // Get duration from the list
                    duration = (String)point.get("duration");
                    continue;
                }

                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);
        }

        tvDistanceDuration.setText("Distance:"+distance + ", Duration:"+duration);

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

并且错误在:

  

SupportMapFragment fm =(SupportMapFragment)getSupportFragmentManager()。findFragmentById(R.id.map);

错误信息&#34;方法getSupportFragmentManager()未定义类型MainActivity&#34; 请帮帮我

3 个答案:

答案 0 :(得分:0)

你应该遗漏import android.support.v4.app.FragmentManager;

答案 1 :(得分:0)

您需要声明import android.support.v4.app.FragmentManager;

或者您可以使用以下方式创建成员:

private android.support.v4.app.FragmentManager ftManager;

答案 2 :(得分:0)

我猜你的MainActivity扩展了Activity而不是Fragment Activity。

你也有

initilizeMap();

因为你有

googleMap = ((MapFragment) getFragmentManager().findFragmentById(
            R.id.map)).getMap();

虽然你有

SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);

    // Getting Map for the SupportMapFragment
googleMap = fm.getMap();

您正在初始化地图对象两次。使用MapFragment然后使用SupportMapFragment

修复

检查清单中的min sdk版本。如果它低于11,则延伸FragmentActivity并使用SupportMapFragment

其次检查Google Play服务的可用性,无需初始化地图对象两次。