How can I include the traffic layer of google maps?
Asked Answered
M

3

24

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.

Misbecome answered 27/7, 2015 at 15:58 Comment(3)
Can you try with a hard coded location like NYC ? Google Maps don't have traffic data for all countries!Yatzeck
Yes sir; I'm able to load the map without an issue using the coordinates of a city in the US. I hard coded into my XML manifest file; am I supposed to declare that in the mainactivity instead?Misbecome
You need to detect your location for showing traffic data for that particular location. Please check my answer.Yatzeck
Y
29

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

                }
            }
        }
Yatzeck answered 27/7, 2015 at 16:39 Comment(1)
Tried this code but it is adding traffic layer all over the map instead of adding it only on the route.Breedlove
A
7

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

            }
}
Athanor answered 27/7, 2015 at 16:3 Comment(2)
Thanks for the recommendation! I attempted this but it keeps telling me that 'try' is an unexpected token and initializeMap(); is unidentified. Should I put try { in a method and create a constant for initializeMap? I apologize if I sound clueless; I'm still getting the grips of understanding the logic.Misbecome
Thank you again for your help; but please excuse my ignorance on the matter. I've checked your edits and re-implemented it into my code, however I continue to get "cannot resolve symbol" on 'googleMap' and 'locationManager'; what can I do to continue? Additionally, I had to create a method for initializeMap in order to get that error to go away; is this also incorrect?Misbecome
B
0

Set following lines for enabling traffic and current location:

mGoogleMap.isMyLocationEnabled = true
mGoogleMap.isTrafficEnabled = true
Belgrade answered 3/8, 2021 at 12:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.