簡體   English   中英

在適用於Android的Google Maps API v2中使用多個標記

[英]use multiple markers in google maps api v2 for android

我正在使用Google Maps api v2 for android在infoWindow中顯示商家詳細信息以實現此目的,我使用asynctask從服務器加載交易詳細信息。 用戶單擊標記時,需要顯示信息窗口。

我的問題是我為所有標記都獲得了相同的信息窗口(相同的數據),我應該怎么做才能在信息窗口中顯示標記信息?

另一個問題是由於某種原因,onMarkerClick()回調不起作用。

我將很樂意編寫代碼示例或告訴我如何使用infoWindowAdapter以及onMarkerClick為什么不起作用?

public class GetDealsNearbyTask extends AsyncTask<String, Integer, List<Deal>>{
Context context;
Editor editor;
SharedPreferences settings;
Editor settingsEditor;
private FragmentActivity activity;
private UserUtil user;
private GoogleMap map;

HashMap<Marker, Deal> dealMarker;


public GetDealsNearbyTask(Context context, FragmentActivity activity) {
    this.context = context;
    this.activity = activity;
    settings = context.getSharedPreferences(Constants.SETTINGS_FILE_NAME,Context.MODE_PRIVATE);
    settingsEditor = settings.edit();
    user = new UserUtil(activity);

}

@Override
protected void onPreExecute() {
}

@Override
protected List<Deal> doInBackground(String... urls) {
    HttpConnection httpConnection = new HttpConnection(urls[0]);
    String currentSecurityToken = settings.getString(Constants.SECURITY_TOKEN, null);
    JSONObject json = new JSONObject();
    double lat = user.getSelfLocation().getLatitude();
    double lon = user.getSelfLocation().getLongitude();

    // JSON data:
    try {
        json.put(Constants.SECURITY_TOKEN, currentSecurityToken);
        json.put(Constants.Latitude, lat);
        json.put(Constants.Longitude, lon);

    } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    // Set HTTP parameters
    StringEntity se = null;
    try {
        se = new StringEntity(json.toString());
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    httpConnection.AddParam(se);
    httpConnection.AddHeader("Content-type", "application/json");

    try {
        httpConnection.Execute(RequestMethod.POST);
    } catch (Exception e) {
        e.printStackTrace();
    }

    String response = httpConnection.getResponse();
    String errorMessage = httpConnection.getErrorMessage();
    if (errorMessage.equalsIgnoreCase("OK")){
        return saveToPreferences(response);
    }else{
        return null;
    }
}

private List<Deal> saveToPreferences(String response) {
    List<Deal> deals = null;
    try {
        JSONObject responseObject = new JSONObject(response);
        String securityToken = (String)responseObject.get(Constants.SECURITY_TOKEN);
        settingsEditor.putString(Constants.SECURITY_TOKEN, securityToken).commit();
        String status = (String)responseObject.get("Status");

        JSONArray results = responseObject.getJSONArray("Results");
        deals = new ArrayList<Deal>();
        for (int i = 0; i < results.length(); i++) { 
            JSONObject jDeal = results.getJSONObject(i);
            String branchAdress = jDeal.getString(Constants.BranchAdress);
            String branchName = jDeal.getString(Constants.BranchName);
            String currency = jDeal.getString(Constants.Currency);
            int actualPrice = jDeal.getInt(Constants.ActualPrice);
            int dealCode = jDeal.getInt(Constants.DealCode);
            String discount = jDeal.getString(Constants.Discount);
            int distance = jDeal.getInt(Constants.Distance);
            String endDateTime = jDeal.getJSONObject(Constants.Ending).getString(Constants.ExpirationDateTime);
            int interestCode = jDeal.getInt(Constants.InterestCode);
            double lat = jDeal.getDouble(Constants.Latitude);
            double lon = jDeal.getDouble(Constants.Longitude);
            int ourPick = jDeal.getInt(Constants.OurPick);
            int rating = jDeal.getInt(Constants.Rating);
            String title = jDeal.getString(Constants.Title);
            String smallImageUrl = jDeal.getString("SmallPhoto");
            deals.add(new Deal(interestCode, dealCode, rating, title, branchName, smallImageUrl, branchAdress, endDateTime, lat, lon));

        }
    }catch (JSONException e) {
        e.printStackTrace();
    }
    return deals;

}
@Override
protected void onPostExecute(final List<Deal> data) {
    // get reference to GoogleMap
    this.map = null;
    SupportMapFragment mapFragment = (SupportMapFragment) activity.getSupportFragmentManager().findFragmentById(R.id.map);
    this.map = mapFragment.getMap();

    // move camera to self location
    LatLng selfLocation = new LatLng(user.getSelfLocation().getLatitude(), user.getSelfLocation().getLongitude());
    map.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(selfLocation, 10, 0, 0)));


    // set self location marker configuration
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(selfLocation );
    markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.logo));
    markerOptions.title("this is you!");
    map.addMarker(markerOptions);

    // add deals markers
    for (final Deal deal : data) {
        int markerIcon = R.drawable.ic_menu_preferences;
        switch (deal.getInterestCode()) {
        case 2:
            markerIcon =  (R.drawable.books_blue);
            break;
        case 3:
            markerIcon =  (R.drawable.rest_blue);
            break;
        case 4:
            markerIcon =  (R.drawable.bar_blue);
            break;
        case 5:
            markerIcon =  ( R.drawable.electronic_blue);
            break;
        case 6:
            markerIcon =  (R.drawable.spa_blue);
            break;
        case 7:
            markerIcon =  (R.drawable.sports_blue);
            break;
        case 8:
            markerIcon =  (R.drawable.cloth_blue);
            break;
        case 9:
            markerIcon =  (R.drawable.coffee_blue);
            break;

        default:
            break;
        }
        try {
            Marker marker = map.addMarker(new MarkerOptions().position(new LatLng(deal.getLat(), deal.getLon())).title("Marker").icon(BitmapDescriptorFactory.fromResource(markerIcon)));
            dealMarker.put(marker, deal);

        } catch (Exception e) {
            Log.e("MAP", "faild adding marker in " + deal.getLat() + " , " + deal.getLon() + " interestCode: " + deal.getInterestCode() + "message: " + e.getMessage());
        }

    }

    // handle click event for the markers
    map.setOnMarkerClickListener(new OnMarkerClickListener() {

        @Override
        public boolean onMarkerClick(Marker marker) {
            Deal deal = dealMarker.get(marker);
            Toast.makeText(context, "the title is: " + deal.getTitle(), Toast.LENGTH_SHORT).show();
            GoozInfoWindowAdapter adapter = new GoozInfoWindowAdapter(activity.getLayoutInflater(), deal);
            map.setInfoWindowAdapter(adapter);
            marker.showInfoWindow();
            return false;
        }
    });

}




private Marker placeMarker(Deal deal) {
      Marker m  = map.addMarker(new MarkerOptions()
       .position(new LatLng(deal.getLat(),deal.getLon()))
       .title(deal.getTitle()));
    return m;
}

@Override
protected void onProgressUpdate(Integer... progress) {

}

請看一下InfoWindowAdapter代碼,其中的注釋解釋了幾乎每一行的內容。

   // Defines the contents of the InfoWindow
            @Override
            public View getInfoContents(Marker args) {

                // 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
                clickMarkerLatLng = args.getPosition();

                TextView title = (TextView) v.findViewById(R.id.tvTitle);
                title.setText(args.getTitle());

                //Setting the click listener
                map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {          
                    public void onInfoWindowClick(Marker marker) 
                    {
                        //Check if the clicked marker is my location
                        if (SGTasksListAppObj.getInstance().currentUserLocation!=null)
                        {   
                            if (String.valueOf(SGTasksListAppObj.getInstance().currentUserLocation.getLatitude()).substring(0, 8).contains(String.valueOf(clickMarkerLatLng.latitude).substring(0, 8)) &&
                                    String.valueOf(SGTasksListAppObj.getInstance().currentUserLocation.getLongitude()).substring(0, 8).contains(String.valueOf(clickMarkerLatLng.longitude).substring(0, 8)))
                            {
                                Toast.makeText(getApplicationContext(), "This your current location, navigation is not needed.",  Toast.LENGTH_SHORT).show();
                            }
                            else
                            {
                                FlurryAgent.onEvent("Start navigation window was clicked from daily map");
                                tasksRepository = SGTasksListAppObj.getInstance().tasksRepository.getTasksRepository();
                                for (Task tmptask : tasksRepository)
                                {
                                    String tempTaskLat = String.valueOf(tmptask.getLatitude());
                                    String tempTaskLng = String.valueOf(tmptask.getLongtitude());

                                    Log.d(TAG, String.valueOf(tmptask.getLatitude())+","+String.valueOf(clickMarkerLatLng.latitude).substring(0, 8));

                                    if (tempTaskLat.contains(String.valueOf(clickMarkerLatLng.latitude).substring(0, 8)) && tempTaskLng.contains(String.valueOf(clickMarkerLatLng.longitude).substring(0, 8)))
                                    {  
                                        task = tmptask;
                                        break;
                                    }
                                }
                                Intent intent = new Intent(getApplicationContext() ,RoadDirectionsActivity.class);
                                intent.putExtra(TasksListActivity.KEY_ID, task.getId());
                                startActivity(intent);

                            }
                        }
                        else
                        {
                            Toast.makeText(getApplicationContext(), "Your current location could not be found,\nNavigation is not possible.",  Toast.LENGTH_SHORT).show();
                        }
                    }
                });

                // Returning the view containing InfoWindow contents
                return v;

            }
        });  

使用map.setInfoWindowAdapter時遇到相同的行為(所有標記具有相同數據的相同信息窗口),這就是為我解決的問題:經過一些調試,我發現當用戶單擊鼠標左鍵時,對setInfoWindowAdapter()的調用已完成。標記。 對我來說,我用來在視圖中設置屬性的對象不再是作用域。 我更改了代碼,以便在運行時獲取對象,然后在視圖中設置屬性。

map.setInfoWindowAdapter(new InfoWindowAdapter() {

    @Override
    public View getInfoContents(Marker marker) {

        View view = instance.getLayoutInflater(getArguments()).inflate(R.layout.my_infowindow, null);

        TextView row1 = (TextView)view.findViewById(R.id.row1);
        TextView row2 = (TextView)view.findViewById(R.id.row2);

        // Get the object so you can use it to set properties in the view
        // In my case I have an ArrayList of Objects. One of the properties of the object is a String that is the same as marker.getTitle() but whatever you need to do, get your runtime data:
        Object myObj = getMyObject(marker.getTitle);

        row1.setText(myObj.getPropertyOne());
        row2.setText(myObj.getPropertyTwo());

        return view;
    }

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM