使用指定选项在Android应用中显示谷歌地图

时间:2013-08-28 14:48:35

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

我是Android开发的新手,我一直试图在我的应用程序中显示一段时间。我终于设法做到了,但我想用一些指定的选项显示它,如缩放级别,位置等,但证明是困难的。

以下是我的.xml文件

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          class="com.google.android.gms.maps.SupportMapFragment"/>

以下是我的.java文件

package com.fourapps.cabkonnect;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import android.location.Location;
import android.graphics.Color;

import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

/**
 * Created by nanakay on 6/6/13.
 */
public class Home extends FragmentActivity {
    GoogleMap map;

    private static final LatLng GOLDEN_GATE_BRIDGE = new LatLng(37.828891,-122.485884);
    private static final LatLng APPLE = new LatLng(37.3325004578, -122.03099823);

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);

        map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

        if (map == null) {
            Toast.makeText(this, "Google maps not available", Toast.LENGTH_LONG).show();
        }

    }

}

地图正在显示,但我想用自己的选项显示它。 如果有人可以提供帮助,我会很高兴。感谢

1 个答案:

答案 0 :(得分:2)

首先要获取当前位置:

private Location mCurrentLocation;
mCurrentLocation = mLocationClient.getLastLocation();

阅读here了解详情。

然后您可以使用以下命令设置该位置的动画:

LatLng myLaLn = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());

CameraPosition camPos = new CameraPosition.Builder().target(myLaLn)
                .zoom(15)
                .bearing(45)
                .tilt(70)
                .build();

 CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);

 map.animateCamera(camUpd3);

我给你一个简单但完整的例子来显示地图和当前位置:

public class MainActivity extends FragmentActivity implements
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener {

    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

    private LocationClient mLocationClient;
    private Location mCurrentLocation;
    private GoogleMap map;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        setUpLocationClientIfNeeded();
        mLocationClient.connect();
    }

    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the
        // map.
        if (map == null) {
            // Try to obtain the map from the SupportMapFragment.
            map = ((SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
            // Check if we were successful in obtaining the map.
            if (map == null) {
                Toast.makeText(this, "Google maps not available",
                        Toast.LENGTH_LONG).show();
            }
        }
    }

    private void setUpLocationClientIfNeeded() {
        if (mLocationClient == null) {
            Toast.makeText(getApplicationContext(), "Waiting for location",
                    Toast.LENGTH_SHORT).show();
            mLocationClient = new LocationClient(getApplicationContext(), this, // ConnectionCallbacks
                    this); // OnConnectionFailedListener
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mLocationClient != null) {
            mLocationClient.disconnect();
        }
    }

    /*
     * Called by Location Services when the request to connect the client
     * finishes successfully. At this point, you can request the current
     * location or start periodic updates
     */
    @Override
    public void onConnected(Bundle dataBundle) {
        mCurrentLocation = mLocationClient.getLastLocation();
        if (mCurrentLocation != null) {
            Toast.makeText(getApplicationContext(), "Found!",
                    Toast.LENGTH_SHORT).show();
            centerInLoc();
        }
    }

    private void centerInLoc() {
        LatLng myLaLn = new LatLng(mCurrentLocation.getLatitude(),
                mCurrentLocation.getLongitude());
        CameraPosition camPos = new CameraPosition.Builder().target(myLaLn)
                .zoom(15).bearing(45).tilt(70).build();

        CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
        map.animateCamera(camUpd3);

        MarkerOptions markerOpts = new MarkerOptions().position(myLaLn).title(
                "my Location");
        map.addMarker(markerOpts);
    }

    /*
     * Called by Location Services if the connection to the location client
     * drops because of an error.
     */
    @Override
    public void onDisconnected() {
        // Display the connection status
        Toast.makeText(this, "Disconnected. Please re-connect.",
                Toast.LENGTH_SHORT).show();
    }

    /*
     * Called by Location Services if the attempt to Location Services fails.
     */
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        /*
         * Google Play services can resolve some errors it detects. If the error
         * has a resolution, try sending an Intent to start a Google Play
         * services activity that can resolve error.
         */
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(this,
                        CONNECTION_FAILURE_RESOLUTION_REQUEST);
                /*
                 * Thrown if Google Play services canceled the original
                 * PendingIntent
                 */
            } catch (IntentSender.SendIntentException e) {
                // Log the error
                e.printStackTrace();
            }
        } else {
            /*
             * If no resolution is available
             */
            Log.e("Home", Integer.toString(connectionResult.getErrorCode()));
        }
    }
}

注1:我简单地省略了“检查Google Play服务”部分,但应将其作为一种良好做法添加。

注意2:您需要google-play-services_lib项目并从您的项目中引用它。

您可以在android here

中找到有关与Google地图进行互动的所有信息

从上面引用的google地图文档中,只举几个例子:

缩放控件:

Maps API提供了内置的缩放控件,显示在地图的右下角。这些默认情况下已启用,但可以通过调用 UiSettings.setZoomControlsEnabled(boolean)来禁用。

我的位置按钮:

仅当启用“我的位置”图层时,“我的位置”按钮才会显示在屏幕的右上角。当用户单击该按钮时,如果当前已知用户的位置,则摄像机会设置动画以关注用户的当前位置。点击还会触发GoogleMap.OnMyLocationButtonClickListener。您可以通过调用 UiSettings.setMyLocationButtonEnabled(boolean)来禁用该按钮。

添加标记:

以下示例演示了如何向地图添加标记。标记在坐标0,0处创建,并在单击时在infowindow中显示字符串“Hello world”。

private GoogleMap mMap;
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.addMarker(new MarkerOptions()
        .position(new LatLng(0, 0))
        .title("Hello world"));