如何在Google地图v2

时间:2015-10-17 18:26:56

标签: android

我想在运行时在谷歌地图v2上显示多个标记。我在远程服务器上有包含所有纬度和经度的位置表。 我想读取纬度和经度来显示位置表中每个条目的标记,但我不知道它在谷歌地图上给出一个标记.....如果是列表的第一个值,如果使用hashMap然后给最后一个数据库中的值 这是我用于在谷歌地图上阅读和显示标记的代码。请帮助m并提前感谢

 public class MapActivity extends AppCompatActivity {

private GoogleMap mMap; // Might be null if Google Play services APK is not available.
JSONArray jsonArray;
ArrayList<HashMap<String, String>> prodArrayList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> HashMap ;
String text;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    setUpMapIfNeeded();
}

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

/**
 * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
 * installed) and the map has not already been instantiated.. This will ensure that we only ever
 * call {@link #setUpMap()} once when {@link #mMap} is not null.
 * <p/>
 * If it isn't installed {@link SupportMapFragment} (and
 * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
 * install/update the Google Play services APK on their device.
 * <p/>
 * A user can return to this FragmentActivity after following the prompt and correctly
 * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
 * have been completely destroyed during this process (it is likely that it would only be
 * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
 * method in {@link #onResume()} to guarantee that it will be called.
 */
private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();



        CameraPosition cameraPosition = new CameraPosition.Builder().target(
                new LatLng(32.634723, 74.1601851)).zoom(12).build();
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
        ActionStartsHere();



        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}

/**
 * This is where we can add markers or lines, add listeners or move the camera. In this case, we
 * just add a marker near Africa.
 * <p/>
 * This should only be called once and when we are sure that {@link #mMap} is not null.
 */
private void setUpMap() {
    ReadDriverLocation task1 = new ReadDriverLocation();
    task1.execute(new String[]{"http://ahsan.comyr.com/ReadLocation.php"});
}
//This method call thread ofter 10 second
public void ActionStartsHere() {
    CallBangroundClass();
}


public void CallBangroundClass() {
    new CountDownTimer(11000, 30000) {
        @Override
        public void onTick(long millisUntilFinished) {

            //Object of ReadActiveDriver Class extends with AsyncTask Class

        }

        @Override
        public void onFinish() {
            ActionStartsHere();
        }

    }.start();
}



///////////////////////////////////////////////////////////////////////////
private class ReadDriverLocation extends AsyncTask<String,Void,Boolean>
{
    String text = "";

    ArrayList<String> list;
    ArrayList<String> list1;
    ArrayList<String> list2;
    @Override
    protected Boolean doInBackground(String... urls) {
        InputStream inputStream;
        for(String url1: urls) {
            try {
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(url1);
                HttpResponse response = client.execute(post);

                inputStream = response.getEntity().getContent();
            } catch (IOException e) {
                Toast.makeText(MapActivity.this, e.toString(), Toast.LENGTH_LONG).show();
                return false;
            }

            BufferedReader reader;
            try {
                reader = new BufferedReader(new InputStreamReader(inputStream));
                String line = null;
                while((line = reader.readLine())!=null)
                {
                    text += line +"\n";
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            list = new ArrayList<String>();
            list1 = new ArrayList<String>();
            list2 = new ArrayList<String>();
            HashMap = new HashMap<String, String>();
            try {
                jsonArray = new JSONArray(text);

                for(int i=0; i<jsonArray.length(); i++)
                {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String lati = jsonObject.getString("latitude");
                    String longLat = jsonObject.getString("longitude");
                    String Time = jsonObject.getString("time");

                    list.add(lati);
                    list1.add(longLat);
                    list2.add(Time);
                   //HashMap.put("Latitude", lati);
                   //HashMap.put("Longitude", longLat);
                   //HashMap.put("time", Time);
                   //prodArrayList.add(HashMap);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        return true;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        if(result == true)
        {
            for(int i=0; i<list.size(); i++)
            {
                Double latitude = Double.parseDouble(list.get(i));
                Double longitude = Double.parseDouble(list1.get(i));

                MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude,longitude)).title(list2.get(i));
                // GREEN color icon
                mMap.addMarker(marker);
            }
            /*
            for(int i=0; i<prodArrayList.size(); i++)
            {
                HashMap<String,String> hMap = prodArrayList.get(i);
                Double latitude = Double.parseDouble(hMap.get("Latitude"));
                Double longitude = Double.parseDouble(hMap.get("Longitude"));

                MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude,longitude)).title(hMap.get("time"));
                // GREEN color icon
                mMap.addMarker(marker);

            }*/
        }
        else
        {
            Toast.makeText(MapActivity.this, "Error in Loading...",Toast.LENGTH_LONG).show();
        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

当您使用HashMap时,您将获得最后一个值,因为您在for循环中使用相同的HashMap对象。根据HashMap定义,如果您使用相同的密钥,则密钥的先前值将被删除并替换为新密钥。

HashMap = new HashMap(); //这个hashMap用于整个循环

尝试{             jsonArray = new JSONArray(text);

        for(int i=0; i<jsonArray.length(); i++)
        {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String lati = jsonObject.getString("latitude");
            String longLat = jsonObject.getString("longitude");
            String Time = jsonObject.getString("time");
           // You use here duplicate key hence last value retained by hash map
           HashMap.put("Latitude", lati);
           HashMap.put("Longitude", longLat);
           HashMap.put("time", Time);
           prodArrayList.add(HashMap);

        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

为了从hashMap获取正确的值,然后在for循环中为hashmap创建新实例,如下所示:

    try {
        jsonArray = new JSONArray(text);

        for(int i=0; i<jsonArray.length(); i++)
        {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String lati = jsonObject.getString("latitude");
            String longLat = jsonObject.getString("longitude");
            String Time = jsonObject.getString("time");

            HashMap = new HashMap<String, String>();

           HashMap.put("Latitude", lati);
           HashMap.put("Longitude", longLat);
           HashMap.put("time", Time);
           prodArrayList.add(HashMap);

        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

按如下方式设置标记:

for(int i=0; i<prodArrayList.size(); i++)
            {
                HashMap<String,String> hMap = prodArrayList.get(i);
                Double latitude = Double.parseDouble(hMap.get("Latitude"));
                Double longitude = Double.parseDouble(hMap.get("Longitude"));

                MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude,longitude)).title(hMap.get("time"));
                // GREEN color icon
                mMap.addMarker(marker);

            }