Android 获取JSON数据后如何向mapView添加多个管脚

Android 获取JSON数据后如何向mapView添加多个管脚,android,android-volley,android-mapview,Android,Android Volley,Android Mapview,我正在制作一个应用程序来显示最近的五个地铁站。我能够获取站点的名称,并用数据填充列表视图 我正在从API获取lng和lat,并希望使用这些坐标向地图添加管脚。我已经让地图工作,我可以显示一个引脚,但不能显示多个引脚。如果您能指出正确的方向,我们将不胜感激-请参阅下面的代码 public class nearMe extends AppCompatActivity implements OnMapReadyCallback { private MapView mapView; p

我正在制作一个应用程序来显示最近的五个地铁站。我能够获取站点的名称,并用数据填充列表视图

我正在从API获取lng和lat,并希望使用这些坐标向地图添加管脚。我已经让地图工作,我可以显示一个引脚,但不能显示多个引脚。如果您能指出正确的方向,我们将不胜感激-请参阅下面的代码

public class nearMe extends AppCompatActivity implements OnMapReadyCallback {

    private MapView mapView;
    public GoogleMap gmap;
    private static final String MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey";

    // Location Co-ordinates
    private String lat = "";
    private String lng = "";

    LocationManager locationManager;
    LocationListener locationListener;

    private List<Station> stationList = new ArrayList<>();
    private RecyclerView recyclerView;
    private stationAdapter mAdapter;

    /*   LOCATION STUFF     */
    @Override
    public void onRequestPermissionsResult(int requestCode,  String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            startListening();
        }
    }

    public void startListening() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        }
    }

    public void updateLocationInfo(Location location) {
        lat = "" + location.getLatitude();
        lng = "" + location.getLongitude();
    }


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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
      //  int id = item.getItemId();


        getNearestStations();
        Toast.makeText(this, "Location Updated!", Toast.LENGTH_SHORT).show();

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_near_me);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        mAdapter = new stationAdapter(stationList);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);

// onClick
        recyclerView.addOnItemTouchListener(new TouchListener(getApplicationContext(), recyclerView, new ClickListener() {
            @Override
            public void onClick(View view, int position) {
              // Toast.makeText(getApplicationContext(), stationList.get(position).getStation() + "", Toast.LENGTH_SHORT).show();

                String findStation = stationList.get(position).getStation();

              //  Toast.makeText(nearMe.this, bob, Toast.LENGTH_SHORT).show();

                Uri gmmIntentUri = Uri.parse("google.navigation:q="+findStation+"underground station+London&mode=w");
                Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
                mapIntent.setPackage("com.google.android.apps.maps");
                mapIntent.setFlags(mapIntent.FLAG_ACTIVITY_CLEAR_TOP);
                if (mapIntent.resolveActivity(getPackageManager()) != null) {
                    startActivity(mapIntent);
                }
            }


        }));

        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                updateLocationInfo(location);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onProviderDisabled(String provider) {
            }
        };

        if (Build.VERSION.SDK_INT < 23) {
            startListening();
        } else {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            } else {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
                Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

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

        // insert Stations in to recycler
        getNearestStations();

        //map
        Bundle mapViewBundle = null;
        if (savedInstanceState != null) {
            mapViewBundle = savedInstanceState.getBundle(MAP_VIEW_BUNDLE_KEY);
        }

        mapView = (MapView) findViewById(R.id.map_view);
        mapView.onCreate(mapViewBundle);
        mapView.getMapAsync(this);
    }

    // clear adapter before adding
    public void clear() {
        int size = this.stationList.size();
        this.stationList.clear();
        mAdapter.notifyItemRangeRemoved(0, size);
    }

    public void getNearestStations(){

        RequestQueue queue = Volley.newRequestQueue(this);
        String url = "https://transportapi.com/v3/uk/tube/stations/near.json?app_id=157c4895&app_key=091697cea8bae89519dd02ebb318fc51&lat=" + lat + "&lon=" + lng + "&rpp=5";

        final StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray jsonArray = jsonObject.getJSONArray("stations");

                    // Call 'Clear' method to clear mAdapter before adding new data
                    clear();
                    if (jsonArray.length() > 0) {

                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jObject = jsonArray.getJSONObject(i);

                            String station = jObject.getString("name");

                            Station newStation = new Station(station);
                            stationList.add(newStation);

                            mAdapter.notifyDataSetChanged();

                            double longitude = Double.parseDouble(lng);
                            double latitude = Double.parseDouble(lat);
                            gmap.addMarker(new MarkerOptions()
                                    .position(new LatLng(latitude, longitude))
                                    .title(station));

                        }
                    }else{
                        Station newStation = new Station("No stations near");
                        stationList.add(newStation);
                        mAdapter.notifyDataSetChanged();

                        // Show a diaog
                        AlertDialog alertDialog = new AlertDialog.Builder(nearMe.this).create();
                        alertDialog.setTitle("No Stations Found");
                        alertDialog.setMessage("You are either not in London or you have no network connectivity.");
                        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                }); alertDialog.show();
                    }
                } catch (JSONException e) { }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);
    }
// maps

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        Bundle mapViewBundle = outState.getBundle(MAP_VIEW_BUNDLE_KEY);
        if (mapViewBundle == null) {
            mapViewBundle = new Bundle();
            outState.putBundle(MAP_VIEW_BUNDLE_KEY, mapViewBundle);
        }
        mapView.onSaveInstanceState(mapViewBundle);
    }
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mapView.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mapView.onStop();
    }
    @Override
    protected void onPause() {
        mapView.onPause();
        super.onPause();
    }
    @Override
    protected void onDestroy() {
        mapView.onDestroy();
        super.onDestroy();
    }
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {




    }
}
public类nearMe扩展了AppCompatActivity在MapReadyCallback上的实现{
私有地图视图;
谷歌地图gmap;
私有静态最终字符串MAP\u VIEW\u BUNDLE\u KEY=“MapViewBundleKey”;
//位置坐标
私有字符串lat=“”;
私有字符串lng=“”;
地点经理地点经理;
LocationListener LocationListener;
private List stationList=new ArrayList();
私人回收站;
私人车站适配器;
/*位置信息*/
@凌驾
public void onRequestPermissionsResult(int-requestCode、字符串[]权限、int[]grantResults){
super.onRequestPermissionsResult(请求代码、权限、授权结果);
if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION\u已授予){
惊人的倾听();
}
}
公营机构{
if(ContextCompat.checkSelfPermission(此,Manifest.permission.ACCESS\u FINE\u位置)==PackageManager.permission\u已授予){
locationManager=(locationManager)this.getSystemService(Context.LOCATION\u服务);
}
}
公共void updateLocationInfo(位置){
lat=”“+位置。getLatitude();
lng=”“+location.getLongitude();
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(右菜单菜单位置,菜单);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//int id=item.getItemId();
获取最近的站点();
Toast.makeText(此“位置已更新!”,Toast.LENGTH_SHORT.show();
返回super.onOptionsItemSelected(项目);
}
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u near\u me);
recyclerView=(recyclerView)findViewById(R.id.recycler\u视图);
mAdapter=新stationAdapter(stationList);
RecyclerView.LayoutManager mLayoutManager=新的LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
setItemAnimator(新的DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
//onClick
addOnItemTouchListener(新的TouchListener(getApplicationContext(),recyclerView,新的ClickListener()){
@凌驾
公共void onClick(视图,int位置){
//Toast.makeText(getApplicationContext(),stationList.get(position).getStation()+“”,Toast.LENGTH_SHORT).show();
String findStation=stationList.get(位置).getStation();
//Toast.makeText(nearMe.this,bob,Toast.LENGTH_SHORT).show();
Uri gmmIntentUri=Uri.parse(“google.navigation:q=“+findStation+”地铁站+London&mode=w”);
Intent mapIntent=新的Intent(Intent.ACTION\u视图,gmminentUri);
setPackage(“com.google.android.apps.maps”);
mapIntent.setFlags(mapIntent.FLAG\u活动\u清除\u顶部);
if(mapIntent.RESOLVECTIVITY(getPackageManager())!=null){
星触觉(mapIntent);
}
}
}));
locationManager=(locationManager)this.getSystemService(Context.LOCATION\u服务);
locationListener=新locationListener(){
@凌驾
已更改位置上的公共无效(位置){
updateLocationInfo(位置);
}
@凌驾
public void onStatusChanged(字符串提供程序、int状态、Bundle extra){
}
@凌驾
公共无效onProviderEnabled(字符串提供程序){
}
@凌驾
公共无效onProviderDisabled(字符串提供程序){
}
};
如果(Build.VERSION.SDK_INT<23){
惊人的倾听();
}否则{
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予){
ActivityCompat.requestPermissions(这个新字符串[]{Manifest.permission.ACCESS\u FINE\u LOCATION},1);
}否则{
locationManager.RequestLocationUpdate(locationManager.GPS\提供程序,0,0,locationListener);
Location Location=locationManager.getLastKnownLocation(locationManager.GPS\U提供程序);
如果(位置!=null){
updateLocationInfo(位置);
}
}
}
//将站点插入到回收站
获取最近的站点();
//地图
Bundle mapViewBundle=null;
如果(savedInstanceState!=null){
mapViewBundle=savedInstanceState.getBundle(映射视图绑定键);
}
mapView=(mapView)findViewById(R.id.map\u视图);
onCreate(mapViewBundle);
getMapAsync(这个);
}
//添加前清除适配器
公共空间清除(){
int size=this.stationList.size();
this.stationList.clear();
mAdapter.notifyItemRangeRemoved(0,大小);
}
公共无效getNearestStations(){
RequestQueue=Volley.newRequestQueue(this);
字符串url=”https://transportapi.com/v3/uk/tube/stations/near.json?app_id=157c4895&app_key=091697cea8bae895
for(int i = 0 ; i < markers.size() ; i++ ) {

    createMarker(markers.get(i).getLatitude(), markers.get(i).getLongitude(), markers.get(i).getTitle(), markers.get(i).getSnippet(), markers.get(i).getIconResID());
}

...

protected Marker createMarker(double latitude, double longitude, String title, String snippet, int iconResID) {

    return googleMap.addMarker(new MarkerOptions()
            .position(new LatLng(latitude, longitude))
            .anchor(0.5f, 0.5f)
            .title(title)
            .snippet(snippet);
            .icon(BitmapDescriptorFactory.fromResource(iconResID)));
}