如何在Android中的ArrayList上添加谷歌地图上的标记

时间:2015-03-26 09:25:03

标签: android google-maps google-maps-api-3

首先抱歉我的英语不好,我正在谷歌地图上工作,我第一次在谷歌地图上工作,我的问题是我从我的服务器端得到一个数组,并在这个数组我得到了这个城市,名称,纬度,长等。  我的数组如下:

城市,名称,21.22,22.33,城市,名称,24.44,25.55,城市,名称,32.222,38.88

我想代表我的lat将标记放在谷歌地图上,很长,正如你在我的阵列上看到的那样,在我的第一个索引上我得到了城市,名称和纬度,然后是第二个位置纬度,长,城市和名称等..请帮助我如何在谷歌地图上实现标记?将非常感谢。

我的MapActivity:

public class MapActivity extends ActionBarActivity {

// Google Map
private GoogleMap googleMap;
double stringLatitude;
double stringLongitude;

String frenchiseLocationArray;
String ServiceCentreLocationArray;

private ArrayList<String> AssociatedArray = new ArrayList<String>();

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

    setupActionBarBackPressed();

    frenchiseLocationArray = getIntent().getExtras().getString(
            "frenchiseLocationArray");
    ServiceCentreLocationArray = getIntent().getExtras().getString(
            "ServiceCentreLocationArray");

    Toast.makeText(
            getApplicationContext(),
            "frenchise " + frenchiseLocationArray + "\n"
                    + " service centre " + ServiceCentreLocationArray,
            Toast.LENGTH_SHORT).show();

    // separate the strings by comma
    StringTokenizer st = new StringTokenizer(frenchiseLocationArray, ",");

    /* List myArray = new ArrayList<String>(); */
    String token = null;

    while (st.hasMoreTokens()) {

        token = st.nextToken();
        AssociatedArray.add(token);

    }
    Log.d("map", "frenchise location array = " + AssociatedArray);
    if (AssociatedArray != null) {

        if (AssociatedArray.size() > 0) {

            for (int a = 0; a < AssociatedArray.size(); a = a + 2) {

            //  Log.d("map", "frenchise location array = " + AssociatedArray);

            }

        }

    }

    try {

        // check if GPS enabled
        GPSTracker gpsTracker = new GPSTracker(this);

        if (gpsTracker.canGetLocation()) {
            stringLatitude = Double.valueOf(gpsTracker.latitude);

            stringLongitude = Double.valueOf(gpsTracker.longitude);

        } else {

            gpsTracker.showSettingsAlert();
        }
        // Loading map
        initilizeMap();


        googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

        // Showing / hiding your current location
        googleMap.setMyLocationEnabled(true);

        // Enable / Disable zooming controls
        googleMap.getUiSettings().setZoomControlsEnabled(false);

        // Enable / Disable my location button
        googleMap.getUiSettings().setMyLocationButtonEnabled(true);

        // Enable / Disable Compass icon
        googleMap.getUiSettings().setCompassEnabled(true);

        // Enable / Disable Rotate gesture
        googleMap.getUiSettings().setRotateGesturesEnabled(true);

        // Enable / Disable zooming functionality
        googleMap.getUiSettings().setZoomGesturesEnabled(true);


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

}

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

/**
 * function to load map If map is not created it will create it for you
 * */
private void initilizeMap() {
    if (googleMap == null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();

        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}

/*
 * creating random postion around a location for testing purpose only
 */
private double[] createRandLocation(double latitude, double longitude) {

    return new double[] { latitude + ((Math.random() - 0.5) / 500),
            longitude + ((Math.random() - 0.5) / 500),
            150 + ((Math.random() - 0.5) * 10) };
}

public void setupActionBarBackPressed() {
    ActionBar actionBar = getSupportActionBar();
    actionBar.setLogo(R.drawable.ic_launcher);
    actionBar.setDisplayUseLogoEnabled(true);
    actionBar.setDisplayShowHomeEnabled(true);

    actionBar.setDisplayHomeAsUpEnabled(true); // BACK BUTTON ENABLED
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        // NavUtils.navigateUpFromSameTask(this);
        finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
  }
}

编辑: 这是地方,这是我的数组,我在其中获取我的AssociatedArray中的值。

Log.d("map", "frenchise location array = " + AssociatedArray);
if (AssociatedArray != null) {

    if (AssociatedArray.size() > 0) {

        for (int a = 0; a < AssociatedArray.size(); a = a + 2) {

          Log.d("map", "frenchise location array = " + AssociatedArray);

        }

    }

3 个答案:

答案 0 :(得分:1)

for (int i = 0; i < result.size(); i++) {

                    MarkerOptions marker = new MarkerOptions().position(
                            new LatLng(result.get(i).getShopLat(), result
                                    .get(i).getShopLng())).title(
                            result.get(i).getShopName());
                    // Changing marker icon
                    marker.icon(BitmapDescriptorFactory
                            .fromResource(R.drawable.marker));

                    // adding marker
                    googleMap.addMarker(marker);

                }


                LatLng latLong = new LatLng(user.getUserLatitude(), user.getUserLogitude());

                CameraPosition cameraPosition = new CameraPosition.Builder()
                        .target(latLong).zoom(19f).tilt(70).build();
                googleMap.setMyLocationEnabled(true);
                googleMap.animateCamera(CameraUpdateFactory
                        .newCameraPosition(cameraPosition));

此处结果是对象的arraylist,包括纬度和经度

答案 1 :(得分:1)

使用它:

创建一个java类MapBean.java

像这样:

public class MapBean {
private String City;
private String Name;
private String Lat;
private String Long;

public MapBean(String City, String Name, String Lat, String Long) {
    this.City = City;
    this.Name = Name;
    this.Lat = Lat;
    this.Long = Long;
}

public String getCity() {
    return City;
}

public void setCity(String city) {
    City = city;
}

public String getName() {
    return Name;
}

public void setName(String name) {
    Name = name;
}

public String getLat() {
    return Lat;
}

public void setLat(String lat) {
    Lat = lat;
}

public String getLong() {
    return Long;
}

public void setLong(String l) {
    Long = l;
}

}

将值放入该bean中

private ArrayList<MapBean> mMapBean = new ArrayList<MapBean>();
mMapBean.add(new MapBean("city","name","21.22","22.33"); 
mMapBean.add(new MapBean("city","name","24.44","25.55");
//like this.....

然后就这样做:

for(int i =0;i<mMapBean.size();i++){

final LatLng name = new LatLng(mMapBean.get(i).getLat(), mMapBean.get(i).getLong());
Marker marker = googleMapForUser.addMarker(new MarkerOptions()
                .position(name)
                .title(name)
                .snippet(name + " is cool")
                .icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.ic_launcher)));

        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(latitude, longitude)).zoom(15).build();

        googleMapForUser.animateCamera(CameraUpdateFactory
                .newCameraPosition(cameraPosition));
}

<强> 编辑: 只是保存这种方式。你说你可以这样做.. 然后粘贴这个..

    String temp = "city,name,21.22,22.33/city,name,24.44,25.55/city,name,32.222,38.88";
    String city = "", name = "", lat = "", lon = "";
    for (String retval : temp.split("/")) {
        System.out.println(retval);
        System.out.println();
        int i = 0;
        city = "";
        name = "";
        lat = "";
        lon = "";
        for (String value : retval.split(",")) {
            if (i == 0) {
                city = value;
            }
            if (i == 1) {
                name = value;
            }
            if (i == 2) {
                lat = value;
            }
            if (i == 3) {
                lon = value;
            }

            System.out.println(city + " " + name + " " + lat + " " + lon);
            i++;
        }
        System.out.println(city + " " + name + " " + lat + " " + lon);
         mMapBean.add(new MapBean(city, name, lat, lon));
    }

}

答案 2 :(得分:1)

使用以下活动替换您的MapActivity,希望它有效。

public class MapActivity extends ActionBarActivity {

// Google Map
private GoogleMap googleMap;
double stringLatitude;
double stringLongitude;

String frenchiseLocationArray;
String ServiceCentreLocationArray;

private ArrayList<String> AssociatedArray = new ArrayList<String>();
private ArrayList<String> AssociatedArrayServicesCentres = new ArrayList<String>();
private ArrayList<MapBean> mMapBean = new ArrayList<MapBean>();

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

    setupActionBarBackPressed();

    frenchiseLocationArray = getIntent().getExtras().getString(
            "frenchiseLocationArray");
    ServiceCentreLocationArray = getIntent().getExtras().getString(
            "ServiceCentreLocationArray");

    Toast.makeText(
            getApplicationContext(),
            "frenchise " + frenchiseLocationArray + "\n"
                    + " service centre " + ServiceCentreLocationArray,
            Toast.LENGTH_SHORT).show();

  ///////////////////////////////////////// for frenchise ///////////////////////////////////////
    // separate the strings by comma
    StringTokenizer st = new StringTokenizer(frenchiseLocationArray, ",");

    /* List myArray = new ArrayList<String>(); */
    String token = null;

    while (st.hasMoreTokens()) {

        token = st.nextToken();
        AssociatedArray.add(token);

    }

 ///////////////////////////// for frenchise End ///////////////////////////////////////

 ///////////////////////////// for ServicesCentre  ///////////////////////////////////////

    // separate the strings by comma
            StringTokenizer st1 = new StringTokenizer(ServiceCentreLocationArray, ",");

            /* List myArray = new ArrayList<String>(); */
            String token1 = null;

            while (st1.hasMoreTokens()) {

                token1 = st1.nextToken();
                AssociatedArrayServicesCentres.add(token1);

            }
 ///////////////////////////// for ServicesCentre End  ///////////////////////////////////////


    try {

        // check if GPS enabled
        GPSTracker gpsTracker = new GPSTracker(this);

        if (gpsTracker.canGetLocation()) {
            stringLatitude = Double.valueOf(gpsTracker.latitude);

            stringLongitude = Double.valueOf(gpsTracker.longitude);

        } else {
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings
            gpsTracker.showSettingsAlert();
        }
        // Loading map
        initilizeMap();


        googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
        // googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);

        // Showing / hiding your current location
        googleMap.setMyLocationEnabled(true);

        // Enable / Disable zooming controls
        googleMap.getUiSettings().setZoomControlsEnabled(false);

        // Enable / Disable my location button
        googleMap.getUiSettings().setMyLocationButtonEnabled(true);

        // Enable / Disable Compass icon
        googleMap.getUiSettings().setCompassEnabled(true);

        // Enable / Disable Rotate gesture
        googleMap.getUiSettings().setRotateGesturesEnabled(true);

        // Enable / Disable zooming functionality
        googleMap.getUiSettings().setZoomGesturesEnabled(true);

        /*
         * double latitude = 17.385044; double longitude = 78.486671;
         */
        double latitude = 0; // = stringLatitude;
        double longitude = 0;// = stringLongitude;
        double latitude1 = 0; // = stringLatitude;
        double longitude1 = 0;// = stringLongitude;

        for (int i = 2; i < AssociatedArrayServicesCentres.size(); i+=4) {
            int j = i;
            /*int j = i;
            latitude = AssociatedArray.get(i)+ "";
            longitude = AssociatedArray.get(j+1);*/
            String City = AssociatedArrayServicesCentres.get(j-2);
            String Address = AssociatedArrayServicesCentres.get(j-1);

            String latstr = AssociatedArrayServicesCentres.get(i);
            latitude1 = Double.parseDouble(latstr);
            String longstr = AssociatedArrayServicesCentres.get(j+1);
            longitude1 = Double.parseDouble(longstr);

            final LatLng ufone = new LatLng(latitude1, longitude1);
            Marker kolkata = googleMap.addMarker(new MarkerOptions()
                            .position(ufone)
                            .title(City)
                            .snippet(Address)
                            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));

                    CameraPosition cameraPosition = new CameraPosition.Builder()
                            .target(new LatLng(latitude1, longitude1)).zoom(15).build();

                    googleMap.animateCamera(CameraUpdateFactory
                            .newCameraPosition(cameraPosition));
        }

        for (int i = 2; i < AssociatedArray.size(); i+=4) {
            int j = i;
            /*int j = i;
            latitude = AssociatedArray.get(i)+ "";
            longitude = AssociatedArray.get(j+1);*/
            String City = AssociatedArray.get(j-2);
            String Address = AssociatedArray.get(j-1);

            String latstr = AssociatedArray.get(i);
            latitude = Double.parseDouble(latstr);
            String longstr = AssociatedArray.get(j+1);
            longitude = Double.parseDouble(longstr);

            final LatLng ufone = new LatLng(latitude, longitude);
            Marker kolkata = googleMap.addMarker(new MarkerOptions()
                            .position(ufone)
                            .title(City)
                            .snippet(Address)
                            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));

                    CameraPosition cameraPosition = new CameraPosition.Builder()
                            .target(new LatLng(latitude, longitude)).zoom(15).build();

                    googleMap.animateCamera(CameraUpdateFactory
                            .newCameraPosition(cameraPosition));
        }






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

}

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

/**
 * function to load map If map is not created it will create it for you
 * */
private void initilizeMap() {
    if (googleMap == null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();

        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}

/*
 * creating random postion around a location for testing purpose only
 */
private double[] createRandLocation(double latitude, double longitude) {

    return new double[] { latitude + ((Math.random() - 0.5) / 500),
            longitude + ((Math.random() - 0.5) / 500),
            150 + ((Math.random() - 0.5) * 10) };
}

public void setupActionBarBackPressed() {
    ActionBar actionBar = getSupportActionBar();
    actionBar.setLogo(R.drawable.ic_launcher);
    actionBar.setDisplayUseLogoEnabled(true);
    actionBar.setDisplayShowHomeEnabled(true);

    actionBar.setDisplayHomeAsUpEnabled(true); // BACK BUTTON ENABLED
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        // NavUtils.navigateUpFromSameTask(this);
        finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
 }
}