【问题标题】:use multiple markers in google maps api v2 for android在 google maps api v2 for android 中使用多个标记
【发布时间】:2013-04-02 05:59:12
【问题描述】:

我正在使用 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) {

}

【问题讨论】:

    标签: android google-maps-api-2


    【解决方案1】:

    看看InfoWindowAdapter 的这段代码,几乎每一行都有 cmets 解释做了什么。

       // 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;
    
                }
            });  
    

    【讨论】:

    • 您好,埃米尔,感谢您的回答。很遗憾。它根本没有回答我的问题,事实上我在某个地方看到了你的例子......任何想法为什么 onclick 不起作用??
    • 我发布的方法对我有用,至少对这里的几个人有用……所以你可能做错了什么。你是什​​么意思它不能回答你的问题。这样您就可以为每个标记创建一个新的信息窗口。关于 onClick,如果您仔细按照此代码 sn-p 操作,它将为您工作。
    【解决方案2】:

    我在使用 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;
        }
    
    });
    

    【讨论】:

      猜你喜欢
      • 2015-08-14
      • 2013-03-14
      • 2012-12-31
      • 1970-01-01
      • 2013-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-14
      相关资源
      最近更新 更多