0

我是 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();
        }

    }

}

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

4

1 回答 1

2

首先要获取当前位置:

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

阅读此处了解更多信息。

然后您可以使用以下方法为该位置设置动画:

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 中与谷歌地图交互的所有信息

从上面引用的谷歌地图文档中,只是一些例子:

缩放控件:

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

我的位置按钮:

仅当启用 My Location 图层时,My Location 按钮才会出现在屏幕的右上角。当用户单击该按钮时,如果用户的位置当前已知,则相机会生成动画以聚焦于用户的当前位置。单击也会触发 GoogleMap.OnMyLocationButtonClickListener。您可以通过调用来完全禁止按钮出现 UiSettings.setMyLocationButtonEnabled(boolean)

添加标记:

下面的示例演示了如何向地图添加标记。标记在坐标 0,0 处创建,并在单击时在信息窗口中显示字符串“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"));
于 2013-08-28T15:39:52.217 回答