当前位置: 动力学知识库 > 问答 > 编程问答 >

android - I want to show Multiple Markers at runtime on the screen which have different id's that received from the server

问题描述:

I want to show Multiple Markers at runtime on the screen which have different id's that received from the server and longitude and latitude also change or save on server.

** Code work fine in 1 to 1 tracking but not work on multiple Id's PLEASE HELP ME..**

 public class MainActivity extends AppCompatActivity

implements GoogleApiClient.ConnectionCallbacks,

GoogleApiClient.OnConnectionFailedListener {

static final LatLng HAMBURG1 = new LatLng(74.3226214, 31.5003567);

static final LatLng HAMBURG = new LatLng(74.3229122, 31.5003193);

private static MainActivity instance;

private static final int ERROR_DIALOG_REQUEST = 9001;

GoogleMap mMap;

int i = 0;

protected static String longitudeServer;

protected static String latitudeServer;

protected static String uniqueidSserver;

protected static String latitudeLast;

protected static String logitudeLast;

protected static String uniqueidlast;

protected static double latilasdoublet;

protected static double longilastdouble;

double latitude = 0;

double longitude = 0;

private GoogleApiClient mLocationClient;

private com.google.android.gms.location.LocationListener mListener;

private Marker marker;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

if (servicesOK()) {

setContentView(R.layout.activity_map);

if (initMap()) {

// gotoLocation(SEATTLE_LAT, SEATTLE_LNG, 15);

mLocationClient = new GoogleApiClient.Builder(this)

.addApi(LocationServices.API)

.addConnectionCallbacks(this)

.addOnConnectionFailedListener(this)

.build();

mLocationClient.connect();

mMap.setMyLocationEnabled(true);

} else {

Toast.makeText(this, "Map not connected!", Toast.LENGTH_SHORT).show();

}

} else {

setContentView(R.layout.activity_main);

}

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.menu_main, menu);

return true;

}

@Override

public boolean onOptionsItemSelected(MenuItem item) {

int id = item.getItemId();

//Add menu handling code

switch (id) {

case R.id.mapTypeNone:

mMap.setMapType(GoogleMap.MAP_TYPE_NONE);

break;

case R.id.mapTypeNormal:

mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

break;

case R.id.mapTypeSatellite:

mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

break;

case R.id.mapTypeTerrain:

mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

break;

case R.id.mapTypeHybrid:

mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

break;

}

return super.onOptionsItemSelected(item);

}

public boolean servicesOK() {

int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

if (isAvailable == ConnectionResult.SUCCESS) {

return true;

} else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {

Dialog dialog =

GooglePlayServicesUtil.getErrorDialog(isAvailable, this, ERROR_DIALOG_REQUEST);

dialog.show();

} else {

Toast.makeText(this, "Can't connect to mapping service", Toast.LENGTH_SHORT).show();

}

return false;

}

private boolean initMap() {

if (mMap == null && i == 0) {

SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

mMap = mapFragment.getMap();

mMap.setMyLocationEnabled(true);

mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

}

return (mMap != null);

}

private void gotoLocation(double lat, double lng, float zoom) {

LatLng latLng = new LatLng(lat, lng);

CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, zoom);

mMap.moveCamera(update);

}

public void showCurrentLocation(MenuItem item) {

Location currentLocation = LocationServices.FusedLocationApi

.getLastLocation(mLocationClient);

if (currentLocation == null) {

Toast.makeText(this, "Couldn't connect!", Toast.LENGTH_SHORT).show();

} else {

LatLng latLng = new LatLng(

currentLocation.getLatitude(),

currentLocation.getLongitude()

);

CameraUpdate update = CameraUpdateFactory.newLatLngZoom(

latLng, 10

);

mMap.animateCamera(update);

}

}

@Override

public void onConnected(Bundle bundle) {

Toast.makeText(this, "Ready to map!", Toast.LENGTH_SHORT).show();

mListener = new LocationListener() {

@Override

public void onLocationChanged(Location location) {

latitude = location.getLatitude();

longitude = location.getLongitude();

LatLng latLng = new LatLng(latitude, longitude);

// mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

Toast.makeText(MainActivity.this, "Location : " + location.getLatitude() + ", " + location.getLongitude(), Toast.LENGTH_LONG).show();

if (i == 0) {

gotoLocation(location.getLatitude(), location.getLongitude(), 15);

i = 1;

}

AppUtill.UniqueId();

if (AppStatus.getInstance(getContext()).isOnline()) {

new JSONAsyncTask().execute("http://ip/hajjapi/api/GPSLocator/GetLocations");

} else {

Toast.makeText(MainActivity.this, "Turn On your WIFI ", Toast.LENGTH_LONG).show();

}

///HOW I CAN DISPLAY MULTIPLE MARKERS WHICH HAVE DIFFERENT ID'S RECEIVED FROM THE SERVER PLEASE HELP ME PLEASE...

if (marker != null) {

marker.remove();

}

MarkerOptions options = new MarkerOptions().title("User Name").position(new LatLng(latilasdoublet, longilastdouble)).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4));

marker = mMap.addMarker(options);

}

};

LocationRequest request = LocationRequest.create();

request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

request.setInterval(5000);

request.setFastestInterval(5000);

LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, request, mListener);

}

@Override

public void onConnectionSuspended(int i) {

}

@Override

public void onConnectionFailed(ConnectionResult connectionResult) {

}

public void showcurrentLocation() {

mMap.animateCamera(CameraUpdateFactory.zoomTo(15));

i = 1;

}

class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

ProgressDialog dialog;

@Override

protected void onPreExecute() {

super.onPreExecute();

}

@Override

protected Boolean doInBackground(String... urls) {

try {

//------------------>>

HttpGet httpGet = new HttpGet(urls[0]);

HttpClient httpclient = new DefaultHttpClient();

HttpResponse response = httpclient.execute(httpGet);

int status = response.getStatusLine().getStatusCode();

if (status == 200) {

HttpEntity entity = response.getEntity();

String data = EntityUtils.toString(entity);

JSONArray jsonarray = new JSONArray(data);

for (int i = 0; i < jsonarray.length(); i++) {

JSONObject obj = jsonarray.getJSONObject(i);

longitudeServer = obj.getString("longi");

latitudeServer = obj.getString("lati");

uniqueidSserver = obj.getString("uniqueid");

}

////LAST LONGITUDE AND LATITUDE THAT RECEIVED FROM SERVER

List<String> longitude = Arrays.asList(longitudeServer);

logitudeLast = longitude.get(longitude.size() - 1);

System.out.println(logitudeLast + " logitude ");

List<String> latitude = Arrays.asList(latitudeServer);

latitudeLast = latitude.get(latitude.size() - 1);

System.out.println(latitudeLast + " latitude ");

List<String> uniqueid = Arrays.asList(uniqueidSserver);

uniqueidlast = uniqueid.get(uniqueid.size() - 1);

System.out.println(uniqueidlast + " unique id ");

latilasdoublet = Double.parseDouble(latitudeLast);

longilastdouble = Double.parseDouble(logitudeLast);

return true;

}

//------------------>>

} catch (IOException e) {

e.printStackTrace();

} catch (JSONException e) {

e.printStackTrace();

}

return false;

}

protected void onPostExecute(Boolean result) {

if (result == false)

Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();

}

}

@Override

protected void onStop() {

super.onStop();

startService(new Intent(getContext(), Services.class));

}

public MainActivity() {

instance = this;

}

public static Context getContext() {

return instance;

}

}

网友答案:

you are using only two double variables for lat and lng. create an arrayList of LatLng objects. for all the urls you get in response, add the LatLng to the arrayList.

  1. add a field

    private ArrayList<LatLng> latLngList;
    
  2. initialize in oncreate function

    latLngList = new ArrayList<>();
    
  3. instead of

    latilasdoublet = Double.parseDouble(latitudeLast);
    longilastdouble = Double.parseDouble(logitudeLast);
    

    add

    for(int i=0; i< latitude.size(); i++){
       LatLng latLng = new LatLng(Double.parseDouble(latitude.get(i)), Double.parseDouble(longitude.get(i)));
       latLngList.add(latLng);
    }
    
  4. in place of

    MarkerOptions options = new MarkerOptions().title("User Name").position(new LatLng(latilasdoublet, longilastdouble)).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4));
        marker = mMap.addMarker(options);
    

    use

    ArrayList<MarkerOptions> list = new ArrayList<>();  
    for (LatLng object : latLngList){
        MarkerOptions options = new MarkerOptions().title("User Name").position(object).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4));
        mMap.addMarker(options);
        list.add(options);   //if you want to keep track of all your markers
    }
    

use mMap.clear() to clear all markers and clustering refer

More info on markers.

分享给朋友:
您可能感兴趣的文章:
随机阅读: