3

在这里,我想根据其 latlong 将标记的详细 onclick 显示到 infowindow 中,并想做新事件 onclick infowindow。这里我做了一个标记列表和 lat1 long1 数组,它取自 url,你可以看到 private void setUpMapIfNeeded() 这个函数这里 nameb 包含标记名称列表

 public class Mainactivity extends FragmentActivity {
        String friendid;
        Double lng1;
        Double lat1;
        String lat;
        String lon;
        String gen;
        String test;
        String gender;
        String result;
        Drawable drawable;
        String frid;
        String nameb;
        private GoogleMap mMap;
        ImageView logout;
        private static final int DIALOG_ALERT = 10;
        Bitmap bm;
        static boolean Iscamera=false;
        ArrayList<Double> arrayLat = null;
        ArrayList<Double> arrayLong = null;
        ArrayList<String> arrayGender = null;
        ArrayList<String> arrayUsername = null;
        ArrayList<String> arrayFrnd = null;
        static ArrayList<Marker> markerList = null;
        EventListTask eventListTask;
        TextView tvLng;
        TextView tvLat;
        private static final int NOTIFICATION_ID = 1;


        private AQuery androidAQuery;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.flirtalerthome_screen);
            logout = (ImageView) findViewById(R.id.logoutimage);


    //*************************************************************************************************************

            androidAQuery=new AQuery(this);
            androidAQuery.ajax(Constant.Profile_Image, Bitmap.class, 0,new AjaxCallback<Bitmap>(){

                @Override
                public void callback(String url, Bitmap object, com.androidquery.callback.AjaxStatus status) {
                    super.callback(url, object, status);
                    bm=object;
                    //You will get Bitmap from object.
                }


            });
    //  ***************************************************************************************************************     
            new EventListTask().execute();



            logout.setOnClickListener(new View.OnClickListener() {
                @SuppressWarnings("deprecation")
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    showDialog(DIALOG_ALERT);
                }
            });


        }

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

        private void setUpMapIfNeeded() {

            if (mMap == null) {

                // Try to obtain the map from the SupportMapFragment.
                mMap = ((SupportMapFragment) getSupportFragmentManager()
                        .findFragmentById(R.id.map)).getMap();

                mMap.setMyLocationEnabled(true);

                if (mMap != null) {

                        mMap.setMyLocationEnabled(true);

                        mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
                        @Override
                        public void onMyLocationChange(Location arg0) {
                            // TODO Auto-generated method stub

                        mMap.clear();

                        if(!Iscamera){
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                                        new LatLng(arg0.getLatitude(), arg0
                                                .getLongitude()), 20));
                                Iscamera = true;
                            }
                            try{

                                 mMap.setInfoWindowAdapter(new InfoWindowAdapter()
                                 {

                                 // Use default InfoWindow frame
                                 public View getInfoWindow(Marker marker) {
                                 return null;
                                 }

    //                           Defines the contents of the InfoWindow
                                 public View getInfoContents(Marker marker) {


                                    // Getting view from the layout file info_window_layout
                                        View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);

                                        // Getting the position from the marker
    //                              

                                        // Getting reference to the TextView to set latitude
                                         tvLat = (TextView) v.findViewById(R.id.tv_lat);

                                        // Getting reference to the TextView to set longitude
    //                                  TextView tv = (TextView) v.findViewById(R.id.tv);

                                        // Setting the latitude
    //                                  tvLat.setText();

                                        // Setting the longitude
    //                                  tvLng.setText(nameb);

                                        // Returning the view containing InfoWindow contents
                                        return v;

                                    }

                                });







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

                                        lat1 = arrayLat.get(i);
                                        lng1 = arrayLong.get(i);
                                        gen = arrayGender.get(i);
                                        frid = arrayFrnd.get(i);
                                        nameb = arrayUsername.get(i);
                                        if (gen.equals("1")) {
                                            markerList
                                                    .add(mMap.addMarker(new MarkerOptions()
                                                            .position(new LatLng(lat1, lng1))
                                                            .title(nameb)
                                                            .icon(BitmapDescriptorFactory
                                                                    .fromResource(R.drawable.bluesmilelarge))));

                                        } else if (gen.equals("2")) {
                                            markerList
                                                    .add(mMap.addMarker(new MarkerOptions()
                                                            .position(new LatLng(lat1, lng1))
                                                            .title(nameb)
                                                            .icon(BitmapDescriptorFactory
                                                                    .fromResource(R.drawable.purplesmilelarge))));
                                        } else {
                                 markerList
                                                    .add(mMap.addMarker(new MarkerOptions()
                                                            .position(new LatLng(lat1, lng1))
                                                            .title(nameb)
                                                            .icon(BitmapDescriptorFactory
                                                                    .fromResource(R.drawable.purplesmilelarge))));

                                        }

                                    }



                            mMap.addMarker(new MarkerOptions()
                                    .position(
                                            new LatLng(arg0.getLatitude(), arg0
                                                    .getLongitude()))
                                    .title(Constant.USERNAME)
                                    .icon(BitmapDescriptorFactory.fromBitmap(bm)));

                            }catch (Exception e){
                                 Toast.makeText(getApplicationContext(),
                                 e.getMessage(),
                                 Toast.LENGTH_LONG).show();
                                 Log.e(e.getClass().getName(),
                                 e.getMessage(), e);
                            }

                        }
                    });

                }
            }
        }

        @SuppressWarnings("unused")
        private void setUpMap() {

            mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title(
                    "Marker"));
        }

        // ***********************************************************************************************************************
        @SuppressWarnings("deprecation")
        protected Dialog onCreateDialog(int id) {
            switch (id) {
            case DIALOG_ALERT:
                // Create out AlterDialog
                Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("Are you sure,want to logout");
                builder.setCancelable(true);
                builder.setPositiveButton("Yes", new OkOnClickListener());

                builder.setNegativeButton("No", new CancelOnClickListener());
                AlertDialog dialog = builder.create();
                dialog.show();
            }
            return super.onCreateDialog(id);
        }

        private final class CancelOnClickListener implements
                DialogInterface.OnClickListener {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }

        private final class OkOnClickListener implements
                DialogInterface.OnClickListener {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(FlirtHome_Screen.this, LoginScreen.class);
                SharedPreferences settings = getSharedPreferences(
                        Constant.PREFS_NAME, 0);
                SharedPreferences.Editor editor = settings.edit();
                editor.putString("logged", null);
                editor.commit();
                startActivity(intent);
                int pid = android.os.Process.myPid();
                android.os.Process.killProcess(pid);
                System.exit(0);

            }
        }

        // ********************************************************************************************************************

        private class EventListTask extends AsyncTask<Context, Void, Void> {
            ProgressDialog dialog = new ProgressDialog(FlirtHome_Screen.this);
            String message;
            String s;

            protected void onPreExecute() {
                super.onPreExecute();
                dialog.setMessage("Loading....please wait ");
                dialog.setCancelable(false);
                dialog.show();
            }

            protected Void doInBackground(Context... params) {
                try {

                    message = myMethod();
                    s = saveData(message);
    //              bm = drawableToBitmap(draw);
                } catch (Exception e) {
                    System.out.print(e.getMessage());
                }
                return null;
            }

            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                if (s == null) {
                } else {
                    for (int i = 0; i < arrayLat.size(); i++) {

                        lat1 = arrayLat.get(i);
                        lng1 = arrayLong.get(i);
                        gen = arrayGender.get(i);
                        frid = arrayFrnd.get(i);
                        nameb = arrayUsername.get(i);
                        if (gen.equals("1")) {
                            markerList
                                    .add(mMap.addMarker(new MarkerOptions()
                                            .position(new LatLng(lat1, lng1))
                                            .title(nameb)
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.bluesmilelarge))));
                        } else if (gen.equals("2")) {
                            markerList
                                    .add(mMap.addMarker(new MarkerOptions()
                                            .position(new LatLng(lat1, lng1))
                                            .title(nameb)
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.purplesmilelarge))));
                        } else {
                            markerList
                                    .add(mMap.addMarker(new MarkerOptions()
                                            .position(new LatLng(lat1, lng1))
                                            .title(nameb)
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.purplesmilelarge))));

                        }

                    }

                }
                dialog.dismiss();

            }

        }

        public String myMethod() throws IOException, JSONException {

            String url1 = "url";
            System.out.println("In get Category method" + url1);
            URL url = new URL(url1);
            URLConnection urlcon = url.openConnection();
            String jsonresponse = convertStreamToString(urlcon.getInputStream());

            Log.e("response", jsonresponse);

            return jsonresponse;
        }

        public String convertStreamToString(InputStream is) {
            if (is != null) {
                Writer writer = new StringWriter();
                char[] buffer = new char[1024];

                try {
                    Reader reader = new BufferedReader(new InputStreamReader(is,
                            "UTF-8"));
                    int n;
                    while ((n = reader.read(buffer)) != -1) {
                        writer.write(buffer, 0, n);
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return writer.toString();
            } else {
                return "";
            }
        }

        private String saveData(String result) {
            try {
                arrayLat = new ArrayList<Double>();
                arrayLong = new ArrayList<Double>();
                arrayGender = new ArrayList<String>();
                arrayUsername = new ArrayList<String>();
                arrayFrnd = new ArrayList<String>();
                markerList = new ArrayList<Marker>();
                JSONObject json = (JSONObject) new JSONTokener(result).nextValue();
                JSONObject json2 = json.getJSONObject("response");
                JSONArray jsonArray = json2.getJSONArray("incircle");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject objJson = jsonArray.getJSONObject(i);
                    test = objJson.getString("username");
                    arrayUsername.add(test);

                    friendid = objJson.getString("useid");
                    arrayFrnd.add(friendid);
                    Constant.FRIENDIDLIST.add(friendid);

                    lat = objJson.getString("lat");
                    Constant.LATITUDEFLIST.add(lat);
                    arrayLat.add(Double.parseDouble(lat));

                    lon = objJson.getString("log");
                    Constant.LONGITUDEFLIST.add(lon);
                    arrayLong.add(Double.parseDouble(lon));

                    gender = objJson.getString("gender");
                    arrayGender.add(gender);
                }
            } catch (JSONException e) {

                e.printStackTrace();
            }

            return test;

        }

        public void onBackPressed() {

            return;
        }




    }
4

1 回答 1

1

要在 infowindow 中显示不同的项目,您需要使用 infowindowadapter。这是示例代码。您可以从此处参考。

private GoogleMap googleMap;
private double[][] arrayLatLng = new double[][] { { 21.943046, 72.088989 }, { 26.843677, 73.407349 }, { 30.315988, 77.076782 }, { 29.05617, 82.042603 }, { 25.819672, 85.90979 },
        { 24.726875, 89.667114 }, { 22.87744, 86.766724 }, { 18.937464, 82.723755 }, { 15.411319, 79.603638 }, { 12.618897, 77.670044 }, { 15.771109, 74.747681 }, { 20.055931, 73.780884 } };
private String[] locationName = new String[] { "Bhavnagar, Gujarat", "Rajasthan", "Chandigarth", "Nepal", "Bihar", "Bangladesh", "West Bengal", "Orissa", "Andhra Pradesh", "Karnataka",
        "Bail Hongal, Maharastra", "Nasik, Maharastra" };

private MarkerInfoWindowAdapter infoWindowAdapter;

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

    googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
    googleMap.setOnMarkerClickListener(this);
    googleMap.setOnInfoWindowClickListener(this);
    googleMap.getUiSettings().setAllGesturesEnabled(true);
    // infoWindowAdapter = new MarkerInfoWindowAdapter();
    googleMap.setInfoWindowAdapter(infoWindowAdapter);

    final PolygonOptions polygonOptions = new PolygonOptions();
    polygonOptions.strokeColor(Color.BLUE);
    polygonOptions.strokeWidth(3);
    // polygonOptions.fillColor(Color.RED);

    for (int i = 0; i < arrayLatLng.length; i++) {
        final LatLng latLng = new LatLng(arrayLatLng[i][0], arrayLatLng[i][1]);
        polygonOptions.add(latLng);
        googleMap.addMarker(new MarkerOptions().position(latLng).title(locationName[i]).snippet(arrayLatLng[i][0] + ", " + arrayLatLng[i][1])
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker)));
        infoWindowAdapter = new MarkerInfoWindowAdapter();
        infoWindowAdapter.setTitle(locationName[i]);
        infoWindowAdapter.setDescription(locationName[i]);
    }
    googleMap.addPolygon(polygonOptions);
    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(arrayLatLng[0][0], arrayLatLng[0][1]), 4));
}

@Override
public boolean onMarkerClick(Marker marker) {
    Log.e("Marker Click", "Click Found");
    // marker.showInfoWindow();
    return false;
}

@Override
public void onInfoWindowClick(Marker marker) {
    if (marker.isInfoWindowShown()) {
        marker.hideInfoWindow();
    }
}

class MarkerInfoWindowAdapter implements InfoWindowAdapter {

    private View inflatedView;
    private View tempView;
    private String title, description;

    public void setTitle(String title) {
        this.title = title;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    MarkerInfoWindowAdapter() {
        inflatedView = getLayoutInflater().inflate(R.layout.location_info_window, null);
        tempView = getLayoutInflater().inflate(R.layout.location_content_window, null);
    }

    @Override
    public View getInfoContents(Marker marker) {
        setInfo(marker, inflatedView);
        return inflatedView;
    }

    @Override
    public View getInfoWindow(Marker marker) {
        setInfo(marker, inflatedView);
        return inflatedView;
    }

    private void setInfo(Marker marker, View view) {
        final TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
        final TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);
        txtTitle.setText(title);
        txtDescription.setText(description);
    }
}
于 2013-09-24T07:57:23.860 回答