繁体   English   中英

使用按钮刷新Android上的地图标记

[英]Refresh map markers on android with button

我正在运行带有一些json数据的网络服务,我用它在我的地图上做标记(每小时更新一次)。我想在我的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

我在map.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;

        }
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM