Android 如何在google map v2上显示多个标记
我想在运行时在google map v2上显示多个标记。我在远程服务器上有包含所有纬度和经度的位置表。 我想读取纬度和经度,以显示位置表中每个条目的标记,但我不知道它在google地图上放置一个标记……列表中的第一个值,如果使用hashMap,则在数据库中给出最后一个值 这是我用来在谷歌地图上阅读和显示标记的代码。请帮助我,并提前表示感谢Android 如何在google map v2上显示多个标记,android,Android,我想在运行时在google map v2上显示多个标记。我在远程服务器上有包含所有纬度和经度的位置表。 我想读取纬度和经度,以显示位置表中每个条目的标记,但我不知道它在google地图上放置一个标记……列表中的第一个值,如果使用hashMap,则在数据库中给出最后一个值 这是我用来在谷歌地图上阅读和显示标记的代码。请帮助我,并提前表示感谢 public class MapActivity extends AppCompatActivity { private GoogleMap mMap;
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();
}
}
}
公共类MapActivity扩展了AppCompatActivity{
私有GoogleMap mMap;//如果Google Play services APK不可用,则可能为空。
JSONArray JSONArray;
ArrayList prodArrayList=新的ArrayList();
HashMap;
字符串文本;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
setupmapifneed();
}
@凌驾
受保护的void onResume(){
super.onResume();
setupmapifneed();
}
/**
*如果可能的话,设置地图(例如,Google Play services APK已正确启动)
*已安装)并且映射尚未实例化。这将确保
*当{@link#mMap}不为null时,调用{@link#setUpMap()}一次。
*
*如果未安装{@link SupportMapFragment}(和
*{@link com.google.android.gms.maps.MapView MapView})将提示用户
*在其设备上安装/更新Google Play services APK。
*
*用户可以按照提示正确返回此FragmentActivity
*安装/更新/启用Google Play服务。因为碎片活动可能不会
*在这一过程中被完全破坏(很可能
*停止或暂停),{@link#onCreate(Bundle)}可能不会被再次调用,因此我们应该调用它
*方法来保证将调用它。
*/
私有void setUpMapIfNeeded(){
//执行空检查以确认尚未实例化映射。
如果(mMap==null){
//尝试从SupportMapFragment获取映射。
mMap=((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
CameraPosition CameraPosition=新建CameraPosition.Builder().target(
新的LatLng(32.63472374.1601851)).zoom(12.build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
ActionStartsHere();
//检查我们是否成功获得地图。
如果(mMap!=null){
setUpMap();
}
}
}
/**
*在这里,我们可以添加标记或线条、添加侦听器或移动摄影机
*在非洲附近加一个标记。
*
*当我们确定{@link#mMap}不是null时,应该只调用一次。
*/
私有void setUpMap(){
ReadDriverLocation task1=新的ReadDriverLocation();
task1.execute(新字符串[]{”http://ahsan.comyr.com/ReadLocation.php"});
}
//此方法调用线程的时间为10秒
public void ActionStartsHere(){
CallBangroundClass();
}
public void CallBangroundClass(){
新的倒计时(11000,30000){
@凌驾
公共void onTick(长毫秒未完成){
//ReadActiveDriver类的对象使用AsyncTask类扩展
}
@凌驾
公共无效onFinish(){
ActionStartsHere();
}
}.start();
}
///////////////////////////////////////////////////////////////////////////
私有类ReadDriverLocation扩展异步任务
{
字符串文本=”;
数组列表;
ArrayList列表1;
ArrayList列表2;
@凌驾
受保护的布尔doInBackground(字符串…URL){
输入流输入流;
for(字符串url1:URL){
试一试{
HttpClient=new DefaultHttpClient();
HttpPost=新的HttpPost(url1);
HttpResponse response=client.execute(post);
inputStream=response.getEntity().getContent();
}捕获(IOE异常){
Toast.makeText(MapActivity.this,例如toString(),Toast.LENGTH_LONG).show();
返回false;
}
缓冲读取器;
试一试{
reader=新的BufferedReader(新的InputStreamReader(inputStream));
字符串行=null;
而((line=reader.readLine())!=null)
{
文本+=行+“\n”;
}
}捕获(IOE异常){
e、 printStackTrace();
}
列表=新的ArrayList();
list1=新的ArrayList();
list2=新的ArrayList();
HashMap=新的HashMap();
试一试{
jsonArray=新jsonArray(文本);
for(int i=0;i当您使用HashMap时,您得到的是最后一个值,因为您在for循环中使用的是相同的HashMap对象。根据HashMap定义,如果您使用相同的键,则该键的前一个值将被删除并替换为新的值
HashMap=newhashmap();//此HashMap用于整个循环
试一试{
jsonArray=新jsonArray(文本)
用于(int i=0;我这里是你的谷歌地图片段?我刚刚显示了backgound服务代码以获取值并显示在标记上…如果手动添加纬度和经度,则标记将显示在谷歌地图上。你想在hashmap中添加纬度和经度吗?我已经尝试了你的建议,现在它给我第一个值作为谷歌地图上的标记如何从prodArr获取值ayList?在您的代码中,从prodArrayList获取值会被注释。
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();
}
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);
}