【问题标题】:Update marker location on the map without opening and closing Activity无需打开和关闭 Activity 即可更新地图上的标记位置
【发布时间】:2017-08-23 13:32:46
【问题描述】:

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

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

在下面的这段代码中,显示了来自 Mysql 银行使用 json 的标记的映射。有什么建议吗?

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

}

【问题讨论】:

    标签: android mysql json


    【解决方案1】:

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

    但是我会建议您每次(每 10 秒)发出网络请求不是一个好主意。用户可能一小时后就没有改变那里的位置。所以它的 API 调用毫无价值。因此,如果您使用实时数据库(如 Firebase 实时数据库)会更好。并在您的数据库值更新时收听您的数据更改,它会通知您。 Firebase Real time DB Doc reference

    【讨论】:

      【解决方案2】:

      如果您想在某个时间间隔内更新您的地图,而无需打开和关闭您的活动。您应该将您的逻辑从 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);
          }
      }
      

      【讨论】:

      • 我无法将此 GetMapData () 和 UpdateMap () 放入我的代码中。
      • @raiomobile 这些是您应该创建的方法。我不知道你为什么不适合他们。我通过复制你的一些逻辑来更新我的答案。希望现在更清楚了。您还应该考虑 shahid17june 所说的关于网络请求和实时数据库的内容。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-15
      相关资源
      最近更新 更多