更新地图上的标记位置,而无需打开和关闭活动

时间:2017-08-23 13:32:46

标签: android mysql json

我有一个关于如何做一个我认为简单的项目的问题。 接下来我有一个应用程序,将手机的位置发送10秒到MySql,好吧。

但我现在只需要在另一个应用程序中显示这些用户在映射的10秒内的当前位置,而无需打开和关闭活动。

在下面的代码中,显示了使用json来自Mysql库的标记的映射。有什么提示吗?

   public class MainActivity extends FragmentActivity {

    // Google Map
    private GoogleMap googleMap;

    // Latitude & Longitude
    private Double Latitude = 0.00;
    private Double Longitude = 0.00;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //*** Permission StrictMode
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        ArrayList<HashMap<String, String>> location = null;
        String url = "http://192.168.1.202/android/getLatLon.php";
        try {

            JSONArray data = new JSONArray(getHttpGet(url));

            location = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> map;

            for(int i = 0; i < data.length(); i++){
                JSONObject c = data.getJSONObject(i);

                map = new HashMap<String, String>();
                map.put("LocationID", c.getString("LocationID"));
                map.put("Latitude", c.getString("Latitude"));
                map.put("Longitude", c.getString("Longitude"));
                map.put("LocationName", c.getString("LocationName"));
                location.add(map);

            }           

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        // *** Display Google Map
        googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap)).getMap();

        // *** Focus & Zoom
        Latitude = Double.parseDouble(location.get(0).get("Latitude").toString());
        Longitude = Double.parseDouble(location.get(0).get("Longitude").toString());
        LatLng coordinate = new LatLng(Latitude, Longitude);
        googleMap.setMapType(com.google.android.gms.maps.GoogleMap.MAP_TYPE_HYBRID);
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 17));

        // *** Marker (Loop)
        for (int i = 0; i < location.size(); i++) {
            Latitude = Double.parseDouble(location.get(i).get("Latitude").toString());
            Longitude = Double.parseDouble(location.get(i).get("Longitude").toString());
            String name = location.get(i).get("LocationName").toString();
            MarkerOptions marker = new MarkerOptions().position(new LatLng(Latitude, Longitude)).title(name);
            googleMap.addMarker(marker);
        }

    }

    public static String getHttpGet(String url) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) { // Download OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download result..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();
    }

}

2 个答案:

答案 0 :(得分:1)

您可以使用 COUNTDOWN TIMER COUNT DOWN TIMER EXAMPLE,这样每10秒就会发出一次网络请求,您将获得更新后的值。 并且您可以使用新的 LATITUDE,LONGITUDE 值更新标记。并且请记住仅在第一个网络请求之后添加标记 不需要添加标记只需要更改标记位置。 。how to change marker position

但是我会推荐你每次(每10秒)发出一次网络请求并不是一个好主意。自一小时以来,用户可能无法更改位置。因此,它无需API调用。所以如果你使用REAL TIME DATABASE(比如Firebase实时数据库)会更好。并在您的数据库值更新时监听您的数据更改,它将通知您。 Firebase Real time DB Doc reference

答案 1 :(得分:0)

如果您想在某段时间内更新地图而无需打开和关闭活动。您应该从onCreate()方法移动逻辑。

Thread myLoopingThread = new Thread(new Runnable() {
    @Override
    public void run() {
        while(!Thread.currentThread().isInterrupted()){
            final String result = getHttpGet("http://192.168.1.202/android/getLatLon.php");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    UpdateMap(result);
                }
            });
            Thread.sleep(timeToSleep);
        }
    }
});

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //do other stuff..
    myLoopingThread.start();
}
//also we should stop the thread when its not needed anymore
@Override
 protected void onDestroy(){
    myLoopingThread.interrupt();
    super.onDestroy();
}  
void UpdateMap(String input){
    ArrayList<HashMap<String, String>> location = null;

    try {

        JSONArray data = new JSONArray(input);

        location = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> map;

        for(int i = 0; i < data.length(); i++){
            JSONObject c = data.getJSONObject(i);

            map = new HashMap<String, String>();
            map.put("LocationID", c.getString("LocationID"));
            map.put("Latitude", c.getString("Latitude"));
            map.put("Longitude", c.getString("Longitude"));
            map.put("LocationName", c.getString("LocationName"));
            location.add(map);

        }           

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    // *** Display Google Map
    googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap)).getMap();

    // *** Focus & Zoom
    Latitude = Double.parseDouble(location.get(0).get("Latitude").toString());
    Longitude = Double.parseDouble(location.get(0).get("Longitude").toString());
    LatLng coordinate = new LatLng(Latitude, Longitude);
    googleMap.setMapType(com.google.android.gms.maps.GoogleMap.MAP_TYPE_HYBRID);
    googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 17));

    // *** Marker (Loop)
    for (int i = 0; i < location.size(); i++) {
        Latitude = Double.parseDouble(location.get(i).get("Latitude").toString());
        Longitude = Double.parseDouble(location.get(i).get("Longitude").toString());
        String name = location.get(i).get("LocationName").toString();
        MarkerOptions marker = new MarkerOptions().position(new LatLng(Latitude, Longitude)).title(name);
        googleMap.addMarker(marker);
    }
}