【问题标题】:How can I include the traffic layer of google maps?如何包含谷歌地图的交通图层?
【发布时间】:2015-10-17 22:01:40
【问题描述】:

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

我通过 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 完成的?这是我的完整活动代码:

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

}

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

【问题讨论】:

  • 您可以尝试使用像 NYC 这样的硬编码位置吗?谷歌地图没有所有国家的交通数据!
  • 是的,先生;我可以使用美国城市的坐标毫无问题地加载地图。我硬编码到我的 XML 清单文件中;我应该在 mainactivity 中声明吗?
  • 您需要检测您的位置以显示该特定位置的交通数据。请检查我的答案。

标签: android google-maps google-maps-api-2


【解决方案1】:

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

  1. 确保在 Google 地图中检测到您的当前位置

  2. 确保您的 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);
               }
              });

                }
            }
        }

【讨论】:

  • 试过这段代码,但它在地图上添加了交通层,而不是只在路线上添加。
【解决方案2】:

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

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

            }
}

【讨论】:

  • 感谢推荐!我尝试了这个,但它一直告诉我“尝试”是一个意外的标记,并且 initializeMap();身份不明。我应该把try {放在一个方法中并为initializeMap创建一个常量吗?如果我听起来毫无头绪,我深表歉意;我仍然在理解逻辑。
  • 再次感谢您的帮助;但请原谅我对此事的无知。我已经检查了您的编辑并将其重新实现到我的代码中,但是我继续在“googleMap”和“locationManager”上得到“无法解析符号”;我该怎么做才能继续?此外,我必须创建一个用于 initializeMap 的方法,以消除该错误;这也是不正确的吗?
【解决方案3】:

设置以下行以启用交通和当前位置:

mGoogleMap.isMyLocationEnabled = true
mGoogleMap.isTrafficEnabled = true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-30
    • 2018-12-17
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多