【问题标题】:Android: Constantly Update Map With Coordinates from Web ServiceAndroid:使用来自 Web 服务的坐标不断更新地图
【发布时间】:2012-04-29 04:32:05
【问题描述】:

您好,我正在编写一个使用来自网络服务器的坐标的应用程序。我知道如何从网络服务中检索坐标,但是一旦我得到它们,我怎么能不断地在地图上显示它们。有点像位置监听器在位置管理器的位置更改时更新地图上的点。我想不断更新我从网络服务收到的积分。 这是通过服务完成的吗?如果有怎么办?

        public class GeoUpdateHandler implements LocationListener {  

        @Override  
        public void onLocationChanged(Location location) {  
            ...
                GeoPoint point = new GeoPoint(lat, lng);  
            createMarker();  
            mapController.animateTo(point); // mapController.setCenter(point);  
        }  

更新:Createmarker 的代码

private void createMarker() {  
        GeoPoint p = mapView.getMapCenter();  
        OverlayItem overlayitem = new OverlayItem(p, "", "");  
        itemizedoverlay.addOverlay(overlayitem);  
        mapView.getOverlays().add(itemizedoverlay);  
    }  

更新:从 web 服务获取坐标的代码...

HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(".../android/serverFile.php");
        JSONObject json = new JSONObject();
        try {
            JSONArray postjson=new JSONArray();
            postjson.put(json);
            // Execute HTTP Post Request
            System.out.print(json);
            HttpResponse response = httpclient.execute(httppost);
            // for JSON:
            if(response != null)
            {
                InputStream is = response.getEntity().getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();
                String line = null;
                try {
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                String jsonStr = sb.toString();
                JSONObject jsonObj = new JSONObject(jsonStr);
                String longitudecord = jsonObj.getString("lon");
                String latitudecord = jsonObj.getString("lat");

}

用定时器更新:

public void startService(){
    timer.scheduleAtFixedRate(new TimerTask(){
        @Override
        public void run() {
                 //Call the method that contacts the server and  
                 //adds the coordinates to a list. Get those values from the list.  
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.kre8tiveinspired.com/android/serverFile.php");
            JSONObject json = new JSONObject();

            try {
                // JSON data:
                JSONArray postjson=new JSONArray();
                postjson.put(json);
                // Execute HTTP Post Request
                System.out.print(json);
                HttpResponse response = httpclient.execute(httppost);
                // for JSON:
                if(response != null)
                {
                    InputStream is = response.getEntity().getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    try {
                        while ((line = reader.readLine()) != null) {
                            sb.append(line + "\n");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    String jsonStr = sb.toString();
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    // grabbing the menu object 
                    String longitudecord = jsonObj.getString("lon");
                    String latitudecord = jsonObj.getString("lat");
                    latcord = latitudecord;
                    loncord = longitudecord;
                }

            }catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
            } catch (IOException e) {
                // TODO Auto-generated catch block
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                 Handler handler = new Handler();
                 handler.post(new Runnable(){  
                       public void run(){

                        double aDouble = Double.parseDouble(loncord);
                    double bDouble = Double.parseDouble(latcord);

                    int lat = (int) (aDouble * 1E6);  
                        int lng = (int) (bDouble * 1E6);  
                        GeoPoint point = new GeoPoint(lat, lng);  
                        createMarker();  
                        mapController.animateTo(point); // mapController.setCenter(point);
                            //add the overlays to the map
                            // and call invalidate for the mapview.
                             mapView.invalidate();

                       }
                 });
            }

    }, 0, 1000); // Here im calling the timer every 10 seconds

【问题讨论】:

  • createMarker() 的代码;
  • @Agarwal 刚刚用 createMarker(); 的代码更新了问题。

标签: android android-service


【解决方案1】:

你可以做的是使用timer 来填充地图。基本上,您可以使用一种方法来联系服务器,获取坐标并将它们添加到数组列表中。现在可以从计时器内部调用此方法(可以每隔几秒运行一次,具体取决于您的需要)。此外,在这个计时器类中,您可以重新填充地图。一些代码:

timer=new Timer();  // Refresh map via timer task.
    timer.scheduleAtFixedRate(new TimerTask(){
        @Override
        public void run() {
                 //Call the method that contacts the server and  
                 //adds the coordinates to a list. Get those values from the list.  
                 Handler handler = new Handler();
                 handler.post(new Runnable(){  
                       public void run(){
                            //add the overlays to the map
                            // and call invalidate for the mapview.
                       }
                 });
            }

    }, 0, 10000); // Here im calling the timer every 10 seconds

如果您想查看使用此想法的示例项目,请前往here,并查看onResume() 中的计时器。它使用另一个名为FetchParse 的类来联系服务器并获取更新的坐标列表。

【讨论】:

  • 另外,不要忘记在计时器内重新填充地图之前清除地图上的所有叠加层。
  • 谢谢,这听起来很理想。我更新了我最初的问题。我粘贴了从 web 服务获取字符串的代码,只是为了检查它是否有字。我将来可以制作一个单独的方法。但什么都没有发生。在粘贴其他代码之前,我什至每 10 秒弹出一次祝酒词。我不知道为什么?
  • 所以吐司不是每 10 秒弹出一次吗?您是否将吐司放入处理程序中?
  • 你确定startService()被调用了吗?在startService() 中添加一个日志语句作为第一行并检查它是否有效。
  • 该错误意味着您正在尝试在 run() 方法之外执行与 UI 相关的操作。确保所有与 UI 相关的代码都在 run() 方法中。
【解决方案2】:
GeoPoint p = mapView.getProjection().fromPixels((int) event.getX(),(int) event.getY());
Drawable srcdrawable = getApplicationContext().getResources().getDrawable(R.drawable.pin_blue);
CustomItemizedOverlay srcitemizedOverlay = new CustomItemizedOverlay(srcdrawable, getApplicationContext());
OverlayItem srcoverlayitem = new OverlayItem(p, "Hello!", "This is your Location.");
srcitemizedOverlay.addOverlay(srcoverlayitem);
mapView.getOverlays().clear();
mapView.getOverlays().add(srcitemizedOverlay);

在创建标记中尝试此代码

【讨论】:

  • 感谢代码,我更新了我的代码以显示我从网络服务中读取...最后我有两个字符串 longitudecord 和 latitude cord...你给我的代码怎么样不断地从网络服务中读取这些字符串?大概每 6-10 秒一次?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多