android – How can I include the traffic layer of google maps?-ThrowExceptions

Exception or error:

I’m new to development within android using the Google Maps API. I’ve been able to set up a map and test out the basic functionality, but I’m having trouble implementing the logic shown in the documentation into my own code.

I’ve researched and found through google’s documentation you must have the map check if traffic data is available by using:

public final boolean isTrafficEnabled() 

and then calling the method:

public final boolean isTrafficEnabled() {
   return mMap.isTrafficEnabled();

}
public final void setTrafficEnabled(boolean enabled) {
   mMap.setTrafficEnabled(enabled);
}

I’m not exactly sure how to implement this as I’m new to development altogether. I found in another documentation source the following example:

var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

var trafficLayer = new google.maps.TrafficLayer();
 trafficLayer.setMap(map);

}

google.maps.event.addDomListener(window, 'load', initialize);

Yet I can’t seem to figure out how to do it properly. Do I have to edit the manifest XML in any way or is this all done from the mainActivity? Here is my full activity code:

package example.testdevice;

import android.app.Dialog;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;


public class MainActivity extends FragmentActivity {

private static final int GPS_ERRORDIALOG_REQUEST = 9001;
GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (servicesOK()) {                                                         //checks if APK is available; if it is, display Map
        setContentView(R.layout.activity_map);

        if (initMap()){
            Toast.makeText(this, "Ready to Map", Toast.LENGTH_SHORT).show();
        }
    else {
            Toast.makeText(this, "Map not available!", Toast.LENGTH_SHORT).show();
        }
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

public boolean servicesOK() {
    int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); //pass this as context

    if (isAvailable == ConnectionResult.SUCCESS) {
        return true;
    }
    else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, GPS_ERRORDIALOG_REQUEST); //error code, activity, request code
        dialog.show();
    }
    else {
        Toast.makeText(this, "Can't connect to Google Play Services", Toast.LENGTH_SHORT).show();
    }
    return false;
    }

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

private boolean initMap() {
    if (mMap == null) {
        SupportMapFragment mapFrag =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); // reference to support map fragment
        mMap = mapFrag.getMap();
    }
    return (mMap != null);
}

public final boolean isTrafficEnabled() {
    return mMap.isTrafficEnabled();

}
public final void setTrafficEnabled(boolean enabled) {
    mMap.setTrafficEnabled(enabled);
}

}

The map loads but it does not show any kind of traffic. Any and all help would be greatly appreciated; thank you in advance.

How to solve:

To be able to show traffic data you should consider the following issues,

  1. Make sure your current location is detected in Google Map

  2. Make sure your Google Map has traffic data available for your current location.

You may also try the following code. It initializes the map properly then sets traffic data after detecting your current location.

  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) getSupportFragmentManager().findFragmentById(R.id.map))
                        .getMap();
                mMap.setMyLocationEnabled(true);
                // Check if we were successful in obtaining the map.
                if (mMap != null) {


                 mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {

               @Override
               public void onMyLocationChange(Location arg0) {
                // TODO Auto-generated method stub

                 mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));

                 //load the traffic now
                  googleMap.setTrafficEnabled(true);
               }
              });

                }
            }
        }

###

Try the following code in your activity in which you want to load the map:

private GoogleMap googleMap;
protected LocationManager locationManager;
    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);


    try {
                // Loading map
                initilizeMap();

                // Changing map type
                googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                // googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                // googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
                // googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
                // googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);

                // Showing / hiding your current location
                googleMap.setMyLocationEnabled(true);
                googleMap.setTrafficEnabled(true);
                // Enable / Disable zooming controls
                googleMap.getUiSettings().setZoomControlsEnabled(true);

                // Enable / Disable my location button
                googleMap.getUiSettings().setMyLocationButtonEnabled(true);

                // Enable / Disable Compass icon
                googleMap.getUiSettings().setCompassEnabled(true);

                // Enable / Disable Rotate gesture
                googleMap.getUiSettings().setRotateGesturesEnabled(true);

                // Enable / Disable zooming functionality
                googleMap.getUiSettings().setZoomGesturesEnabled(true);
                locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);


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

            }
}

Leave a Reply

Your email address will not be published. Required fields are marked *