Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I include the traffic layer of google maps?

Tags:

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.

like image 650
Sassy Llama Avatar asked Jul 27 '15 15:07

Sassy Llama


People also ask

How do I add traffic layers to Google Maps?

Step 1 Go to Add Or Edit Map and scroll down to 'Layers Settings' section. Step 2 Enable or tick 'Traffic Layer Tab'. Step 3 Then click on Save Map. You'll see the traffic layer on the map.

Does Google Maps include traffic?

Yes, Google Maps monitors traffic, and it has done so increasingly over time, using a growing array of data points, both public and private. Traffic sensors, such as radar, are used by both private companies and government agencies to gather traffic data from highways or major thoroughfares.

How do I get traffic data from Google Maps API?

Google Maps traffic information is available via the Distance Matrix API, and to access it, the only thing you need to do is to get a developer key from Google. You can call the service up to 2,500 times in a 24-hour period for free, which should be fine for most advertisers.


1 Answers

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);                }               });                  }             }         } 
like image 146
Prokash Sarkar Avatar answered Oct 15 '22 01:10

Prokash Sarkar