Android 基于微调器值更新贴图
我成功地做了一个展示附近地方的活动。现在,我必须根据微调器值检索贴图,如果没有从微调器中选择值,则显示默认的世界贴图。假设我在活动的操作栏中有一个微调器,它由各种城市名称组成,如果我从微调器中选择纽约,纽约地图将显示在地图屏幕区域中。如果可能的话,有人能告诉我怎么做吗?如果可能的话,告诉我如何展示该城市著名的旅游景点。我还没有找到任何有益的教程。任何帮助都将不胜感激 My NearbyPlacesActivity.javaAndroid 基于微调器值更新贴图,android,google-maps,spinner,google-places-api,Android,Google Maps,Spinner,Google Places Api,我成功地做了一个展示附近地方的活动。现在,我必须根据微调器值检索贴图,如果没有从微调器中选择值,则显示默认的世界贴图。假设我在活动的操作栏中有一个微调器,它由各种城市名称组成,如果我从微调器中选择纽约,纽约地图将显示在地图屏幕区域中。如果可能的话,有人能告诉我怎么做吗?如果可能的话,告诉我如何展示该城市著名的旅游景点。我还没有找到任何有益的教程。任何帮助都将不胜感激 My NearbyPlacesActivity.java public class NearbyPlacesActivity ex
public class NearbyPlacesActivity extends Activity implements LocationListener {
//instance variables for Marker icon drawable resources
private int userIcon, foodIcon, drinkIcon, shopIcon, otherIcon;
//the map
private GoogleMap theMap;
//location manager
private LocationManager locMan;
//gps tracker and connnection detect to be included
//user marker
private Marker userMarker;
//places of interest
private Marker[] placeMarkers;
//max
private final int MAX_PLACES = 20;//most returned from google
//marker options
private MarkerOptions[] places;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby_places);
//get drawable IDs
userIcon = R.drawable.yellow_point;
foodIcon = R.drawable.red_point;
drinkIcon = R.drawable.blue_point;
shopIcon = R.drawable.green_point;
otherIcon = R.drawable.purple_point;
//find out if we already have it
if(theMap==null){
//get the map
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
//check in case map/ Google Play services not available
if(theMap!=null){
//ok - proceed
theMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//create marker array
placeMarkers = new Marker[MAX_PLACES];
}
}
}
//location listener functions
@Override
public void onLocationChanged(Location location) {
Log.v("MyMapActivity", "location changed");
updatePlaces(location);
}
@Override
public void onProviderDisabled(String provider){
Log.v("MyMapActivity", "provider disabled");
}
@Override
public void onProviderEnabled(String provider) {
Log.v("MyMapActivity", "provider enabled");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.v("MyMapActivity", "status changed");
}
/*
* update the place markers
*/
private void updatePlaces(Location givenlocation){
//get location manager
double lat = givenlocation.getLatitude();
double lng = givenlocation.getLongitude();
//create LatLng
LatLng lastLatLng = new LatLng(lat, lng);
//remove any existing marker
if(userMarker!=null) userMarker.remove();
//create and set marker properties
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title("You are here")
.icon(BitmapDescriptorFactory.fromResource(userIcon))
.snippet("Your last recorded location"));
//move to location
theMap.animateCamera(CameraUpdateFactory.newLatLng(lastLatLng), 3000, null);
//build places query string
@SuppressWarnings("deprecation")
String encodedstr = URLEncoder.encode("food|bar|movie_theater|museum|bank");
String placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=7000&sensor=true"+
"&types="+encodedstr+
"&key=AIzaSyBqDgqbxFenOtooTivY5YSsJ2JrwBK42hw";//ADD KEY
//execute query
new GetPlaces().execute(placesSearchStr);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
}
private class GetPlaces extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... placesURL) {
//fetch places
//build result as string
StringBuilder placesBuilder = new StringBuilder();
//process search parameter string(s)
for (String placeSearchURL : placesURL) {
HttpClient placesClient = new DefaultHttpClient();
try {
//try to fetch the data
//HTTP Get receives URL string
HttpGet placesGet = new HttpGet(placeSearchURL);
//execute GET with Client - return response
HttpResponse placesResponse = placesClient.execute(placesGet);
//check response status
StatusLine placeSearchStatus = placesResponse.getStatusLine();
//only carry on if response is OK
if (placeSearchStatus.getStatusCode() == 200) {
//get response entity
HttpEntity placesEntity = placesResponse.getEntity();
//get input stream setup
InputStream placesContent = placesEntity.getContent();
//create reader
InputStreamReader placesInput = new InputStreamReader(placesContent);
//use buffered reader to process
BufferedReader placesReader = new BufferedReader(placesInput);
//read a line at a time, append to string builder
String lineIn;
while ((lineIn = placesReader.readLine()) != null) {
placesBuilder.append(lineIn);
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
return placesBuilder.toString();
}
//process data retrieved from doInBackground
protected void onPostExecute(String result) {
//parse place data returned from Google Places
//remove existing markers
if(placeMarkers!=null){
for(int pm=0; pm<placeMarkers.length; pm++){
if(placeMarkers[pm]!=null)
placeMarkers[pm].remove();
}
}
try {
//parse JSON
//create JSONObject, pass stinrg returned from doInBackground
JSONObject resultObject = new JSONObject(result);
//get "results" array
JSONArray placesArray = resultObject.getJSONArray("results");
//marker options for each place returned
places = new MarkerOptions[placesArray.length()];
//loop through places
for (int p=0; p<placesArray.length(); p++) {
//parse each place
//if any values are missing we won't show the marker
boolean missingValue=false;
LatLng placeLL=null;
String placeName="";
String vicinity="";
int currIcon = otherIcon;
try{
//attempt to retrieve place data values
missingValue=false;
//get place at this index
JSONObject placeObject = placesArray.getJSONObject(p);
//get location section
JSONObject loc = placeObject.getJSONObject("geometry")
.getJSONObject("location");
//read lat lng
placeLL = new LatLng(Double.valueOf(loc.getString("lat")),
Double.valueOf(loc.getString("lng")));
//get types
JSONArray types = placeObject.getJSONArray("types");
//loop through types
for(int t=0; t<types.length(); t++){
//what type is it
String thisType=types.get(t).toString();
//check for particular types - set icons
if(thisType.contains("food")){
currIcon = foodIcon;
break;
}
else if(thisType.contains("bar")){
currIcon = drinkIcon;
break;
}
else if(thisType.contains("movie_theater")){
currIcon = shopIcon;
break;
}
}
//vicinity
vicinity = placeObject.getString("vicinity");
//name
placeName = placeObject.getString("name");
}
catch(JSONException jse){
Log.v("PLACES", "missing value");
missingValue=true;
jse.printStackTrace();
}
//if values missing we don't display
if(missingValue) places[p]=null;
else
places[p]=new MarkerOptions()
.position(placeLL)
.title(placeName)
.icon(BitmapDescriptorFactory.fromResource(currIcon))
.snippet(vicinity);
}
}
catch (Exception e) {
e.printStackTrace();
}
if(places!=null && placeMarkers!=null){
for(int p=0; p<places.length && p<placeMarkers.length; p++){
//will be null if a value was missing
if(places[p]!=null)
placeMarkers[p]=theMap.addMarker(places[p]);
}
}
}
}
@Override
protected void onResume() {
super.onResume();
if(theMap!=null){
//get location manager
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//get last location
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
updatePlaces(lastLoc);
}
}
@Override
protected void onPause() {
super.onPause();
if(theMap!=null){
locMan.removeUpdates(this);
}
}
}
公共类nearbyplaceActivity扩展活动实现LocationListener{
//标记图标可绘制资源的实例变量
私有int userIcon、foodIcon、drinkIcon、shopIcon、otherIcon;
//地图
私人谷歌地图;
//位置管理器
私人场所经理洛克曼;
//包括gps跟踪器和连接检测
//用户标记
专用标记用户标记;
//名胜古迹
专用标记[]位置标记;
//马克斯
private final int MAX_PLACES=20;//大部分从google返回
//标记选项
私人市场选择[]个地点;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u附近的位置);
//获取可提取ID
userIcon=R.drawable.yellow\u点;
foodIcon=R.可绘制的红色点;
drinkIcon=R.可绘制.蓝色\u点;
shopIcon=R.drawable.green\u point;
otherIcon=R.drawable.purple_点;
//看看我们是否已经有了它
if(theMap==null){
//去拿地图
theMap=((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
//签入案例地图/谷歌播放服务不可用
如果(theMap!=null){
//好-继续
setMapType(GoogleMap.MAP\u TYPE\u NORMAL);
//创建标记数组
placeMarkers=新标记[最大位置];
}
}
}
//位置侦听器函数
@凌驾
已更改位置上的公共无效(位置){
Log.v(“MyMapActivity”,“位置更改”);
更新位置(位置);
}
@凌驾
公共无效onProviderDisabled(字符串提供程序){
Log.v(“MyMapActivity”、“提供程序已禁用”);
}
@凌驾
公共无效onProviderEnabled(字符串提供程序){
Log.v(“MyMapActivity”,“已启用提供程序”);
}
@凌驾
public void onStatusChanged(字符串提供程序、int状态、Bundle extra){
Log.v(“MyMapActivity”,“状态更改”);
}
/*
*更新位置标记
*/
私有void updatePlaces(位置给定位置){
//获取位置管理器
双lat=givenlocation.getLatitude();
double lng=givenlocation.getLongitude();
//创建板条
LatLng lastLatLng=新LatLng(lat,lng);
//删除任何现有标记
如果(userMarker!=null)userMarker.remove();
//创建和设置标记属性
userMarker=theMap.addMarker(新标记选项()
.位置(最后一个)
.title(“您在这里”)
.icon(BitmapDescriptorFactory.fromResource(userIcon))
.snippet(“您上次录制的位置”);
//移动到位置
theMap.animateCamera(CameraUpdateFactory.newLatLng(lastLatLng),3000,空);
//生成位置查询字符串
@抑制警告(“弃用”)
String encodedstr=URLEncoder.encode(“食品|酒吧|电影院|博物馆|银行”);
字符串placesSearchStr=”https://maps.googleapis.com/maps/api/place/nearbysearch/" +
“json”位置=“+lat+”,“+lng+
“&radius=7000&sensor=true”+
“&types=“+编码器”+
“&key=aizasybqdgqbxfenototivity5yssj2jrwbk42hw”;//添加密钥
//执行查询
新建GetPlaces().execute(placesSearchStr);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,30000100,this);
}
私有类GetPlaces扩展异步任务{
@凌驾
受保护的字符串背景(字符串…placesURL){
//找地方
//将结果生成为字符串
StringBuilder placesBuilder=新StringBuilder();
//进程搜索参数字符串
for(字符串placeSearchURL:placesURL){
HttpClient placesClient=new DefaultHttpClient();
试一试{
//尝试获取数据
//HTTP Get接收URL字符串
HttpGet placesGet=新的HttpGet(placeSearchURL);
//使用客户端返回响应执行GET
HttpResponse placesResponse=placesClient.execute(placesGet);
//检查响应状态
StatusLine placeSearchStatus=placesResponse.getStatusLine();
//只有在响应正常时才能继续
if(placeSearchStatus.getStatusCode()==200){
//获取响应实体
HttpEntity placesEntity=placesResponse.getEntity();
//获取输入流设置
InputStream placesContent=placesEntity.getContent();
//创建阅读器
InputStreamReader placesInput=新的InputStreamReader(placesContent);
//使用缓冲读取器来处理
BufferedReader placesReader=新的BufferedReader(placesInput);
//一次读取一行,附加到字符串生成器
弦线;
而((lineIn=placesReader.readLine())!=null){
placesBuilder.append(lineIn);
yourpinner.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});