1

我对 Android 开发非常陌生,我正在尝试创建一个应用程序,该应用程序将在我行走时使用地图叠加层来跟踪路线。我已经能够启动并运行地图,并且可以让它显示我的运动,但我不知道如何在地图上显示路线。我想我需要使用折线来做到这一点,并且我尝试设置一个列表,然后从该列表中绘制线,但我不确定这是否是要使用的适当逻辑。任何帮助都将不胜感激。

这是我到目前为止的代码:

ACTIVITY_MAIN_XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<fragment  
      android:id="@+id/map"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:name="com.google.android.gms.maps.MapFragment"
      />

MAINACTIVITY.JAVA

package com.example.google_maps_test;

import java.util.List;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource.OnLocationChangedListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

import android.location.Location;
import android.location.LocationListener;
import android.os.Build;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity implements    GooglePlayServicesClient.ConnectionCallbacks, 
OnConnectionFailedListener, LocationListener{

private OnLocationChangedListener mListener;
GoogleMap mMap;
LocationClient mLocationClient;
Location mCurrentLocation;
LocationRequest mLocationRequest;
List<LatLng>routePoints;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mMap =((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
    mMap.setMyLocationEnabled(true);
    mLocationClient = new LocationClient(this,this, this);
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setPriority(mLocationRequest.PRIORITY_HIGH_ACCURACY);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public void onConnected(Bundle dataBundle) {

    Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
    Location location = mLocationClient.getLastLocation();
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    routePoints.add(latLng);
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17);
    mMap.animateCamera(cameraUpdate);

}

@Override
public void onDisconnected() {

    Toast.makeText(this, "Disconnected. Please re-connect.",
            Toast.LENGTH_SHORT).show();

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

public void onStart(){
    super.onStart();
    mLocationClient.connect();
}

public void onStop(){
    mLocationClient.disconnect();
    super.onStop();
}

public void activate(OnLocationChangedListener listener){
    mListener = listener;
}

public void deactivate(){
    mListener = null;
}

@Override
public void onLocationChanged(Location location) {

    if(mListener != null){
        mListener.onLocationChanged(location);
    }

    LatLng mapPoint = new LatLng(location.getLatitude(), location.getLongitude());
    routePoints.add(mapPoint);
    Polyline route = mMap.addPolyline(new PolylineOptions());
    route.setPoints(routePoints);


}   
@Override
public void onProviderDisabled(String arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    // TODO Auto-generated method stub

}
}

ANDROIDMANIFEST_XML

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.google_maps_test"
android:versionCode="1"
android:versionName="1.0" >

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission     android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.google_maps_test.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="AIzaSyCOqSOYCyR-0bji10qcHa1WByfGoW-2ZsU"/>
</application>

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true"/>

</manifest>

当我运行这个应用程序时,它由于 OnLocationChanged 方法中的空指针异常而崩溃。

提前感谢您的帮助!

4

2 回答 2

3

对于任何想知道该错误的人,我发现 routePoints 从未初始化。

于 2016-02-28T19:59:19.693 回答
1

你可以试试这个:它修复了我的应用程序在尝试接收我的位置时出现的错误

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            Criteria criteria = new Criteria();

            Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
            if (location != null)
            {
                map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                        new LatLng(location.getLatitude(), location.getLongitude()), 13));

                CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
                .zoom(17)                   // Sets the zoom
                .bearing(90)                // Sets the orientation of the camera to east
                .tilt(40)                   // Sets the tilt of the camera to 30 degrees
                .build();                   // Creates a CameraPosition from the builder
            map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

            }
于 2014-01-11T21:36:15.623 回答