2013-03-11 6 views
5

mi sono bloccato con questo problema e spero che qualcuno mi può portare a una soluzione, ho trascorso 3 giorni su di esso fino ad ora ..ottenere altri valori da marcatore

Il problema

I avere 2 attività, attività A è una lista popolata da un elenco JSON. Attività B è Google Maps v2 basato sulla stessa lista JSON ma sulla mappa non sulla lista.

sull'attività A elenco c'è onItemclicklistener e quando faccio clic su di esso mostra un'altra attività e funziona bene. nessun problema qui. tutto funziona come si suppone anche.

su Attività B c'è il frammento di mappa, ed è pieno di valori lat-lng anche da un elenco JSON. Quindi ci sono 10 + marcatori sulla mappa. Quindi quando clicco su un marker, sto ottenendo il nome e l'indirizzo e anche il suo funzionamento.

questo quello che voglio

Quando ho clic sulla voce nella lista che mi prendendo all'attività C. e ci sono alcune visualizzazioni testuali per mostrare in quali giorni la società è aperta. questo passo è fatto, sta funzionando bene e tutto ciò che piace suppone anche.

Quando faccio clic su Mappa, ci sono indicatori, quindi ho onInfoWindowClick(). Va bene, ma come posso ottenere più valori dal onInfoWindowClick()?

Quello che voglio dire è che posso ottenere (getSnippet e getTitle dal marker) Ma ho altri valori nell'elenco, come nome, giorni, id. ciò che ottengo è solo .getsnippet e getTitle attraverso l'indicatore.

Sono molto bloccato con questo problema. Voglio davvero fare lo stesso come sulla lista. Quando premo sull'elenco ottiene tutti i valori ma quando iam su Maps posso ottenere solo la finestra dei marker con Title e Snippet. Scusa se non riesco a spiegarmi bene, sentitevi liberi di chiedermi se c'è più codice che volete vedere.

   for (HashMap<String, String> hashMap : contactList) { 
      map.addMarker(new MarkerOptions() 
       .position(new LatLng(Double.valueOf(hashMap.get(TAG_LAT)) , Double.valueOf(hashMap.get(TAG_LNG)))) 
       .title(hashMap.get(TAG_ADDRESS)) 
       .snippet(hashMap.get(TAG_NAME))); 

@Override 
public void onInfoWindowClick(Marker marker) { 

    marker.getTitle(); 
    marker.getSnippet(); 
} 

codice aggiornato

public class MapBased extends AbstractMapActivity implements OnNavigationListener,OnInfoWindowClickListener 
{ 
    private static final String TAG_Location = "location_id"; 
    private static final String TAG_Company = "company_id"; 
    private static final String TAG_PLACE = "place"; 
    private static final String TAG_POSTAL = "postal"; 
    private static final String TAG_CITY = "city"; 
    private static final String TAG_MONDAY = "monday"; 
    private static final String TAG_TUESDAY = "tuesday"; 
    private static final String TAG_WEDNESDAY = "wednesday"; 
    private static final String TAG_THURSDAY = "thursday"; 
    private static final String TAG_FRIDAY = "friday"; 
    private static final String TAG_SATURDAY = "saturday"; 
    private static final String TAG_SUNDAY = "sunday"; 
    private static final String TAG_TYPE = "type"; 
    private static final String TAG_NOCAR = "nocar"; 

    private static final String TAG_NAME = "name"; 
    private static final String TAG_LAT = "lat"; 
    private static final String TAG_LNG = "lng"; 
    private static final String TAG_ADDRESS = "address"; 
    private static final String TAG = "Debug of Project"; // 

    private String a; 
private String b; 

private double my_lat; 
private double my_lng; 

private static final String STATE_NAV="nav"; 
private static final int[] MAP_TYPE_NAMES= { R.string.normal, R.string.hybrid, R.string.satellite, R.string.terrain }; 
private static final int[] MAP_TYPES= { GoogleMap.MAP_TYPE_NORMAL, GoogleMap.MAP_TYPE_HYBRID, GoogleMap.MAP_TYPE_SATELLITE, 
           GoogleMap.MAP_TYPE_TERRAIN }; 
private GoogleMap map=null; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    SQLiteDatabase db = openOrCreateDatabase("mydb.db", Context.MODE_PRIVATE, null); 
    db.execSQL("CREATE TABLE IF NOT EXISTS gps_kordinater (ID INTEGER PRIMARY KEY AUTOINCREMENT, Latitude REAL, Longitude REAL);"); 

    String query = "SELECT Latitude,Longitude FROM gps_kordinater WHERE Id = (SELECT MAX(Id) FROM gps_kordinater)"; 
    Cursor cursor = db.rawQuery(query, null); 
    if(cursor != null) 
    { 
    cursor.moveToFirst(); 
    a = cursor.getString(0); 

    b = cursor.getString(1); 
    } 


    String url = "http://example.com"; 

    my_lat = Double.valueOf(a); 
    my_lng = Double.valueOf(b); 


    db.close(); 

    // now enabled if disabled = ingen support for jb aka 4.0 
    if (android.os.Build.VERSION.SDK_INT > 9) { 
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
      StrictMode.setThreadPolicy(policy); 
    } 

    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>(); 
    JSONParser jParser = new JSONParser(); 
    JSONArray json = jParser.getJSONFromUrl(url); 
    try { 
      for(int i = 0; i < json.length(); i++){ 
       JSONObject c = json.getJSONObject(i); 

       String lat = c.getString(TAG_LAT); 
       String lng = c.getString(TAG_LNG); 
       String name = c.getString(TAG_NAME); 
       String adresse = c.getString(TAG_ADDRESS); 

       String location_id = c.getString(TAG_Location); 
       String company_id = c.getString(TAG_Company); 
       String place = c.getString(TAG_PLACE) ; 
       String postal = c.getString(TAG_POSTAL); 
       String city = c.getString(TAG_CITY); 
       String monday = c.getString(TAG_MONDAY); 
       if(c.getString(TAG_MONDAY).isEmpty()) 
        { 
         monday="Lukket"; 
        } 
       else 
        { 
         monday=c.getString(TAG_MONDAY); 
        } 

       String tuesday = c.getString(TAG_TUESDAY); 
       if(c.getString(TAG_TUESDAY).isEmpty()) 
        { 
         tuesday="Lukket"; 
        } 
       else 
        { 
         tuesday=c.getString(TAG_TUESDAY); 
        } 

       String wednesday = c.getString(TAG_WEDNESDAY); 
       if(c.getString(TAG_WEDNESDAY).isEmpty()) 
        { 
         wednesday="Lukket"; 
        } 
       else 
        { 
         wednesday=c.getString(TAG_WEDNESDAY); 
        } 

       String thursday = c.getString(TAG_THURSDAY); 
       if(c.getString(TAG_THURSDAY).isEmpty()) 
        { 
         thursday="Lukket"; 
        } 
       else 
        { 
         thursday=c.getString(TAG_THURSDAY); 
        } 

       String friday = c.getString(TAG_FRIDAY); 
       if(c.getString(TAG_FRIDAY).isEmpty()) 
        { 
         friday="Lukket"; 
        } 
       else 
        { 
         friday=c.getString(TAG_FRIDAY); 
        } 

       String saturday = c.getString(TAG_SATURDAY); 
       if(c.getString(TAG_SATURDAY).isEmpty()) 
        { 
         saturday="Lukket"; 
        } 
       else 
        { 
         saturday=c.getString(TAG_SATURDAY); 
        } 

       String sunday=c.getString(TAG_SUNDAY); 
       if(c.getString(TAG_SUNDAY).isEmpty()) 
        { 
         sunday="Lukket"; 
        } 
       else 
        { 
         sunday=c.getString(TAG_SUNDAY); 
        } 



       String nocar = c.getString(TAG_NOCAR); 
       String type = c.getString(TAG_TYPE); 


      // creating new HashMap 
      HashMap<String, String> map2 = new HashMap<String, String>(); 

      // adding each child node to HashMap key => value 

      map2.put(TAG_LAT, lat); 
      map2.put(TAG_LNG, lng); 

      map2.put(TAG_NAME, name); 
      map2.put(TAG_ADDRESS, adresse); 
      map2.put(TAG_Location, location_id); 
      map2.put(TAG_Company, company_id); 
      map2.put(TAG_PLACE, place); 
      map2.put(TAG_POSTAL, postal); 
      map2.put(TAG_CITY, city); 
      map2.put(TAG_MONDAY, monday); 
      map2.put(TAG_TUESDAY, tuesday); 
      map2.put(TAG_WEDNESDAY, wednesday); 
      map2.put(TAG_THURSDAY, thursday); 
      map2.put(TAG_FRIDAY, friday); 
      map2.put(TAG_SATURDAY, saturday); 
      map2.put(TAG_SUNDAY, sunday); 
      map2.put(TAG_TYPE, type); 
      map2.put(TAG_NOCAR, nocar); 

      // adding HashList to ArrayList 
      contactList.add(map2); 

      Log.d(TAG, "Hashmap 1: " + map2); 

      Log.d(TAG, "Hashmap 2: " + map2.values()); 
      Log.d(TAG, "array 4: " + contactList); 

      } 


      Log.d(TAG, "array 5: " + contactList); 

    } catch (JSONException e) { 
     e.printStackTrace(); 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 

    } 

    if (readyToGo()) { 
     setContentView(R.layout.map_based); 

     SupportMapFragment mapFrag= 
       (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map2); 
     initListNav(); 

     map=mapFrag.getMap(); 

     CameraUpdate center= CameraUpdateFactory.newLatLng(new LatLng(my_lat , my_lng)); 

     CameraUpdate zoom=CameraUpdateFactory.zoomTo(10); 
     map.moveCamera(center); 
     map.animateCamera(zoom); 

     for (HashMap<String, String> hashMap : contactList) { 
      map.addMarker(new MarkerOptions() 
       .position(new LatLng(Double.valueOf(hashMap.get(TAG_LAT)) , Double.valueOf(hashMap.get(TAG_LNG)))) 
       .title(hashMap.get(TAG_ADDRESS)) 
       .snippet(hashMap.get(TAG_NAME)) 

      ); 
     } 

     map.setInfoWindowAdapter(new PopupMapBasedAdapter(getLayoutInflater())); 
     map.setOnInfoWindowClickListener(this); 

    } 

    Button btn_web = (Button) findViewById(R.id.footer_list_btn); 
     btn_web.setOnClickListener(new View.OnClickListener() { 
      @Override 
       public void onClick(View view) { 
       //myVib.vibrate(50); 
       finish(); 
       } 
      }); 
} 

@Override 
public boolean onNavigationItemSelected(int itemPosition, long itemId) { 
    map.setMapType(MAP_TYPES[itemPosition]); 
    return(true); 
} 

@Override 
public void onSaveInstanceState(Bundle savedInstanceState) { 
    super.onSaveInstanceState(savedInstanceState); 
    savedInstanceState.putInt(STATE_NAV,getSupportActionBar().getSelectedNavigationIndex()); 
} 

@Override 
public void onInfoWindowClick(Marker marker) { 

    marker.getTitle(); 
    marker.getSnippet(); 
} 

    @Override 
    public void onRestoreInstanceState(Bundle savedInstanceState) { 
    super.onRestoreInstanceState(savedInstanceState); 
    getSupportActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_NAV)); 
    } 

    private void initListNav() { 
ArrayList<String> items=new ArrayList<String>(); 
ArrayAdapter<String> nav=null; 
ActionBar bar=getSupportActionBar(); 

    for (int type : MAP_TYPE_NAMES) { 
     items.add(getString(type)); 
    } 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 
     nav= 
       new ArrayAdapter<String>(
         bar.getThemedContext(), 
         android.R.layout.simple_spinner_item, 
         items); 
       } 
    else { 
     nav= 
      new ArrayAdapter<String>( 
        this, 
        android.R.layout.simple_spinner_item, 
        items); 
       } 

    nav.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); 
    bar.setListNavigationCallbacks(nav, this); 
} 


    } 

risposta

20

Non è possibile aggiungere più dati al marcatore, a meno che non lo si inserisca tutti nello snippet.

Quindi, se si desidera aggiungere più dati al proprio indicatore, sarà necessario memorizzarlo in una variabile esterna collegata al proprio indicatore.

Each made marker has an unique ID.

È possibile utilizzare queste informazioni per salvare tutti i dati aggiuntivi mappati a questo ID in una variabile indipendente.

Esempio:

Creare una variabile è possibile accedere:

/** 
    * Create your variable where you store all your data mapped to the marker ID, 
    * make it accessible where you want. 
    * The key of this hashmap is your marker ID, the value is another Map with extra data 
    */ 
HashMap<String, HashMap> extraMarkerInfo = new HashMap<String, HashMap>(); 

OPZIONE 1 modificare il codice marcatore modo si aggiungono dati in più per questa variabile

for (HashMap<String, String> hashMap : contactList) { 
    // Create your marker like normal, nothing changes 
    Marker marker = map.addMarker(new MarkerOptions() 
     .position(new LatLng(Double.valueOf(hashMap.get(TAG_LAT)) , Double.valueOf(hashMap.get(TAG_LNG)))) 
     .title(hashMap.get(TAG_ADDRESS)) 
     .snippet(hashMap.get(TAG_NAME))); 

    // When you created the marker you store the extra data from your JSON in another variable (HashMap for example) 
    HashMap<String, String> data = new HashMap<String, String>(); 

    data.put(TAG_Location,hashMap.get(TAG_Location)); 
    data.put(TAG_Company,hashMap.get(TAG_Company)); 
    data.put(TAG_PLACE,hashMap.get(TAG_PLACE)); 
    data.put(TAG_POSTAL,hashMap.get(TAG_POSTAL)); 
    data.put(TAG_CITY,hashMap.get(TAG_CITY)); 
    data.put(TAG_MONDAY,hashMap.get(TAG_MONDAY)); 
    data.put(TAG_TUESDAY,hashMap.get(TAG_TUESDAY)); 
    data.put(TAG_WEDNESDAY,hashMap.get(TAG_WEDNESDAY)); 
    data.put(TAG_THURSDAY,hashMap.get(TAG_THURSDAY)); 
    data.put(TAG_FRIDAY,hashMap.get(TAG_FRIDAY)); 
    data.put(TAG_SATURDAY,hashMap.get(TAG_SATURDAY)); 
    data.put(TAG_SUNDAY,hashMap.get(TAG_SUNDAY)); 
    data.put(TAG_TYPE,hashMap.get(TAG_TYPE)); 
    data.put(TAG_NOCAR,hashMap.get(TAG_NOCAR)); 

    // Save this marker data in your previously made HashMap mapped to the marker ID. So you can get it back based on the marker ID 
    extraMarkerInfo.put(marker.getId(),data); 

} 

EASY OPZIONE 2 Basta salvare l'intera mappa nella variabile esterna

for (HashMap<String, String> hashMap : contactList) { 
    // Create your marker like normal, nothing changes 
    Marker marker = map.addMarker(new MarkerOptions() 
     .position(new LatLng(Double.valueOf(hashMap.get(TAG_LAT)) , Double.valueOf(hashMap.get(TAG_LNG)))) 
     .title(hashMap.get(TAG_ADDRESS)) 
     .snippet(hashMap.get(TAG_NAME))); 

    // Just save the entire json hashmap into the external variable 
    extraMarkerInfo.put(marker.getId(),hashMap); 

} 

Ora è possibile accedere a tale extraMarkerInfo ogni volta che vuoi, sai l'id Marker utilizzando getID().

@Override 
public void onInfoWindowClick(Marker marker) { 

    String title = marker.getTitle(); 
    String snippet = marker.getSnippet(); 

    // Get extra data with marker ID 
    HashMap<String, String> marker_data = extraMarkerInfo.get(marker.getId()); 

    // Getting the data from Map 
    String location = marker_data.get(TAG_Location); 
    String company = marker_data.get(TAG_Company); 
    String place = marker_data.get(TAG_PLACE); 
    //.. etc etc 
} 

Questo è solo un piccolo esempio di operazioni HashMaps, ma è possibile utilizzare diverse soluzioni quello che preferite.

+0

Vero, ma ho una lista da JSON e tutti i dati sono già nella mappa di hash. Il tuo esempio è un marker con valori di autoaggiunta, ma l'ho già su hashmap, come posso aggiungerlo al marker? – Tirolel

+0

Non penso che tu capisca cosa intendo. Leggi di nuovo l'intera risposta. Tu ** NON FACCIA ** aggiungilo al marcatore, non puoi. Ma puoi mapparlo a qualcos'altro e usare l'identificatore come chiave. Ottieni i tuoi dati extra dal tuo JSON e invece di inserirlo nel marker. Mettilo nella variabile esterna e dai l'ID del marker come chiave e tutti i dati extra come valore. – Timmetje

+0

sicuro che sarà molto utile da parte tua. Ti sto solo mettendo il codice enitre, quindi sarà più facile per te capire cosa intendo. – Tirolel

1

Credo che bisogna avere un elenco con tutte le informazioni che si hanno anche nel vostro ListAcivity nel MapActivity. Quando un utente fa clic su un indicatore, cerca l'oggetto specifico (suppongo che si tratti di contatti) nell'elenco e ottiene il resto delle informazioni necessarie.

1
@Override 
    public boolean onMarkerClick(Marker marker) { 
     // TODO Auto-generated method stub 
     String selected_marker=marker.getTitle(); 
     return false; 
    } 

Quindi è possibile lavorare in base a quale indicatore viene selezionato (quale operazione si desidera). Qui di sapere quale marcatore viene cliccato ...

1

Un modo davvero piacevole e facile per farlo è - ogni volta che si aggiunge un indicatore alla mappa, fare un riferimento ad esso in qualcosa di simile HashMap<Marker, <WhateverDataYouNeed> extraMarkerData

Poi ogni volta che si vuoi i suoi dati, tutto ciò che devi fare è chiamare extraMarkerData.get(<yourMarker>) per restituirlo. simples.

Grazie a questo tipo tizio che ha scritto un tutorial, ho trovato ad essere piuttosto esteso per quello che mi serviva, ma a condizione che la semplice idea:

http://bon-app-etit.blogspot.be/2012/12/add-informationobject-to-marker-in.html

miei dati più simile a questa:

private HashMap<Marker,HashMap<String,String>> markerUserData; 

Poi ogni volta aggiungo un marcatore per la mia mappa, mi assicuro faccio un riferimento ai suoi dati utilizzando il marcatore come chiave

Marker marker = map.addMarker(new MarkerOptions() 
     .position(new LatLng(<lat>,<lng>) 
     .title(<markerTitle>) 
     .snippet(<markerSnippet>) 
); 

markerUserData.put(marker,<myExtraMarkerDataHashMap>); //add reference to marker data 

E dato che ho la mia classe per gestire OnInfoWindowClickListener, ho fatto un getter pubblico

public HashMap<String,String> getDataforMarker(Marker marker){ 
    return extraMarkerData.get(marker); 
} 

OnInfoWindowClickListener:

@Override 
public void onInfoWindowClick(Marker marker) { 
    Log.i("SFCT","Data for marker = "+activity.getDataforMarker(marker)); 
}