简体   繁体   中英

How to show specific markers in Android Maps activity?

I am trying to create an Android app that displays a Map that shows every university | school in the area/nearby. I've looked over SO and Google and have only found tutorials on how to add markers, add tiles, or show a specific lat/lng but is there a way to show specific markers based on specific parameters? For example, if I want to show every marker for all universities/schools how would I go about passing those parameters to the MapFragment? I haven't tried anything because I haven't found anything that even hints at how to do that except for a reference to the web app api which didn't help for the Android specific api.

Hope it helps its a travel guide app code

    public class SearchPlaceType extends Activity
{
    String[] itemTypeName ={
            "airport",
            "atm",
            "bank",
            "bus_station",
            "gas_station",
            "hospital",
            "mosque",
            "park",
            "restaurant",
            "university",
            "food"

        };

    ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.search_place_type);

        listView = (ListView)findViewById(R.id.typeList);

        listView.setAdapter(new PlaceTypeAdapter(SearchPlaceType.this, itemTypeName));

        listView.setOnItemClickListener(new OnItemClickListener() 
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) 
            {
                Intent intent = new Intent(SearchPlaceType.this,NearByPlaces.class);

                intent.putExtra("positionOfType", (int)position);

                startActivity(intent);
            }
        });
    }

}

Than class to tell the near by places

public class NearByPlaces extends Activity
{
    ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

    ListView listView;

    int positionOfType = 0;

    Context context;

    MyLocation myLocation;

    double current_location_lat, current_location_lng;

    public static String latStr = "";
    public static String longStr = "";

    public static LatLng myLatLng = null;

    public static LatLng destinationLatLng = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.near_by_places);

        context = NearByPlaces.this;

        Bundle extras = getIntent().getExtras();

        if(extras!=null)
        {
            positionOfType = extras.getInt("positionOfType", positionOfType);
        }

        listView = (ListView)findViewById(R.id.nearbyList);

        myLocation = new MyLocation(context);

        if (myLocation.isLocationAvailable() && myLocation.getUserLocation() != null)
        {
            current_location_lat =  myLocation.getUserLocation().latitude;

            current_location_lng =  myLocation.getUserLocation().longitude;

            latStr = current_location_lat + "";

            longStr = current_location_lng + "";

            myLatLng = new LatLng(current_location_lat, current_location_lng);

            //url = url_part1 + latStr + "," + longStr + url_part2;

            Log.d("LATITUDE", String.valueOf(current_location_lat));

            Log.d("LONGITUDE", String.valueOf(current_location_lng));


            new PlaceTask(context, positionOfType, latStr, longStr, new onTaskDoneListener() 
            {
                @Override
                public void onTaskDone(JSONObject jsonObject) 
                {
                    if(jsonObject!=null)
                    {
                        try 
                        {
                            JSONObject obj = jsonObject;//new JSONObject(jsonObject);

                            String status = obj.getString("status");

                            if(status.equals("OK"))
                            {
                                JSONArray arr = obj.getJSONArray("results");

                                for(int i = 0; i < arr.length(); i++)
                                {
                                    double lat = arr.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lat");

                                    double lng = arr.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lng"); 

                                    String place_name = arr.getJSONObject(i).getString("name");

                                    String vicinity = arr.getJSONObject(i).getString("vicinity");

                                    HashMap<String, String> map = new HashMap<String,String>();

                                    map.put("placeName", place_name);

                                    map.put("vicinity", vicinity);

                                    map.put("lat", String.valueOf(lat));

                                    map.put("lng", String.valueOf(lng));

                                    list.add(map);
                                }

                                NearByPlaceAdapter adapter = new NearByPlaceAdapter(context, list);

                                listView.setAdapter(adapter);
                            }
                        } 
                        catch (JSONException e) 
                        {
                            e.printStackTrace();
                        }
                    }
                    else
                    {
                        Toast.makeText(context, "Response is Null", Toast.LENGTH_LONG).show();
                    }

                }
            }).execute();

            //showSearchDialog(map);    
        }               
        else
        {
            Toast.makeText(context, "Please Enable Location Services and GPS From your Device", 
                    Toast.LENGTH_LONG).show();
        }       

        listView.setOnItemClickListener(new OnItemClickListener() 
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) 
            {
                HashMap<String, String> map = list.get(position);

                Intent intent = new Intent(context,DirectionActivity3.class);

                destinationLatLng = new LatLng(Double.valueOf(map.get("lat")), Double.valueOf(map.get("lat")));

                startActivity(intent);
            }
        });
    }

}

Draw marker using this MapyPane class

public class MapyPane extends Activity implements OnMapReadyCallback 
{
    String[] itemTypeName ={
            "airport",
            "atm",
            "bank",
            "bus_station",
            "gas_station",
            "hospital",
            "mosque",
            "park",
            "restaurant",
            "university",
            "food"

        };

    Marker myMarker;

    GMapV2Direction md;

    MyLocation myLocation;

    GoogleMap googleMap;

    double current_location_lat, current_location_lng;

    public static String latStr = "";
    public static String longStr = "";

    Dialog searchDialog;

    ImageView searchDialogIv;
    ImageView searchIcon;

    EditText searchText;

    Context context;

    Integer[] imageId = {
            R.drawable.school_3,
            R.drawable.atm_3,
            R.drawable.school_3,
            R.drawable.police_station_3,
            R.drawable.cng_station_3,//5
            R.drawable.hospital_3,
            R.drawable.school_3,
            R.drawable.hospital_3,//8
            R.drawable.hotel_3,
            R.drawable.cng_station_3,
            R.drawable.hotel_3
    };

    int positionToFind =  0;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        context = MapyPane.this;

        md = new GMapV2Direction();


        MapFragment mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.fragment_map);

        mapFragment.getMapAsync(this);

        googleMap = mapFragment.getMap();//my doctory..

        Bundle extras = getIntent().getExtras();

        if(extras!=null)
        {
            positionToFind = extras.getInt("positionToFind", positionToFind);
        }




        searchText = (EditText)findViewById(R.id.search_text);

        searchDialogIv = (ImageView)findViewById(R.id.search_dialogIv);

        searchDialogIv.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if(googleMap==null)
                {
                    Toast.makeText(context, "Unable to load Map", Toast.LENGTH_LONG).show();
                }
                else
                {
                    showSearchDialog(googleMap);
                }
            }
        });

        searchIcon = (ImageView)findViewById(R.id.search_icon);

        searchIcon.setVisibility(View.GONE);

        searchText.setVisibility(View.GONE);

        searchIcon.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //if(sear)
                new PlaceTask(context, searchText.getText().toString(), latStr, longStr, new onTaskDoneListener()
                {
                    @Override
                    public void onTaskDone(JSONObject jsonObject)
                    {
                        //drawMarkersOnMap(jsonObject, googleMap,postponeEnterTransition());
                    }
                }).execute();
            }
        });
    }

    /*public void drawPathBetween(LatLng sourcePosition,LatLng destPosition,GoogleMap mMap)
    {
        Document doc = md.getDocument(sourcePosition, destPosition,
                GMapV2Direction.MODE_DRIVING);

        ArrayList<LatLng> directionPoint = md.getDirection(doc);
        PolylineOptions rectLine = new PolylineOptions().width(3).color(
                Color.RED);

        for (int i = 0; i < directionPoint.size(); i++) 
        {
            rectLine.add(directionPoint.get(i));
        }
        Polyline polylin = mMap.addPolyline(rectLine);
    }*/

    @Override
    public void onMapReady(GoogleMap map) 
    {
        // check if map is created successfully or not
        if (map == null) 
        {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to load maps", Toast.LENGTH_SHORT)
                    .show();
        }
        else
        {           
            myLocation = new MyLocation(MapyPane.this, map);

            if (myLocation.isLocationAvailable() && myLocation.getUserLocation() != null)
            {
                current_location_lat =  myLocation.getUserLocation().latitude;

                current_location_lng =  myLocation.getUserLocation().longitude;

                latStr = current_location_lat + "";

                longStr = current_location_lng + "";

                //url = url_part1 + latStr + "," + longStr + url_part2;

                Log.d("LATITUDE", String.valueOf(current_location_lat));

                Log.d("LONGITUDE", String.valueOf(current_location_lng));

                // Showing Current Location

                map.setMyLocationEnabled(true);


                // Move the camera instantly to hamburg with a zoom of 15.
                map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(current_location_lat, current_location_lng), 15));

                // Zoom in, animating the camera.
                map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);



                // Moving Camera to a Location with animation

                /*CameraPosition cameraPosition = new CameraPosition.Builder().target(
                        new LatLng(current_location_lat, current_location_lng)).zoom(12).build();

                //CameraPosition cameraPosition = new CameraPosition.Builder().target(
                //new LatLng( -33.8650, 151.2094)).zoom(12).build();

                map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));*/



                MarkerOptions markerOptions = new MarkerOptions().title("YourLocation").position(new LatLng(current_location_lat, current_location_lng)).icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.gas_station));//gas_station


                myMarker = map.addMarker(markerOptions);


                new PlaceTask(context, positionToFind, latStr, longStr, new onTaskDoneListener() {

                    @Override
                    public void onTaskDone(JSONObject jsonObject) 
                    {

                    }
                });

                //showSearchDialog(map);    
            }               
            else
            {
                Toast.makeText(MapyPane.this, "Please Enable Location Services and GPS From your Device", 
                        Toast.LENGTH_LONG).show();
            }           
        }

       /* LatLng sydney = new LatLng(-33.867, 151.206);

        map.setMyLocationEnabled(true);
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));

        map.addMarker(new MarkerOptions()
                .title("Sydney")
                .snippet("The most populous city in Australia.")
                .position(sydney));*/


        /*map.moveCamera(CameraUpdateFactory.newLatLngZoom(
                new LatLng(41.889, -87.622), 16));

        // You can customize the marker image using images bundled with
        // your app, or dynamically generated bitmaps.
        map.addMarker(new MarkerOptions()
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
                .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
                .position(new LatLng(41.889, -87.622)));*/
    }

    private void drawMarkersOnMap(JSONObject jsonObject,final GoogleMap googleMap,int posi)
    {
        if(jsonObject!=null)
        {
            googleMap.clear();

            try 
            {
                JSONObject obj = jsonObject;//new JSONObject(jsonObject);

                String status = obj.getString("status");

                if(status.equals("OK"))
                {
                    JSONArray arr = obj.getJSONArray("results");

                    for(int i = 0; i < arr.length(); i++)
                    {
                        double lat = arr.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lat");

                        double lng = arr.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lng"); 

                        String food_name = arr.getJSONObject(i).getString("name");

                        String vicinity = arr.getJSONObject(i).getString("vicinity");

                        MarkerOptions marker = new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory
                                .fromResource( imageId[posi]));// R.drawable.ic_launcher));//gas_station


                        marker.title(food_name);

                        marker.snippet(vicinity);

                        final Marker testMarker = googleMap.addMarker(marker);

                        googleMap.setOnMarkerClickListener(new OnMarkerClickListener()
                        {
                            @Override
                            public boolean onMarkerClick(Marker markker)
                            {
                                if(markker.equals(testMarker))
                                {
                                    //drawPathBetween(myMarker.getPosition(), markker.getPosition(), googleMap);
                                }
                                else
                                {

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

    private void showSearchDialog(final GoogleMap map) 
    {
        searchDialog = new Dialog(MapyPane.this);

        searchDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

        searchDialog.setContentView(R.layout.menu_item_custom_dialog);      

        searchDialog.setCanceledOnTouchOutside(false);

        ListView list;
        final String[] web = {
                "airport",
                "atm",
                "bank",
                "bus_station",
                "gas_station",  //department_store  ya home_goods_store
                "hospital",  //health
                "mosque",//7
                "park",
                "restaurant",//instead of hotels
                "university",
                "Food"
        } ;
        Integer[] imageId = {
                R.drawable.school_3,
                R.drawable.atm_3,
                R.drawable.school_3,
                R.drawable.police_station_3,
                R.drawable.cng_station_3,//5
                R.drawable.hospital_3,
                R.drawable.school_3,
                R.drawable.hospital_3,//8
                R.drawable.hotel_3,
                R.drawable.cng_station_3,
                R.drawable.hotel_3
        };

        CustomList adapter = new
                CustomList(MapyPane.this, web, imageId);

        list = (ListView) searchDialog.findViewById(R.id.list_location);
        list.setAdapter(adapter);

        ///list.setSelector(R.drawable.list_item_selector);

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    final int position, long id) {
                //Toast.makeText(MapyPane.this, "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();

                ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

                if (mWifi.isConnected())
                {
                    if(latStr.equals(""))
                    {
                        Toast.makeText(MapyPane.this, " please enable your gps location ", Toast.LENGTH_SHORT).show();
                    }

                    else
                    {
                        new PlaceTask(MapyPane.this, position, latStr, longStr, new onTaskDoneListener()
                        {
                            @Override
                            public void onTaskDone(JSONObject jsonObject)
                            {
                                drawMarkersOnMap(jsonObject, map,position);
                            }
                        }).execute();

                        searchDialog.dismiss();
                    }       
                }
                else
                {
                    Toast.makeText(MapyPane.this, "Internet is not available", Toast.LENGTH_SHORT).show();
                }
            }
        });

        searchDialog.show();

    }

}

然后问题的解决方案是Android Places API ....它允许您根据您的选择显示附近的地点...这将有助于您入门... https://developers.google.com/places/ Android的API /启动

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM