Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在android上通过移动获取实时地理位置(如谷歌地图)_Android_Google Maps_Gps_Geolocation_Latitude Longitude - Fatal编程技术网

如何在android上通过移动获取实时地理位置(如谷歌地图)

如何在android上通过移动获取实时地理位置(如谷歌地图),android,google-maps,gps,geolocation,latitude-longitude,Android,Google Maps,Gps,Geolocation,Latitude Longitude,我是android新手,我正在创建一个基于GPS的应用程序。所以我已经在我的应用程序上实现了谷歌地图和定位点标识符,但它只需要我第一次尝试地理定位,当我移动它时,它不会得到更新。请帮我解决这个问题。多谢各位 package com.android.locationtracker; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java

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


            }

        }



    }
package com.android.locationtracker;
导入java.util.ArrayList;
导入java.util.HashMap;
导入java.util.List;
导入java.util.Map;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.annotation.SuppressLint;
导入android.app.Activity;
导入android.app.ProgressDialog;
导入android.content.Context;
导入android.content.SharedReferences;
导入android.graphics.Color;
导入android.location.location;
导入android.location.LocationListener;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.widget.EditText;
导入android.widget.LinearLayout;
导入android.widget.Toast;
导入com.android.app.AppConst;
导入com.android.app.AppController;
导入com.android.common.GPSTracker;
导入com.android.volley.Response;
导入com.android.volley.VolleyError;
导入com.android.volley.VolleyLog;
导入com.android.volley.Request.Method;
导入com.android.volley.toolbox.JsonArrayRequest;
导入com.android.volley.toolbox.JsonObjectRequest;
导入com.google.android.gms.maps.CameraUpdateFactory;
导入com.google.android.gms.maps.GoogleMap;
导入com.google.android.gms.maps.MapFragment;
导入com.google.android.gms.maps.SupportMapFragment;
导入com.google.android.gms.maps.model.BitmapDescriptorFactory;
导入com.google.android.gms.maps.model.LatLng;
导入com.google.android.gms.maps.model.Marker;
导入com.google.android.gms.maps.model.MarkerOptions;
导入com.google.android.gms.maps.model.PolylineOptions;
公共类NearByActivity扩展了活动{
私有静态最终字符串TAG=“error”;
私人谷歌地图谷歌地图;
私有静态字符串URL=AppConst.GEOMETRY;
私有静态字符串URL_UPDATE=AppConst.GEOMETRY_UPDATE;
私有字符串jsonResponse;
私人对话;
全球定位系统;
双纬度;
双长;
字符串id;
字符串类型;
列表标记列表=新的ArrayList();
标记;
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.Nearned_活动);
试一试{
//装载图
initilizeMap();
googleMap.setMapType(googleMap.MAP\u TYPE\u NORMAL);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setRotategestureEnabled(true);
}捕获(例外e){
e、 printStackTrace();
}
gps=新的GPSTracker(本);
if(gps.canGetLocation()){
纬度=gps.getLatitude();
longtudent=gps.getlongtudent();
}否则{
gps.showSettingAllerts();
}
新建LoadGeo().execute();
}
私有void initilizeMap(){
试一试{
if(googleMap==null){
googleMap=((MapFragment)getFragmentManager()
.findFragmentById(R.id.map)).getMap();
//检查是否成功创建映射
if(googleMap==null){
Toast.makeText(getApplicationContext(),
“抱歉!无法创建地图”,Toast.LENGTH\u SHORT)
.show();
}
}
}捕获(例外e){
e、 printStackTrace();
}
}
@凌驾
恢复时公开作废(){
super.onResume();
initilizeMap();
}
私有void hidePDialog(){
如果(pDialog!=null){
pDialog.disclose();
pDialog=null;
}
}
私有类LoadGeo扩展异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=新建进度对话框(NearByActivity.this);
设置消息(“加载…”);
pDialog.show();
//
}
@凌驾
受保护的Void doInBackground(Void…arg0){
SharedReferences prefs=GetSharedReferences(“ConetText”,
上下文。模式(私人);
id=prefs.getString(“userid”,null);
type=prefs.getString(“persontype”,null);
Map params=新的HashMap();
参数put(“userid”,id);
参数put(“用户类型”,类型);
参数put(“lat”,String.valueOf(纬度));
参数put(“lng”,字符串值of(长度));
JsonObjectRequest req=新的JsonObjectRequest(URL\U更新,
新JSONObject(参数),
新的Response.Listener(){
@凌驾
公共void onResponse(JSONObject响应){
试一试{
Log.d(“地图”、“味精”);
VolleyLog.v(“响应:%n%s”,
响应。toString(4));
}捕获(JSONException e){
e、 printStackTrace();
}
}
if (gps.canGetLocation()) {
                latitude = gps.getLatitude();
                longtitude = gps.getLongtitude();
            } else {
                gps.showSettingAllerts();
            }

            new LoadGeo().execute();
@Override
public void onLocationChanged(Location location) {
//smth like this
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongtitude()), 17));  
}
private void requestLocation(Context context, int frequency) //frequency in mins
{
    LocationMgr loc_mgr = new LocationMgr(context);
    loc_mgr.requestLocationUpdates(frequency);
}
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();

}

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