测量距离用的GeoPoint走去,显示用户的距离 [英] Measure distance walked with GeoPoint and displaying distance to user

查看:300
本文介绍了测量距离用的GeoPoint走去,显示用户的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用我想使它可以计算一个人行走的距离。要做到这一点,我已经创建了一个LocationHelper类,应该让我当前的GeoPoint每30秒或10米。我已经有一个返回两个GeoPoints,我知道的作品,因为我已经在previous项目中使用它之间米的距离的方法。我也有叫WalkActivity,我调用该方法getDistance的()在LocationHelper并且在每30秒计时器的帮助更新TextView中显示它的活动。请参见下面code。

当我跑我的应用程序不显示任何内容。它说:你已经走0.0米不管我走多远。我没有得到任何错误消息。你觉得我做错了什么?我已搜查,看着无数的例子,但发现没有人能告诉我什么是错在这里。

我希望这不是一个愚蠢的问题,任何帮助是值得欢迎的:)

 封装控制器;进口com.google.android.maps.GeoPoint;
进口android.content.Context;
进口android.location.Location;
进口android.location.LocationListener;
进口android.location.LocationManager;
进口android.os.Bundle;/ **
 *位置辅助类处理该位置管理和位置监听器的创建。
 *
 * /
公共类LocationHelper {    私人双距离= 0;
    GeoPoint的geoPointA;
    GeoPoint的geoPointB;    //位置管理器和监听
    私人的LocationManager的LocationManager;
    私人MyLocationListener LocationListener的;    / **
     *构造LocationHelper
     *
     * @参数方面 - 主叫活动的背景。
     * /
    公共LocationHelper(上下文的背景下){        //设置位置管理器
        的LocationManager =(的LocationManager)context.getSystemService(Context.LOCATION_SERVICE);        //创建位置监听器
        LocationListener的=新MyLocationListener();        //设置为当GPS获取的锁,我们接收数据的回调
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,30000,10,LocationListener的);    }    / **
     *接收从位置管理的通知时,他们发送。
     *
     * /
    公共类MyLocationListener实现LocationListener的{
        / **
         *调用时的位置服务报告中的位置发生变化
         * /
        公共无效onLocationChanged(地点){            如果(geoPointB == NULL){
                geoPointB =新的GeoPoint((int)的location.getLatitude(),(INT)location.getLongitude());
            }            //获取当前的GeoPoint。
            geoPointA =新的GeoPoint((int)的location.getLatitude(),(INT)location.getLongitude());            //计算在米的距离
            距离=距离+ nu.placebo.whatsup.util.Geodetics.distance(geoPointA,geoPointB);            //使当前的GeoPoint的previous的GeoPoint
            geoPointB = geoPointA;        }        //当供应商被禁用称为
        公共无效onProviderDisabled(字符串提供商){}
        //当启用提供商称为
        公共无效onProviderEnabled(字符串提供商){}
        //当提供改变状态称为
        公共无效onStatusChanged(字符串提供商,INT地位,捆绑演员){}
    }    / **
     *从位置服务停止更新。
     * /
    公共无效killLocationServices(){
        locationManager.removeUpdates(LocationListener的);
    }    / **
     *获取距离
     *
     * @返回 - 当前远处走去。
     * /
    公共双getDistance的(){
        返回距离;
    }    / **
     *检查的地点被发现呢。
     * @返回 - 如果一个位置已经被获取真。否则为false。
     * /
    公共布尔gpsEnabled(){
        返回locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }
}包edu.chl.dat255.sofiase.readyforapet;进口java.util.Timer中;
进口java.util.TimerTask中;
进口Controller.LocationHelper;
进口android.app.Activity;
进口android.app.AlertDialog;
进口android.content.DialogInterface;
进口android.content.Intent;
进口android.os.Bundle;
进口android.os.Handler;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.Button;
进口android.widget.TextView;
进口android.widget.Toast;公共类WalkActivity延伸活动{    私人TextView的displayDistance;
    私人INT延迟= 0;
    私人诠释周期= 30000;
    私人定时器定时器;
    处理程序处理程序=新的处理程序();    私人LocationHelper位置;    / **
     *在创建方法
     *
     * @参数savedInstanceState - 包
     * /
    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.walkactivity);
        位置=新LocationHelper(本);        //检查是否启用了GPS,否则如果我们想在用户启动GPS。
        如果(location.gpsEnabled()){
            Toast.makeText(这一点,启用GPS在你的devide,Toast.LENGTH_SHORT).show();
        }
        其他{
            showGPSDisabledAlert();
        }        按钮startWalking =(按钮)findViewById(R.id.startwalking);
        startWalking.setOnClickListener(新OnClickListener(){            / **
             *方法的onClick为开始行走按钮
             *
             * @参数v - 输出查看
             * /
            公共无效的onClick(视图v){                尝试{
                    定时器=新定时器();
                    timer.schedule(myTimerTask,延迟期);
                }
                赶上(例外五){
                    e.printStackTrace();
                }
            }
        }                );        按钮stopWalking =(按钮)findViewById(R.id.stopwalking);
        stopWalking.setOnClickListener(新OnClickListener(){            / **
             *方法的onClick为止损步行按钮
             *
             * @参数v - 输出查看
             * /
            公共无效的onClick(视图v){
                timer.cancel();
                location.killLocationServices();
                startActivity(新意图(WalkActivity.this,PetActivity.class));
            }
        }
                );    }
    TimerTask的myTimerTask =新的TimerTask(){        @覆盖
        公共无效的run(){
            handler.post(新的Runnable(){
                @覆盖
                公共无效的run(){
                    displayDistance =(的TextView)findViewById(R.id.distance);
                    displayDistance.setText(你走+ location.getDistance()+米那么远。);
                }
            });        }    };    / **
     *如果GPS被关闭,让用户要么选择启用GPS或取消。
     *
     * /
    私人无效showGPSDisabledAlert(){
        AlertDialog.Builder alertDialogBu​​ilder =新AlertDialog.Builder(本);
        alertDialogBu​​ilder.setMessage(GPS是您的设备上停用,要启用吗?)
        .setCancelable(假)
        .setPositiveButton(转到设置页面启用GPS,
                新DialogInterface.OnClickListener(){
            公共无效的onClick(DialogInterface对话,诠释的id){
                意图callGPSSettingIntent =新意图(
                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(callGPSSettingIntent);
            }
        });
        alertDialogBu​​ilder.setNegativeButton(取消,
                新DialogInterface.OnClickListener(){
            公共无效的onClick(DialogInterface对话,诠释的id){
                dialog.cancel();
            }
        });
        AlertDialog警报= alertDialogBu​​ilder.create();
        alert.show();
    }}


解决方案

在您的code的一个问题是,当你创建一个的GeoPoint 位置 onLocationChanged(地点)。无论 getLatitude() getLongitude()从类位置回报度,但为的GeoPoint 的构造函数微度。这可能会搞砸了你的距离计算的,因为你的的GeoPoint 坐标可能是,我们只能说,42度,这原来是0.0000042度的的GeoPoint

另外,你可以尝试打印的当前位置不知何故,通过调试监控器或通过吐司消息。这将在调试过程中有很大帮助,因为你可以看到你的纬度/经度变化和调试从那里。

请注意:我会建议更新到地图V2,他们改变了很多类,并添加经纬度这使得事情更容易理解:)

In my app I am trying to make it possible to calculate the distance a person walks. To do this I have created a LocationHelper class that should get me the current GeoPoint every 30 seconds or 10 meters. I already have a method that returns the distance in meters between two GeoPoints that I know works, because I have used it in a previous project. I also have an Activity called WalkActivity where I call the method getDistance() in LocationHelper and display it in a TextView that is updated every 30 seconds with help of a timer. See code below.

When I run my app nothing is displayed. It says "You have walked 0.0 meters" no matter how far I walk. I get no error messages. What do you think I am doing wrong? I have searched and looked at numerous examples but found none that can tell me what is wrong here.

I hope this is not a stupid question, any help is welcome :)

package Controller;

import com.google.android.maps.GeoPoint;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

/**
 * Location Helper Class that handles creation of the Location Manager and Location Listener.
 * 
 */
public class LocationHelper{

    private double distance = 0;
    GeoPoint geoPointA;
    GeoPoint geoPointB;

    //location manager and listener
    private LocationManager locationManager;
    private MyLocationListener locationListener;

    /**
     * Constructor for LocationHelper
     * 
     * @param context - The context of the calling activity.
     */
    public LocationHelper(Context context){

        //setup the location manager
        locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);

        //create the location listener
        locationListener = new MyLocationListener();

        //setup a callback for when the GPS gets a lock and we receive data
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 10, locationListener);

    }

    /**
     * Receiving notifications from the Location Manager when they are sent.
     *
     */
    public class MyLocationListener implements LocationListener {


        /**
         * called when the location service reports a change in location
         */
        public void onLocationChanged(Location location) {

            if (geoPointB == null){
                geoPointB = new GeoPoint((int) location.getLatitude(), (int) location.getLongitude());
            }

            //Getting the current GeoPoint.
            geoPointA = new GeoPoint((int) location.getLatitude(), (int) location.getLongitude());

            //Calculating the distance in meters
            distance = distance + nu.placebo.whatsup.util.Geodetics.distance(geoPointA, geoPointB);

            //Making current GeoPoint the previous GeoPoint
            geoPointB = geoPointA;

        }

        //called when the provider is disabled
        public void onProviderDisabled(String provider) {}
        //called when the provider is enabled
        public void onProviderEnabled(String provider) {}
        //called when the provider changes state
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    }

    /**
     * Stop updates from the Location Service.
     */
    public void killLocationServices(){
        locationManager.removeUpdates(locationListener);
    }

    /**
     * Get Distance 
     *
     * @return - The current distance walked.
     */
    public double getDistance(){
        return distance;
    }

    /**
     * Check if a location has been found yet.
     * @return - True if a location has been acquired. False otherwise.
     */
    public Boolean gpsEnabled(){
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }   
}

package edu.chl.dat255.sofiase.readyforapet;

import java.util.Timer;
import java.util.TimerTask;
import Controller.LocationHelper;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class WalkActivity extends Activity{

    private TextView displayDistance;
    private int delay = 0;
    private int period = 30000;
    private Timer timer;
    Handler handler = new Handler();

    private LocationHelper location;

    /**
     * On Create method
     * 
     * @param savedInstanceState - bundle
     */
    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.walkactivity);
        location = new LocationHelper(this);

        //Checking if the GPS is enabled, else let the user start GPS if wanted.
        if (location.gpsEnabled()){
            Toast.makeText(this, "GPS is Enabled on your devide", Toast.LENGTH_SHORT).show();
        }
        else{
            showGPSDisabledAlert();
        }

        Button startWalking = (Button) findViewById(R.id.startwalking);
        startWalking.setOnClickListener(new OnClickListener() {

            /**
             * Method onClick for the start walking button
             * 
             * @param v - View
             */
            public void onClick (View v){

                try{
                    timer = new Timer();
                    timer.schedule(myTimerTask, delay, period);
                } 
                catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

                );

        Button stopWalking = (Button) findViewById(R.id.stopwalking);
        stopWalking.setOnClickListener(new OnClickListener() {

            /**
             * Method onClick for the stop walking button
             * 
             * @param v - View
             */
            public void onClick (View v){
                timer.cancel();
                location.killLocationServices();
                startActivity(new Intent(WalkActivity.this, PetActivity.class));
            }
        }
                );

    }


    TimerTask myTimerTask = new TimerTask() {

        @Override
        public void run() {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    displayDistance = (TextView) findViewById(R.id.distance);
                    displayDistance.setText("You have walked " + location.getDistance() + " meters so far.");
                }
            });

        }

    };

    /**
     * If GPS is turned off, lets the user either choose to enable GPS or cancel.
     * 
     */
    private void showGPSDisabledAlert(){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("GPS is disabled on your device. Would you like to enable it?")
        .setCancelable(false)
        .setPositiveButton("Go to Settings Page To Enable GPS",
                new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                Intent callGPSSettingIntent = new Intent(
                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(callGPSSettingIntent);
            }
        });
        alertDialogBuilder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                dialog.cancel();
            }
        });
        AlertDialog alert = alertDialogBuilder.create();
        alert.show();
    }

}

解决方案

One problem in your code is when you create a GeoPoint from a Location in onLocationChanged(Location location). Both getLatitude() and getLongitude() from the class Location return degrees, but the constructor for GeoPoint takes microdegrees. This might be screwing up your distance calculation because your GeoPoint coordinates could be, let's just say, 42 degrees, which turns out to be .0000042 degrees in the GeoPoint.

Also, you might try printing the current location somehow, through the debug monitor or through a Toast message. This will greatly help in the debugging process, as you can see your Lat/Long changing and debug from there.

Note: I would recommend updating to Maps v2, they changed a lot of classes and added LatLng which makes things easier to understand :)

这篇关于测量距离用的GeoPoint走去,显示用户的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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