使用Android版Google Maps API实时动态跟踪路线 [英] Dynamically tracing a route in real time using Google Maps API for Android

查看:108
本文介绍了使用Android版Google Maps API实时动态跟踪路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Android开发非常陌生,我正在尝试创建一个应用程序,该应用程序将在行走时使用地图叠加层来跟踪路线.我已经能够启动并运行该地图,并且可以显示它的运动,但是我对如何显示在地图上所走的路线一无所知.我认为我需要使用折线来执行此操作,并且我尝试设置一个List,然后从该List绘制线,但是我不确定这是否是合适的逻辑.任何帮助将不胜感激.

I am very new to Android development, and I am trying to create an app which will trace a route using a map overlay as I walk. I have been able to get the map up and running, and can get it to show my movement, but I am lost as to how to show the route taken on the map. I figure I need to use a polyline to do so, and I have tried to set up a List, and then to draw the line from that List, but I'm not sure if this is the appropriate logic to use. Any help would definitely be appreciated.

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

Here is the code I have so far:

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方法中的Null Pointer异常而崩溃.

When I run this app, it crashes due to a Null Pointer Exception in the OnLocationChanged method.

在此先感谢您的帮助!

推荐答案

您可以尝试以下方法:它在尝试接收我的位置时修复了我的应用程序中的错误

You could try this : It fixed an error at my application when trying to receive my location

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

            }

这篇关于使用Android版Google Maps API实时动态跟踪路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆