Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/229.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 清除除我所在位置以外的地图标记_Android_Google Maps_Google Places - Fatal编程技术网

Android 清除除我所在位置以外的地图标记

Android 清除除我所在位置以外的地图标记,android,google-maps,google-places,Android,Google Maps,Google Places,我正在寻找地图上我的位置附近的地方。当我更改地点类别时,我希望地图从上一次搜索的标记中清除,但我位置的标记始终存在。“mGoogleMap.clear();”清除所有标记,包括我所在位置的标记。我怎样才能改变这一点 这是我的主要活动: package com.example.mobiletourismapp; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import

我正在寻找地图上我的位置附近的地方。当我更改地点类别时,我希望地图从上一次搜索的标记中清除,但我位置的标记始终存在。“mGoogleMap.clear();”清除所有标记,包括我所在位置的标记。我怎样才能改变这一点

这是我的主要活动:

package com.example.mobiletourismapp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.animation.ValueAnimator;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;




public class MainActivity extends FragmentActivity implements LocationListener{

    GoogleMap mGoogleMap;   
    Spinner mSprPlaceType;  

    String[] mPlaceType=null;
    String[] mPlaceTypeName=null;

    double mLatitude=0;
    double mLongitude=0;

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


    @Override
    protected void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     

        // Array of place types
        mPlaceType = getResources().getStringArray(R.array.place_type);

        // Array of place type names
        mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);

        // Creating an array adapter with an array of Place types
        // to populate the spinner
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);

        // Getting reference to the Spinner 
        mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);

        // Setting adapter on Spinner to set place types
        mSprPlaceType.setAdapter(adapter);

        Button btnFind;

        // Getting reference to Find Button
        btnFind = ( Button ) findViewById(R.id.btn_find);


        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());


        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        }else { // Google Play Services are available

            // Getting reference to the SupportMapFragment
            SupportMapFragment fragment = ( SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting Google Map
            mGoogleMap = fragment.getMap();

            // Enabling MyLocation in Google Map
            mGoogleMap.setMyLocationEnabled(true);



            // Getting LocationManager object from System Service LOCATION_SERVICE
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

            // Creating a criteria object to retrieve provider
            Criteria criteria = new Criteria();

            // Getting the name of the best provider
            String provider = locationManager.getBestProvider(criteria, true);

            // Getting Current Location From GPS
            Location location = locationManager.getLastKnownLocation(provider);

            if(location!=null){
                    onLocationChanged(location);
            }

            locationManager.requestLocationUpdates(provider, 20000, 0, this);



            mGoogleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

                @Override
                public void onInfoWindowClick(Marker arg0) {
                    Intent intent = new Intent(getBaseContext(), PlaceDetailsActivity.class);
                    String reference = mMarkerPlaceLink.get(arg0.getId());
                    intent.putExtra("reference", reference);

                    // Starting the Place Details Activity
                    startActivity(intent);
                }
            });



            // Setting click event lister for the find button
            btnFind.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {   


                    int selectedPosition = mSprPlaceType.getSelectedItemPosition();
                    String type = mPlaceType[selectedPosition];


                    StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
                    sb.append("location="+mLatitude+","+mLongitude);
                    sb.append("&radius=5000");
                    sb.append("&types="+type);
                    sb.append("&sensor=true");
                    sb.append("&key=AIzaSyB6f_n3Z9877pSGkV6XhHXsJtfCmetJqCM");


                    // Creating a new non-ui thread task to download Google place json data 
                    PlacesTask placesTask = new PlacesTask();                                   

                    // Invokes the "doInBackground()" method of the class PlaceTask
                    placesTask.execute(sb.toString());

                }
            });

        }       

    }

    /** A method to download json data from url */
    private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
                URL url = new URL(strUrl);                


                // Creating an http connection to communicate with url 
                urlConnection = (HttpURLConnection) url.openConnection();                

                // Connecting to url 
                urlConnection.connect();                

                // Reading data from url 
                iStream = urlConnection.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

                StringBuffer sb  = new StringBuffer();

                String line = "";
                while( ( line = br.readLine())  != null){
                        sb.append(line);
                }

                data = sb.toString();

                br.close();

        }catch(Exception e){
                Log.d("Exception while downloading url", e.toString());
        }finally{
                iStream.close();
                urlConnection.disconnect();
        }

        return data;
    }         


    /** A class, to download Google Places */
    private class PlacesTask extends AsyncTask<String, Integer, String>{

        String data = null;

        // Invoked by execute() method of this object
        @Override
        protected String doInBackground(String... url) {
            try{
                data = downloadUrl(url[0]);
            }catch(Exception e){
                 Log.d("Background Task",e.toString());
            }
            return data;
        }

        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(String result){            
            ParserTask parserTask = new ParserTask();

            // Start parsing the Google places in JSON format
            // Invokes the "doInBackground()" method of the class ParseTask
            parserTask.execute(result);
        }

    }

    /** A class to parse the Google Places in JSON format */
    private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{

        JSONObject jObject;

        // Invoked by execute() method of this object
        @Override
        protected List<HashMap<String,String>> doInBackground(String... jsonData) {

            List<HashMap<String, String>> places = null;            
            PlaceJSONParser placeJsonParser = new PlaceJSONParser();

            try{
                jObject = new JSONObject(jsonData[0]);

                /** Getting the parsed data as a List construct */
                places = placeJsonParser.parse(jObject);

            }catch(Exception e){
                    Log.d("Exception",e.toString());
            }
            return places;
        }

        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(List<HashMap<String,String>> list){            

            // Clears all the existing markers 
            mGoogleMap.clear();

            for(int i=0;i<list.size();i++){

                // Creating a marker
                MarkerOptions markerOptions = new MarkerOptions()
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.pin));

                // Getting a place from the places list
                HashMap<String, String> hmPlace = list.get(i);

                // Getting latitude of the place
                double lat = Double.parseDouble(hmPlace.get("lat"));                

                // Getting longitude of the place
                double lng = Double.parseDouble(hmPlace.get("lng"));

                // Getting name
                String name = hmPlace.get("place_name");

                // Getting vicinity
                String vicinity = hmPlace.get("vicinity");

                LatLng latLng = new LatLng(lat, lng);

                // Setting the position for the marker
                markerOptions.position(latLng);

                // Setting the title for the marker. 
                //This will be displayed on taping the marker
                markerOptions.title(name + " : " + vicinity);   
                markerOptions.snippet("Click here for more info...");

                // Placing a marker on the touched position
                Marker m = mGoogleMap.addMarker(markerOptions);             

              // mGoogleMap.setInfoWindowAdapter(new MyInfoWindowAdapter(name,
                      //  vicinity));

                // Linking Marker id and place reference
                mMarkerPlaceLink.put(m.getId(), hmPlace.get("reference"));              


            }       

        }

    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onLocationChanged(Location location) {
        mLatitude = location.getLatitude();
        mLongitude = location.getLongitude();
        LatLng latLng = new LatLng(mLatitude, mLongitude);

        mGoogleMap.addMarker (new MarkerOptions()
        .title ("You are here")
        .snippet("Current location")
        .position(latLng)
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.gps)
                        ));

        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));


    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub      
    }
}
package com.example.mobiletourismapp;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.util.HashMap;
导入java.util.List;
导入org.json.JSONObject;
导入android.animation.ValueAnimator;
导入android.app.Dialog;
导入android.content.Intent;
导入android.graphics.Color;
导入android.location.Criteria;
导入android.location.location;
导入android.location.LocationListener;
导入android.location.LocationManager;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.support.v4.app.FragmentActivity;
导入android.util.Log;
导入android.view.Menu;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.ArrayAdapter;
导入android.widget.Button;
导入android.widget.Spinner;
导入com.google.android.gms.common.ConnectionResult;
导入com.google.android.gms.common.GooglePlayServicesUtil;
导入com.google.android.gms.maps.CameraUpdateFactory;
导入com.google.android.gms.maps.GoogleMap;
导入com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
导入com.google.android.gms.maps.SupportMapFragment;
导入com.google.android.gms.maps.model.BitmapDescriptorFactory;
导入com.google.android.gms.maps.model.LatLng;
导入com.google.android.gms.maps.model.Marker;
导入com.google.android.gms.maps.model.MarkerOptions;
公共类MainActivity扩展FragmentActivity实现LocationListener{
谷歌地图;
微调器mSprPlaceType;
字符串[]mPlaceType=null;
字符串[]mPlaceTypeName=null;
双梯度=0;
双倍长度=0;
HashMap mMarkerPlaceLink=新HashMap();
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//位置类型数组
mPlaceType=getResources().getStringArray(R.array.place\u类型);
//地名类型名称数组
mPlaceTypeName=getResources().getStringArray(R.array.place\u type\u name);
//使用位置类型数组创建数组适配器
//填充微调器的步骤
ArrayAdapter=新的ArrayAdapter(这是android.R.layout.simple\u spinner\u dropdown\u项,mPlaceTypeName);
//获取对微调器的引用
mSprPlaceType=(微调器)findViewById(R.id.spr\u place\u type);
//在微调器上设置适配器以设置放置类型
mSprPlaceType.setAdapter(适配器);
按钮btnFind;
//获取“查找”按钮的引用
btnFind=(按钮)findviewbyd(R.id.btn\u find);
//获取Google Play可用性状态
int status=GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
如果(status!=ConnectionResult.SUCCESS){//Google Play服务不可用
int requestCode=10;
Dialog Dialog=GooglePlayServicesUtil.getErrorDialog(状态、此、请求代码);
dialog.show();
}其他{//Google Play服务可用
//获取对SupportMapFragment的引用
SupportMapFragment fragment=(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
//获取谷歌地图
mGoogleMap=fragment.getMap();
//在Google地图中启用MyLocation
mGoogleMap.setMyLocationEnabled(true);
//从系统服务位置\u服务获取LocationManager对象
LocationManager LocationManager=(LocationManager)getSystemService(LOCATION\u服务);
//创建条件对象以检索提供程序
标准=新标准();
//获取最佳提供商的名称
字符串提供程序=locationManager.getBestProvider(条件为true);
//从GPS获取当前位置
Location Location=locationManager.getLastKnownLocation(提供者);
如果(位置!=null){
onLocationChanged(位置);
}
locationManager.RequestLocationUpdate(提供程序,20000,0,此);
mGoogleMap.setOnInfoWindowClickListener(新的OnInfoWindowClickListener(){
@凌驾
公用无效信息窗口单击(标记arg0){
Intent Intent=new Intent(getBaseContext(),PlaceDetailsActivity.class);
字符串引用=mMarkerPlaceLink.get(arg0.getId());
意向。额外(“参考”,参考);
//正在启动“地点详细信息”活动
星触觉(意向);
}
});
//设置“查找”按钮的单击事件列表器
setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
int selectedPosition=mSprPlaceType.getSelectedItemPosition();
字符串类型=mPlaceType[selectedPosition];
StringBuilder sb=新的StringBuilder(“https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.追加(“位置=”+mLatitude+,“+mllongitude”);
sb.追加(“&radius=5000”);
sb.追加(“&types=“+type”);
sb.追加(“&sensor=true”);
sb.追加(“&key=AIzaSyB6f_n3Z9877pSGkV6XhHXsJtfCmetJqCM”);
//创建新的非ui线程任务以下载Googl
mGoogleMap.clear();