【问题标题】:how to get real time geolocation with movings(like google maps) on android with movings如何在 android 上通过移动获取实时地理定位(如谷歌地图)
【发布时间】:2015-09-01 05:01:22
【问题描述】:

我是 android 新手,我正在创建一个基于 GPS 的应用程序。所以我在我的应用程序上实现了谷歌地图和位置点标识符,但它只需要我第一次尝试地理位置,当我移动它时它不会得到更新。请帮我解决这个问题。谢谢你。

    package com.android.locationtracker;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.SharedPreferences;
    import android.graphics.Color;
    import android.location.Location;
    import android.location.LocationListener;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.EditText;
    import android.widget.LinearLayout;
    import android.widget.Toast;

    import com.android.app.AppConst;
    import com.android.app.AppController;
    import com.android.common.GPSTracker;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.VolleyLog;
    import com.android.volley.Request.Method;
    import com.android.volley.toolbox.JsonArrayRequest;
    import com.android.volley.toolbox.JsonObjectRequest;
    import com.google.android.gms.maps.CameraUpdateFactory;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.MapFragment;
    import com.google.android.gms.maps.SupportMapFragment;
    import com.google.android.gms.maps.model.BitmapDescriptorFactory;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.Marker;
    import com.google.android.gms.maps.model.MarkerOptions;
    import com.google.android.gms.maps.model.PolylineOptions;

    public class NearByActivity extends Activity {

        private static final String TAG = "error";
        private GoogleMap googleMap;
        private static String URL = AppConst.GEOMETRY;
        private static String URL_UPDATE = AppConst.GEOMETRY_UPDATE;
        private String jsonResponse;
        private ProgressDialog pDialog;
        GPSTracker gps;
        double latitude;
        double longtitude;
        String id;
        String type;
        List<Marker> markerList = new ArrayList<Marker>();
        Marker marker;

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.nearby_activity);

            try {
                // Loading map
                initilizeMap();
                googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

                googleMap.getUiSettings().setCompassEnabled(true);
                googleMap.getUiSettings().setRotateGesturesEnabled(true);

            } catch (Exception e) {
                e.printStackTrace();
            }

            gps = new GPSTracker(this);
            if (gps.canGetLocation()) {
                latitude = gps.getLatitude();
                longtitude = gps.getLongtitude();
            } else {
                gps.showSettingAllerts();
            }

            new LoadGeo().execute();


        }

        private void initilizeMap() {
            try {

                if (googleMap == null) {
                    googleMap = ((MapFragment) getFragmentManager()
                            .findFragmentById(R.id.map)).getMap();

                    // check if map is created successfully or not
                    if (googleMap == null) {
                        Toast.makeText(getApplicationContext(),
                                "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                                .show();
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onResume() {
            super.onResume();
            initilizeMap();
        }

        private void hidePDialog() {
            if (pDialog != null) {
                pDialog.dismiss();
                pDialog = null;
            }
        }

        private class LoadGeo extends AsyncTask<Void, Void, Void> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(NearByActivity.this);
                pDialog.setMessage("Loading...");
                pDialog.show();
                //
            }

            @Override
            protected Void doInBackground(Void... arg0) {
                SharedPreferences prefs = getSharedPreferences("conetext",
                        Context.MODE_PRIVATE);
                id = prefs.getString("userid", null);
                type = prefs.getString("persontype", null);
                Map<String, String> params = new HashMap<String, String>();
                params.put("userid", id);
                params.put("usertype", type);
                params.put("lat", String.valueOf(latitude));
                params.put("lng", String.valueOf(longtitude));

                JsonObjectRequest req = new JsonObjectRequest(URL_UPDATE,
                        new JSONObject(params),
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                try {
                                    Log.d("map", "msg");
                                    VolleyLog.v("Response:%n %s",
                                            response.toString(4));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                VolleyLog.e("Error: ", error.getMessage());
                            }
                        });

                // add the request object to the queue to be executed
                AppController.getInstance().addToRequestQueue(req);

                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                Thread thread = new Thread() {
                    @Override
                    public void run() {

                        try {
                            while (true) {
                                sleep(1000);

                                JsonArrayRequest req = new JsonArrayRequest(URL,
                                        new Response.Listener<JSONArray>() {
                                            @Override
                                            public void onResponse(
                                                    JSONArray response) {
                                                Log.d(TAG, response.toString());
                                                hidePDialog();
                                                try {
                                                    markerList.clear();
                                                    googleMap.clear();

                                                    for (int i = 0; i < response
                                                            .length(); i++) {

                                                        JSONObject geo = (JSONObject) response
                                                                .get(i);

                                                        String usertype = geo
                                                                .getString("UserType");
                                                        MarkerOptions markerblue = new MarkerOptions();
                                                        markerblue.icon(BitmapDescriptorFactory
                                                                .defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
                                                        markerblue.position(new LatLng(latitude, longtitude));
                                                        googleMap.addMarker(markerblue);
                                                        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
                                                                latitude, longtitude), 17));
                                                        if (usertype
                                                                .equals("driver")) {
                                                            double lat = geo
                                                                    .getDouble("Lat");
                                                            double lng = geo
                                                                    .getDouble("Lng");

                                                            MarkerOptions markerop = new MarkerOptions();

                                                            markerop.icon(BitmapDescriptorFactory
                                                                    .defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                                                            markerop.position(
                                                                    new LatLng(lat,
                                                                            lng))
                                                                    .draggable(true)
                                                                    .visible(true);

                                                            marker= googleMap
                                                                    .addMarker(markerop);
                                                            markerList.add(marker);
                                                        }

                                                    }


                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                    Toast.makeText(
                                                            getApplicationContext(),
                                                            "Error: "
                                                                    + e.getMessage(),
                                                            Toast.LENGTH_LONG)
                                                            .show();
                                                }

                                            }
                                        }, new Response.ErrorListener() {

                                            @Override
                                            public void onErrorResponse(
                                                    VolleyError error) {
                                                VolleyLog.d(
                                                        TAG,
                                                        "Error: "
                                                                + error.getMessage());
                                                Toast.makeText(
                                                        getApplicationContext(),
                                                        error.getMessage(),
                                                        Toast.LENGTH_SHORT).show();

                                            }
                                        });

                                // Adding request to request queue
                                AppController.getInstance().addToRequestQueue(req);
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                };

                thread.start();


            }

        }



    }

【问题讨论】:

    标签: android google-maps gps geolocation latitude-longitude


    【解决方案1】:

    需要注册LocationListener并实现方法

    @Override
    public void onLocationChanged(Location location) {
    //smth like this
    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
    new LatLng(location.getLatitude(), location.getLongtitude()), 17));  
    }
    

    详细信息在这里https://developer.android.com/training/location/receive-location-updates.html

    【讨论】:

    • 谢谢你的建议,你能给我一个例子吗?如何将此添加到我的?
    • @TaSh 这里是基本示例googlesample
    【解决方案2】:

    你需要在特定的时间间隔内执行这段代码

    if (gps.canGetLocation()) {
                    latitude = gps.getLatitude();
                    longtitude = gps.getLongtitude();
                } else {
                    gps.showSettingAllerts();
                }
    
                new LoadGeo().execute();
    

    我建议使用 Handler.postDelayed(Runnable,Interval) 方法来解决这个问题。

    【讨论】:

    • 感谢您的建议,能否给我一个代码示例?
    【解决方案3】:

    您可以使用定位服务。这是代码:

    通过给出所需的频率(以分钟为单位)调用此函数:

    private void requestLocation(Context context, int frequency) //frequency in mins
    {
        LocationMgr loc_mgr = new LocationMgr(context);
        loc_mgr.requestLocationUpdates(frequency);
    }
    

    这是 LocationMgr 类:

    public class LocationMgr implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
    {
    
    private final Context context;
    private GoogleApiClient googleApiClient;
    private boolean inProgress;
    public enum REQUEST_TYPE {START, STOP, LAST_KNOWN}
    private REQUEST_TYPE requestType;
    private Intent intent; 
    LocationRequest mLocationRequest;
    LocationListener ll;
    
    
    public LocationMgr(Context context) 
    {
        this.context = context;
        this.googleApiClient = new GoogleApiClient.Builder(context)
        .addApi(LocationServices.API)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .build();
        intent = new Intent(context, LocationService.class);
        inProgress = false;
    }
    
    @Override
    public void onConnectionFailed(ConnectionResult arg0) {
        inProgress = false;     
    }
    
    @Override
    public void onConnectionSuspended(int arg0) {
        googleApiClient.connect();  
    }
    
    @Override
    public void onConnected(Bundle connectionHint) {
        PendingIntent pendingIntent = PendingIntent.getService(context, 123, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    
    
        switch (requestType) 
        {
        case START :
            LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, mLocationRequest, pendingIntent);
            break;
    
        case STOP :
            LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, pendingIntent);
            break;
    
        case LAST_KNOWN :
            Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
            ll.onNewLocationUpdate(location);
            break;
    
        default :
            log.e("Unknown request type in onConnected().");
            break;
        }
    
        inProgress = false;
        googleApiClient.disconnect();
    
    }
    
    
    
    /**
     * 
     * @param frequency (minutes) minimum time interval between location updates
     */
    public void requestLocationUpdates(int frequency)
    {       
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(frequency * 60 * 1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setFastestInterval(1000);
        if (inProgress) 
        {
            log.e("A request is already underway");
            return;
        }
        inProgress = true;
        requestType = REQUEST_TYPE.START;
        googleApiClient.connect();  
    }
    
    public void removeContinuousUpdates()
    {
        if (inProgress) 
        {
            log.e("A request is already underway");
            return;
        }
        inProgress = true;
        requestType = REQUEST_TYPE.STOP;
        googleApiClient.connect();  
    }
    
    public void getLastKnownLocation(LocationListener ll)
    {
        this.ll = ll;
        if (inProgress) 
        {
            log.e("A request is already underway");
            return;
        }
        inProgress = true;
        requestType = REQUEST_TYPE.LAST_KNOWN;
        googleApiClient.connect();
    
    }
    
    }
    

    这是 LocationService 类:

    public class LocationService extends IntentService
    {
    
    public LocationService()
    {
        super("NOTIFICATION_SERVICE");
    }
    
    
    /**
     * Called when a new location update is available.
     */
    @Override
    protected void onHandleIntent(Intent intent)
    {       
        LocationListener ll = new LocationListener() 
        {
            @Override
            public void onNewLocationUpdate(Location location) 
            {
                // here you will get the latest location
            }
        };
    
        LocationMgr lm = new LocationMgr(getApplicationContext());
        lm.getLastKnownLocation(ll);
    }       
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-19
      • 2011-09-06
      相关资源
      最近更新 更多