如何包含 google 地图的交通图层?

How can I include the traffic layer of google maps?

我是 android 中使用 Google 地图 API 进行开发的新手。我已经能够设置地图并测试基本功能,但我无法将文档中显示的逻辑实现到我自己的代码中。

我通过 google 的文档进行了研究并发现您必须使用以下方法检查地图是否有可用的交通数据:

public final boolean isTrafficEnabled() 

然后调用方法:

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

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

我不太确定如何实现它,因为我是开发新手。我在另一个文档来源中找到了以下示例:

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

但我似乎无法弄清楚如何正确地做到这一点。我必须以任何方式编辑清单 XML 还是全部从 mainActivity 完成?这是我的完整 activity 代码:

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

}

地图加载但未显示任何类型的交通。任何帮助将不胜感激;提前谢谢你。

在您要加载地图的 activity 中尝试以下代码:

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

            }
}

为了能够显示流量数据,您应该考虑以下问题,

  1. 确保在 Google 地图

  2. 中检测到您的当前位置
  3. 确保您的 Google 地图具有您当前位置的交通数据。

您也可以试试下面的代码。它会正确初始化地图,然后在检测到您的当前位置后设置交通数据。

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

                }
            }
        }

设置以下行以启用流量和当前位置:

mGoogleMap.isMyLocationEnabled = true
mGoogleMap.isTrafficEnabled = true