【问题标题】:Refresh map markers on android with button使用按钮刷新android上的地图标记
【发布时间】:2016-05-12 20:57:41
【问题描述】:

我正在运行一个带有一些 json 数据的 Web 服务,我用这些数据在我的地图上制作标记(每小时更新一次)。我想在我的 android 地图上添加按钮,以便我将刷新标记数据。任何想法在不改变大部分结构的情况下?我应该在线程上做点什么吗?还是重新启动活动?

这是代码

public class MainActivity extends FragmentActivity {
private static final String LOG_TAG = "jsonmap";

private static final String SERVICE_URL = "http://7a27183e.ngrok.com";

public GoogleMap map;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(activity_maps);



}



@Override
protected void onResume() {
    super.onResume();
    setUpMapIfNeeded();
}

private void setUpMapIfNeeded() {
    if (map == null) {
        MapFragment mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map);
        map = mapFragment.getMap();
        if (map != null) {
            setUpMap();
           // new MarkerTask().execute();
        }
    }
}

private void setUpMap() {
    UiSettings settings = map.getUiSettings();
    settings.setZoomControlsEnabled(true);
    settings.setScrollGesturesEnabled(true);
    // Retrieve the city data from the web service
    // In a worker thread since it's a network operation.
    new Thread(new Runnable() {
        public void run() {
            try {
                retrieveAndAddCities();
            } catch (IOException e) {
                Log.e(LOG_TAG, "Cannot retrive cities", e);
                return;
            }
        }
    }).start();
}



protected void retrieveAndAddCities() throws IOException {
    HttpURLConnection conn = null;
    final StringBuilder json = new StringBuilder();
    try {
        // Connect to the web service
        URL url = new URL(SERVICE_URL);
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Read the JSON data into the StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            json.append(buff, 0, read);
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error connecting to service", e);
        throw new IOException("Error connecting to service", e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    // Create markers for the city data.
    // Must run this on the UI thread since it's a UI operation.
    runOnUiThread(new Runnable() {
        public void run() {
            try {

                createMarkersFromJson(json.toString());

            } catch (JSONException e) {
                Log.e(LOG_TAG, "Error processing JSON", e);
            }
        }
    });
}

void createMarkersFromJson(String json) throws JSONException {
    // De-serialize the JSON string into an array of city objects
    JSONArray jsonArray = new JSONArray(json);



    for (int i = 0; i < jsonArray.length(); i++) {
        // Create a marker for each city in the JSON data.
        //.title(jsonObj.getString("pollutant")+" "+jsonObj.getString("network"))
        // .snippet(Integer.toString(jsonObj.getInt("numeric_val")))
        //DATE!!
        JSONObject jsonObj = jsonArray.getJSONObject(i);

        map.addMarker(new MarkerOptions()
                        .title(jsonObj.getString("network") + "\n" + jsonObj.getString("date"))
                        .snippet(jsonObj.getString("pollutant") + "=" + jsonObj.getString("numeric_val"))

                        .position(new LatLng(
                                jsonObj.getDouble("x"),
                                jsonObj.getDouble("y")))
                        .icon(BitmapDescriptorFactory.defaultMarker(new Random().nextInt(360)))
        );


        map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

            @Override
            public View getInfoContents(Marker arg0) {
                return null;
            }

            @Override
            public View getInfoWindow(Marker arg0) {

                View v = getLayoutInflater().inflate(R.layout.customlayout, null);

                TextView tTitle = (TextView) v.findViewById(R.id.title);

                TextView tSnippet = (TextView) v.findViewById(R.id.snippet);

                tTitle.setText(arg0.getTitle());

                tSnippet.setText(arg0.getSnippet());

                return v;

            }
        });
    }



}

}

这是json结构:

https://gist.githubusercontent.com/anonymous/42af315ab003ab01764d/raw/79b6cf5451038bd2e35c376766e9ab44bd385a02/gistfile2.txt

还有截图:

http://imgur.com/WZNC9Oz

【问题讨论】:

    标签: android json google-maps google-maps-markers


    【解决方案1】:

    我在 ma​​p.addMarker() 行对名为 createMarkersFromJson() 的方法进行了一些修改。现在您可以使用 changeMarkerPosition() 来改变标记的位置。

    HashMap<String, Marker> markerHashMap = new HashMap<>();
    
    
    void changeMarkerPosition(String key, LatLng latLng) {
    markerHashMap.get(key).setPosition(latLng);
    }
    
    
    void createMarkersFromJson(String json) throws JSONException {
    // De-serialize the JSON string into an array of city objects
    JSONArray jsonArray = new JSONArray(json);
    
    
    
    for (int i = 0; i < jsonArray.length(); i++) {
        // Create a marker for each city in the JSON data.
        //.title(jsonObj.getString("pollutant")+" "+jsonObj.getString("network"))
        // .snippet(Integer.toString(jsonObj.getInt("numeric_val")))
        //DATE!!
        JSONObject jsonObj = jsonArray.getJSONObject(i);
    
        markerHashMap.put("key"+i,(map.addMarker(new MarkerOptions()
                        .title(jsonObj.getString("network") + "\n" + jsonObj.getString("date"))
                        .snippet(jsonObj.getString("pollutant") + "=" + jsonObj.getString("numeric_val"))
    
                        .position(new LatLng(
                                jsonObj.getDouble("x"),
                                jsonObj.getDouble("y")))
                        .icon(BitmapDescriptorFactory.defaultMarker(new Random().nextInt(360)))
        );)
    
    
        map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
    
            @Override
            public View getInfoContents(Marker arg0) {
                return null;
            }
    
            @Override
            public View getInfoWindow(Marker arg0) {
    
                View v = getLayoutInflater().inflate(R.layout.customlayout, null);
    
                TextView tTitle = (TextView) v.findViewById(R.id.title);
    
                TextView tSnippet = (TextView) v.findViewById(R.id.snippet);
    
                tTitle.setText(arg0.getTitle());
    
                tSnippet.setText(arg0.getSnippet());
    
                return v;
    
            }
        });
    }
    

    【讨论】:

    • 感谢您的回答!基本上我想删除当前标记并从一开始就让它们成为我的问题...
    • 我可以根据用户输入使用相同的修改来搜索标记吗??
    • 我没有得到。你能用场景解释一下吗?
    • 例如有一个叫做“MATADERO”的标记。如果用户输入它,我可以打开这个标记的内容窗口吗?
    • 你使用marker.showInfoWindow();但在这种情况下,lat/long 应该匹配或 name 应该匹配。我的意思是应该有一些东西可以代表它请求该特定标记的显示窗口。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 2013-08-28
    • 2018-03-25
    相关资源
    最近更新 更多