如何在 Android 地图活动中显示特定标记?
Posted
技术标签:
【中文标题】如何在 Android 地图活动中显示特定标记?【英文标题】:How to show specific markers in Android Maps activity? 【发布时间】:2017-01-10 01:57:51 【问题描述】:我正在尝试创建一个显示每所大学的地图的 android 应用程序 |该地区/附近的学校。我查看了 SO 和 Google,只找到了有关如何添加标记、添加图块或显示特定 lat/lng 的教程,但是有没有办法根据特定参数显示特定标记?例如,如果我想显示所有大学/学校的每个标记,我将如何将这些参数传递给 MapFragment?我没有尝试过任何东西,因为我没有找到任何甚至暗示如何做到这一点的东西,除了对 web 应用程序 api 的引用,它对 Android 特定的 api 没有帮助。
【问题讨论】:
【参考方案1】:希望它有助于它的旅行指南应用程序代码
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);
);
比班级告诉附近的地方
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);
);
使用这个 MapyPane 类绘制标记
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();
【讨论】:
谢谢你,但它在哪里将指定位置显示为地图上的标记?【参考方案2】:那么您的问题的解决方案是 Android Places API....它允许您根据您的选择显示附近的地方...这将帮助您开始...https://developers.google.com/places/android-api/start
【讨论】:
但这不只是为了让用户“搜索”附近的地方而不是动态设置特定的地方吗? 我查看了该链接,但它没有指定如何传递某些参数以确保某些标记显示在用户当前位置附近的地图上。以上是关于如何在 Android 地图活动中显示特定标记?的主要内容,如果未能解决你的问题,请参考以下文章